babylon.no-module.max.js 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196
  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. /**
  1242. * Gather the list of keyboard event types as constants.
  1243. */
  1244. var KeyboardEventTypes = /** @class */ (function () {
  1245. function KeyboardEventTypes() {
  1246. }
  1247. /**
  1248. * The keydown event is fired when a key becomes active (pressed).
  1249. */
  1250. KeyboardEventTypes.KEYDOWN = 0x01;
  1251. /**
  1252. * The keyup event is fired when a key has been released.
  1253. */
  1254. KeyboardEventTypes.KEYUP = 0x02;
  1255. return KeyboardEventTypes;
  1256. }());
  1257. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1258. /**
  1259. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1260. */
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. /**
  1263. * Instantiates a new keyboard info.
  1264. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1265. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1266. * @param event Defines the related dom event
  1267. */
  1268. function KeyboardInfo(
  1269. /**
  1270. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1271. */
  1272. type,
  1273. /**
  1274. * Defines the related dom event
  1275. */
  1276. event) {
  1277. this.type = type;
  1278. this.event = event;
  1279. }
  1280. return KeyboardInfo;
  1281. }());
  1282. BABYLON.KeyboardInfo = KeyboardInfo;
  1283. /**
  1284. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1285. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1286. */
  1287. var KeyboardInfoPre = /** @class */ (function (_super) {
  1288. __extends(KeyboardInfoPre, _super);
  1289. /**
  1290. * Instantiates a new keyboard pre info.
  1291. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfoPre(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. var _this = _super.call(this, type, event) || this;
  1305. _this.type = type;
  1306. _this.event = event;
  1307. _this.skipOnPointerObservable = false;
  1308. return _this;
  1309. }
  1310. return KeyboardInfoPre;
  1311. }(KeyboardInfo));
  1312. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1313. })(BABYLON || (BABYLON = {}));
  1314. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1315. var BABYLON;
  1316. (function (BABYLON) {
  1317. /**
  1318. * Gather the list of pointer event types as constants.
  1319. */
  1320. var PointerEventTypes = /** @class */ (function () {
  1321. function PointerEventTypes() {
  1322. }
  1323. /**
  1324. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1325. */
  1326. PointerEventTypes.POINTERDOWN = 0x01;
  1327. /**
  1328. * The pointerup event is fired when a pointer is no longer active.
  1329. */
  1330. PointerEventTypes.POINTERUP = 0x02;
  1331. /**
  1332. * The pointermove event is fired when a pointer changes coordinates.
  1333. */
  1334. PointerEventTypes.POINTERMOVE = 0x04;
  1335. /**
  1336. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1337. */
  1338. PointerEventTypes.POINTERWHEEL = 0x08;
  1339. /**
  1340. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1341. */
  1342. PointerEventTypes.POINTERPICK = 0x10;
  1343. /**
  1344. * The pointertap event is fired when a the object has been touched and released without drag.
  1345. */
  1346. PointerEventTypes.POINTERTAP = 0x20;
  1347. /**
  1348. * The pointertap event is fired when a the object has been touched and released twice without drag.
  1349. */
  1350. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1351. return PointerEventTypes;
  1352. }());
  1353. BABYLON.PointerEventTypes = PointerEventTypes;
  1354. /**
  1355. * Base class of pointer info types.
  1356. */
  1357. var PointerInfoBase = /** @class */ (function () {
  1358. /**
  1359. * Instantiates the base class of pointers info.
  1360. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1361. * @param event Defines the related dom event
  1362. */
  1363. function PointerInfoBase(
  1364. /**
  1365. * Defines the type of event (BABYLON.PointerEventTypes)
  1366. */
  1367. type,
  1368. /**
  1369. * Defines the related dom event
  1370. */
  1371. event) {
  1372. this.type = type;
  1373. this.event = event;
  1374. }
  1375. return PointerInfoBase;
  1376. }());
  1377. BABYLON.PointerInfoBase = PointerInfoBase;
  1378. /**
  1379. * This class is used to store pointer related info for the onPrePointerObservable event.
  1380. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1381. */
  1382. var PointerInfoPre = /** @class */ (function (_super) {
  1383. __extends(PointerInfoPre, _super);
  1384. /**
  1385. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1386. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1387. * @param event Defines the related dom event
  1388. * @param localX Defines the local x coordinates of the pointer when the event occured
  1389. * @param localY Defines the local y coordinates of the pointer when the event occured
  1390. */
  1391. function PointerInfoPre(type, event, localX, localY) {
  1392. var _this = _super.call(this, type, event) || this;
  1393. /**
  1394. * Ray from a pointer if availible (eg. 6dof controller)
  1395. */
  1396. _this.ray = null;
  1397. _this.skipOnPointerObservable = false;
  1398. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1399. return _this;
  1400. }
  1401. return PointerInfoPre;
  1402. }(PointerInfoBase));
  1403. BABYLON.PointerInfoPre = PointerInfoPre;
  1404. /**
  1405. * This type contains all the data related to a pointer event in Babylon.js.
  1406. * 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.
  1407. */
  1408. var PointerInfo = /** @class */ (function (_super) {
  1409. __extends(PointerInfo, _super);
  1410. /**
  1411. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1412. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1413. * @param event Defines the related dom event
  1414. * @param pickInfo Defines the picking info associated to the info (if any)\
  1415. */
  1416. function PointerInfo(type, event,
  1417. /**
  1418. * Defines the picking info associated to the info (if any)\
  1419. */
  1420. pickInfo) {
  1421. var _this = _super.call(this, type, event) || this;
  1422. _this.pickInfo = pickInfo;
  1423. return _this;
  1424. }
  1425. return PointerInfo;
  1426. }(PointerInfoBase));
  1427. BABYLON.PointerInfo = PointerInfo;
  1428. })(BABYLON || (BABYLON = {}));
  1429. //# sourceMappingURL=babylon.pointerEvents.js.map
  1430. var BABYLON;
  1431. (function (BABYLON) {
  1432. /**
  1433. * Constant used to convert a value to gamma space
  1434. * @ignorenaming
  1435. */
  1436. BABYLON.ToGammaSpace = 1 / 2.2;
  1437. /**
  1438. * Constant used to convert a value to linear space
  1439. * @ignorenaming
  1440. */
  1441. BABYLON.ToLinearSpace = 2.2;
  1442. /**
  1443. * Constant used to define the minimal number value in Babylon.js
  1444. * @ignorenaming
  1445. */
  1446. BABYLON.Epsilon = 0.001;
  1447. /**
  1448. * Class used to hold a RBG color
  1449. */
  1450. var Color3 = /** @class */ (function () {
  1451. /**
  1452. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1453. * @param r defines the red component (between 0 and 1, default is 0)
  1454. * @param g defines the green component (between 0 and 1, default is 0)
  1455. * @param b defines the blue component (between 0 and 1, default is 0)
  1456. */
  1457. function Color3(
  1458. /**
  1459. * Defines the red component (between 0 and 1, default is 0)
  1460. */
  1461. r,
  1462. /**
  1463. * Defines the green component (between 0 and 1, default is 0)
  1464. */
  1465. g,
  1466. /**
  1467. * Defines the blue component (between 0 and 1, default is 0)
  1468. */
  1469. b) {
  1470. if (r === void 0) { r = 0; }
  1471. if (g === void 0) { g = 0; }
  1472. if (b === void 0) { b = 0; }
  1473. this.r = r;
  1474. this.g = g;
  1475. this.b = b;
  1476. }
  1477. /**
  1478. * Creates a string with the Color3 current values
  1479. * @returns the string representation of the Color3 object
  1480. */
  1481. Color3.prototype.toString = function () {
  1482. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1483. };
  1484. /**
  1485. * Returns the string "Color3"
  1486. * @returns "Color3"
  1487. */
  1488. Color3.prototype.getClassName = function () {
  1489. return "Color3";
  1490. };
  1491. /**
  1492. * Compute the Color3 hash code
  1493. * @returns an unique number that can be used to hash Color3 objects
  1494. */
  1495. Color3.prototype.getHashCode = function () {
  1496. var hash = this.r || 0;
  1497. hash = (hash * 397) ^ (this.g || 0);
  1498. hash = (hash * 397) ^ (this.b || 0);
  1499. return hash;
  1500. };
  1501. // Operators
  1502. /**
  1503. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1504. * @param array defines the array where to store the r,g,b components
  1505. * @param index defines an optional index in the target array to define where to start storing values
  1506. * @returns the current Color3 object
  1507. */
  1508. Color3.prototype.toArray = function (array, index) {
  1509. if (index === undefined) {
  1510. index = 0;
  1511. }
  1512. array[index] = this.r;
  1513. array[index + 1] = this.g;
  1514. array[index + 2] = this.b;
  1515. return this;
  1516. };
  1517. /**
  1518. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1519. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1520. * @returns a new {BABYLON.Color4} object
  1521. */
  1522. Color3.prototype.toColor4 = function (alpha) {
  1523. if (alpha === void 0) { alpha = 1; }
  1524. return new Color4(this.r, this.g, this.b, alpha);
  1525. };
  1526. /**
  1527. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1528. * @returns the new array
  1529. */
  1530. Color3.prototype.asArray = function () {
  1531. var result = new Array();
  1532. this.toArray(result, 0);
  1533. return result;
  1534. };
  1535. /**
  1536. * Returns the luminance value
  1537. * @returns a float value
  1538. */
  1539. Color3.prototype.toLuminance = function () {
  1540. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1541. };
  1542. /**
  1543. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1544. * @param otherColor defines the second operand
  1545. * @returns the new Color3 object
  1546. */
  1547. Color3.prototype.multiply = function (otherColor) {
  1548. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1549. };
  1550. /**
  1551. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1552. * @param otherColor defines the second operand
  1553. * @param result defines the Color3 object where to store the result
  1554. * @returns the current Color3
  1555. */
  1556. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1557. result.r = this.r * otherColor.r;
  1558. result.g = this.g * otherColor.g;
  1559. result.b = this.b * otherColor.b;
  1560. return this;
  1561. };
  1562. /**
  1563. * Determines equality between Color3 objects
  1564. * @param otherColor defines the second operand
  1565. * @returns true if the rgb values are equal to the given ones
  1566. */
  1567. Color3.prototype.equals = function (otherColor) {
  1568. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1569. };
  1570. /**
  1571. * Determines equality between the current Color3 object and a set of r,b,g values
  1572. * @param r defines the red component to check
  1573. * @param g defines the green component to check
  1574. * @param b defines the blue component to check
  1575. * @returns true if the rgb values are equal to the given ones
  1576. */
  1577. Color3.prototype.equalsFloats = function (r, g, b) {
  1578. return this.r === r && this.g === g && this.b === b;
  1579. };
  1580. /**
  1581. * Multiplies in place each rgb value by scale
  1582. * @param scale defines the scaling factor
  1583. * @returns the updated Color3
  1584. */
  1585. Color3.prototype.scale = function (scale) {
  1586. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1587. };
  1588. /**
  1589. * Multiplies the rgb values by scale and stores the result into "result"
  1590. * @param scale defines the scaling factor
  1591. * @param result defines the Color3 object where to store the result
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.scaleToRef = function (scale, result) {
  1595. result.r = this.r * scale;
  1596. result.g = this.g * scale;
  1597. result.b = this.b * scale;
  1598. return this;
  1599. };
  1600. /**
  1601. * Scale the current Color3 values by a factor and add the result to a given Color3
  1602. * @param scale defines the scale factor
  1603. * @param result defines color to store the result into
  1604. * @returns the unmodified current Color3
  1605. */
  1606. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1607. result.r += this.r * scale;
  1608. result.g += this.g * scale;
  1609. result.b += this.b * scale;
  1610. return this;
  1611. };
  1612. /**
  1613. * Clamps the rgb values by the min and max values and stores the result into "result"
  1614. * @param min defines minimum clamping value (default is 0)
  1615. * @param max defines maximum clamping value (default is 1)
  1616. * @param result defines color to store the result into
  1617. * @returns the original Color3
  1618. */
  1619. Color3.prototype.clampToRef = function (min, max, result) {
  1620. if (min === void 0) { min = 0; }
  1621. if (max === void 0) { max = 1; }
  1622. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1623. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1624. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1625. return this;
  1626. };
  1627. /**
  1628. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1629. * @param otherColor defines the second operand
  1630. * @returns the new Color3
  1631. */
  1632. Color3.prototype.add = function (otherColor) {
  1633. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1634. };
  1635. /**
  1636. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1637. * @param otherColor defines the second operand
  1638. * @param result defines Color3 object to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.addToRef = function (otherColor, result) {
  1642. result.r = this.r + otherColor.r;
  1643. result.g = this.g + otherColor.g;
  1644. result.b = this.b + otherColor.b;
  1645. return this;
  1646. };
  1647. /**
  1648. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1649. * @param otherColor defines the second operand
  1650. * @returns the new Color3
  1651. */
  1652. Color3.prototype.subtract = function (otherColor) {
  1653. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1654. };
  1655. /**
  1656. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1657. * @param otherColor defines the second operand
  1658. * @param result defines Color3 object to store the result into
  1659. * @returns the unmodified current Color3
  1660. */
  1661. Color3.prototype.subtractToRef = function (otherColor, result) {
  1662. result.r = this.r - otherColor.r;
  1663. result.g = this.g - otherColor.g;
  1664. result.b = this.b - otherColor.b;
  1665. return this;
  1666. };
  1667. /**
  1668. * Copy the current object
  1669. * @returns a new Color3 copied the current one
  1670. */
  1671. Color3.prototype.clone = function () {
  1672. return new Color3(this.r, this.g, this.b);
  1673. };
  1674. /**
  1675. * Copies the rgb values from the source in the current Color3
  1676. * @param source defines the source Color3 object
  1677. * @returns the updated Color3 object
  1678. */
  1679. Color3.prototype.copyFrom = function (source) {
  1680. this.r = source.r;
  1681. this.g = source.g;
  1682. this.b = source.b;
  1683. return this;
  1684. };
  1685. /**
  1686. * Updates the Color3 rgb values from the given floats
  1687. * @param r defines the red component to read from
  1688. * @param g defines the green component to read from
  1689. * @param b defines the blue component to read from
  1690. * @returns the current Color3 object
  1691. */
  1692. Color3.prototype.copyFromFloats = function (r, g, b) {
  1693. this.r = r;
  1694. this.g = g;
  1695. this.b = b;
  1696. return this;
  1697. };
  1698. /**
  1699. * Updates the Color3 rgb values from the given floats
  1700. * @param r defines the red component to read from
  1701. * @param g defines the green component to read from
  1702. * @param b defines the blue component to read from
  1703. * @returns the current Color3 object
  1704. */
  1705. Color3.prototype.set = function (r, g, b) {
  1706. return this.copyFromFloats(r, g, b);
  1707. };
  1708. /**
  1709. * Compute the Color3 hexadecimal code as a string
  1710. * @returns a string containing the hexadecimal representation of the Color3 object
  1711. */
  1712. Color3.prototype.toHexString = function () {
  1713. var intR = (this.r * 255) | 0;
  1714. var intG = (this.g * 255) | 0;
  1715. var intB = (this.b * 255) | 0;
  1716. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1717. };
  1718. /**
  1719. * Computes a new Color3 converted from the current one to linear space
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.prototype.toLinearSpace = function () {
  1723. var convertedColor = new Color3();
  1724. this.toLinearSpaceToRef(convertedColor);
  1725. return convertedColor;
  1726. };
  1727. /**
  1728. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1729. * @param convertedColor defines the Color3 object where to store the linear space version
  1730. * @returns the unmodified Color3
  1731. */
  1732. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1733. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1734. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1735. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1736. return this;
  1737. };
  1738. /**
  1739. * Computes a new Color3 converted from the current one to gamma space
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.prototype.toGammaSpace = function () {
  1743. var convertedColor = new Color3();
  1744. this.toGammaSpaceToRef(convertedColor);
  1745. return convertedColor;
  1746. };
  1747. /**
  1748. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1749. * @param convertedColor defines the Color3 object where to store the gamma space version
  1750. * @returns the unmodified Color3
  1751. */
  1752. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1753. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1754. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1755. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1756. return this;
  1757. };
  1758. // Statics
  1759. /**
  1760. * Creates a new Color3 from the string containing valid hexadecimal values
  1761. * @param hex defines a string containing valid hexadecimal values
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.FromHexString = function (hex) {
  1765. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1766. return new Color3(0, 0, 0);
  1767. }
  1768. var r = parseInt(hex.substring(1, 3), 16);
  1769. var g = parseInt(hex.substring(3, 5), 16);
  1770. var b = parseInt(hex.substring(5, 7), 16);
  1771. return Color3.FromInts(r, g, b);
  1772. };
  1773. /**
  1774. * Creates a new Vector3 from the starting index of the given array
  1775. * @param array defines the source array
  1776. * @param offset defines an offset in the source array
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.FromArray = function (array, offset) {
  1780. if (offset === void 0) { offset = 0; }
  1781. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1782. };
  1783. /**
  1784. * Creates a new Color3 from integer values (< 256)
  1785. * @param r defines the red component to read from (value between 0 and 255)
  1786. * @param g defines the green component to read from (value between 0 and 255)
  1787. * @param b defines the blue component to read from (value between 0 and 255)
  1788. * @returns a new Color3 object
  1789. */
  1790. Color3.FromInts = function (r, g, b) {
  1791. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1792. };
  1793. /**
  1794. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1795. * @param start defines the start Color3 value
  1796. * @param end defines the end Color3 value
  1797. * @param amount defines the gradient value between start and end
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Lerp = function (start, end, amount) {
  1801. var result = new Color3(0.0, 0.0, 0.0);
  1802. Color3.LerpToRef(start, end, amount, result);
  1803. return result;
  1804. };
  1805. /**
  1806. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1807. * @param left defines the start value
  1808. * @param right defines the end value
  1809. * @param amount defines the gradient factor
  1810. * @param result defines the Color3 object where to store the result
  1811. */
  1812. Color3.LerpToRef = function (left, right, amount, result) {
  1813. result.r = left.r + ((right.r - left.r) * amount);
  1814. result.g = left.g + ((right.g - left.g) * amount);
  1815. result.b = left.b + ((right.b - left.b) * amount);
  1816. };
  1817. /**
  1818. * Returns a Color3 value containing a red color
  1819. * @returns a new Color3 object
  1820. */
  1821. Color3.Red = function () { return new Color3(1, 0, 0); };
  1822. /**
  1823. * Returns a Color3 value containing a green color
  1824. * @returns a new Color3 object
  1825. */
  1826. Color3.Green = function () { return new Color3(0, 1, 0); };
  1827. /**
  1828. * Returns a Color3 value containing a blue color
  1829. * @returns a new Color3 object
  1830. */
  1831. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1832. /**
  1833. * Returns a Color3 value containing a black color
  1834. * @returns a new Color3 object
  1835. */
  1836. Color3.Black = function () { return new Color3(0, 0, 0); };
  1837. /**
  1838. * Returns a Color3 value containing a white color
  1839. * @returns a new Color3 object
  1840. */
  1841. Color3.White = function () { return new Color3(1, 1, 1); };
  1842. /**
  1843. * Returns a Color3 value containing a purple color
  1844. * @returns a new Color3 object
  1845. */
  1846. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1847. /**
  1848. * Returns a Color3 value containing a magenta color
  1849. * @returns a new Color3 object
  1850. */
  1851. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1852. /**
  1853. * Returns a Color3 value containing a yellow color
  1854. * @returns a new Color3 object
  1855. */
  1856. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1857. /**
  1858. * Returns a Color3 value containing a gray color
  1859. * @returns a new Color3 object
  1860. */
  1861. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1862. /**
  1863. * Returns a Color3 value containing a teal color
  1864. * @returns a new Color3 object
  1865. */
  1866. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1867. /**
  1868. * Returns a Color3 value containing a random color
  1869. * @returns a new Color3 object
  1870. */
  1871. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1872. return Color3;
  1873. }());
  1874. BABYLON.Color3 = Color3;
  1875. /**
  1876. * Class used to hold a RBGA color
  1877. */
  1878. var Color4 = /** @class */ (function () {
  1879. /**
  1880. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1881. * @param r defines the red component (between 0 and 1, default is 0)
  1882. * @param g defines the green component (between 0 and 1, default is 0)
  1883. * @param b defines the blue component (between 0 and 1, default is 0)
  1884. * @param a defines the alpha component (between 0 and 1, default is 1)
  1885. */
  1886. function Color4(
  1887. /**
  1888. * Defines the red component (between 0 and 1, default is 0)
  1889. */
  1890. r,
  1891. /**
  1892. * Defines the green component (between 0 and 1, default is 0)
  1893. */
  1894. g,
  1895. /**
  1896. * Defines the blue component (between 0 and 1, default is 0)
  1897. */
  1898. b,
  1899. /**
  1900. * Defines the alpha component (between 0 and 1, default is 1)
  1901. */
  1902. a) {
  1903. if (r === void 0) { r = 0; }
  1904. if (g === void 0) { g = 0; }
  1905. if (b === void 0) { b = 0; }
  1906. if (a === void 0) { a = 1; }
  1907. this.r = r;
  1908. this.g = g;
  1909. this.b = b;
  1910. this.a = a;
  1911. }
  1912. // Operators
  1913. /**
  1914. * Adds in place the given Color4 values to the current Color4 object
  1915. * @param right defines the second operand
  1916. * @returns the current updated Color4 object
  1917. */
  1918. Color4.prototype.addInPlace = function (right) {
  1919. this.r += right.r;
  1920. this.g += right.g;
  1921. this.b += right.b;
  1922. this.a += right.a;
  1923. return this;
  1924. };
  1925. /**
  1926. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1927. * @returns the new array
  1928. */
  1929. Color4.prototype.asArray = function () {
  1930. var result = new Array();
  1931. this.toArray(result, 0);
  1932. return result;
  1933. };
  1934. /**
  1935. * Stores from the starting index in the given array the Color4 successive values
  1936. * @param array defines the array where to store the r,g,b components
  1937. * @param index defines an optional index in the target array to define where to start storing values
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.toArray = function (array, index) {
  1941. if (index === undefined) {
  1942. index = 0;
  1943. }
  1944. array[index] = this.r;
  1945. array[index + 1] = this.g;
  1946. array[index + 2] = this.b;
  1947. array[index + 3] = this.a;
  1948. return this;
  1949. };
  1950. /**
  1951. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1952. * @param right defines the second operand
  1953. * @returns a new Color4 object
  1954. */
  1955. Color4.prototype.add = function (right) {
  1956. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1957. };
  1958. /**
  1959. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1960. * @param right defines the second operand
  1961. * @returns a new Color4 object
  1962. */
  1963. Color4.prototype.subtract = function (right) {
  1964. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1965. };
  1966. /**
  1967. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1968. * @param right defines the second operand
  1969. * @param result defines the Color4 object where to store the result
  1970. * @returns the current Color4 object
  1971. */
  1972. Color4.prototype.subtractToRef = function (right, result) {
  1973. result.r = this.r - right.r;
  1974. result.g = this.g - right.g;
  1975. result.b = this.b - right.b;
  1976. result.a = this.a - right.a;
  1977. return this;
  1978. };
  1979. /**
  1980. * Creates a new Color4 with the current Color4 values multiplied by scale
  1981. * @param scale defines the scaling factor to apply
  1982. * @returns a new Color4 object
  1983. */
  1984. Color4.prototype.scale = function (scale) {
  1985. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1986. };
  1987. /**
  1988. * Multiplies the current Color4 values by scale and stores the result in "result"
  1989. * @param scale defines the scaling factor to apply
  1990. * @param result defines the Color4 object where to store the result
  1991. * @returns the current unmodified Color4
  1992. */
  1993. Color4.prototype.scaleToRef = function (scale, result) {
  1994. result.r = this.r * scale;
  1995. result.g = this.g * scale;
  1996. result.b = this.b * scale;
  1997. result.a = this.a * scale;
  1998. return this;
  1999. };
  2000. /**
  2001. * Scale the current Color4 values by a factor and add the result to a given Color4
  2002. * @param scale defines the scale factor
  2003. * @param result defines the Color4 object where to store the result
  2004. * @returns the unmodified current Color4
  2005. */
  2006. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2007. result.r += this.r * scale;
  2008. result.g += this.g * scale;
  2009. result.b += this.b * scale;
  2010. result.a += this.a * scale;
  2011. return this;
  2012. };
  2013. /**
  2014. * Clamps the rgb values by the min and max values and stores the result into "result"
  2015. * @param min defines minimum clamping value (default is 0)
  2016. * @param max defines maximum clamping value (default is 1)
  2017. * @param result defines color to store the result into.
  2018. * @returns the cuurent Color4
  2019. */
  2020. Color4.prototype.clampToRef = function (min, max, result) {
  2021. if (min === void 0) { min = 0; }
  2022. if (max === void 0) { max = 1; }
  2023. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2024. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2025. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2026. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2027. return this;
  2028. };
  2029. /**
  2030. * Multipy an Color4 value by another and return a new Color4 object
  2031. * @param color defines the Color4 value to multiply by
  2032. * @returns a new Color4 object
  2033. */
  2034. Color4.prototype.multiply = function (color) {
  2035. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2036. };
  2037. /**
  2038. * Multipy a Color4 value by another and push the result in a reference value
  2039. * @param color defines the Color4 value to multiply by
  2040. * @param result defines the Color4 to fill the result in
  2041. * @returns the result Color4
  2042. */
  2043. Color4.prototype.multiplyToRef = function (color, result) {
  2044. result.r = this.r * color.r;
  2045. result.g = this.g * color.g;
  2046. result.b = this.b * color.b;
  2047. result.a = this.a * color.a;
  2048. return result;
  2049. };
  2050. /**
  2051. * Creates a string with the Color4 current values
  2052. * @returns the string representation of the Color4 object
  2053. */
  2054. Color4.prototype.toString = function () {
  2055. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2056. };
  2057. /**
  2058. * Returns the string "Color4"
  2059. * @returns "Color4"
  2060. */
  2061. Color4.prototype.getClassName = function () {
  2062. return "Color4";
  2063. };
  2064. /**
  2065. * Compute the Color4 hash code
  2066. * @returns an unique number that can be used to hash Color4 objects
  2067. */
  2068. Color4.prototype.getHashCode = function () {
  2069. var hash = this.r || 0;
  2070. hash = (hash * 397) ^ (this.g || 0);
  2071. hash = (hash * 397) ^ (this.b || 0);
  2072. hash = (hash * 397) ^ (this.a || 0);
  2073. return hash;
  2074. };
  2075. /**
  2076. * Creates a new Color4 copied from the current one
  2077. * @returns a new Color4 object
  2078. */
  2079. Color4.prototype.clone = function () {
  2080. return new Color4(this.r, this.g, this.b, this.a);
  2081. };
  2082. /**
  2083. * Copies the given Color4 values into the current one
  2084. * @param source defines the source Color4 object
  2085. * @returns the current updated Color4 object
  2086. */
  2087. Color4.prototype.copyFrom = function (source) {
  2088. this.r = source.r;
  2089. this.g = source.g;
  2090. this.b = source.b;
  2091. this.a = source.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Copies the given float values into the current one
  2096. * @param r defines the red component to read from
  2097. * @param g defines the green component to read from
  2098. * @param b defines the blue component to read from
  2099. * @param a defines the alpha component to read from
  2100. * @returns the current updated Color4 object
  2101. */
  2102. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2103. this.r = r;
  2104. this.g = g;
  2105. this.b = b;
  2106. this.a = a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Copies the given float values into the current one
  2111. * @param r defines the red component to read from
  2112. * @param g defines the green component to read from
  2113. * @param b defines the blue component to read from
  2114. * @param a defines the alpha component to read from
  2115. * @returns the current updated Color4 object
  2116. */
  2117. Color4.prototype.set = function (r, g, b, a) {
  2118. return this.copyFromFloats(r, g, b, a);
  2119. };
  2120. /**
  2121. * Compute the Color4 hexadecimal code as a string
  2122. * @returns a string containing the hexadecimal representation of the Color4 object
  2123. */
  2124. Color4.prototype.toHexString = function () {
  2125. var intR = (this.r * 255) | 0;
  2126. var intG = (this.g * 255) | 0;
  2127. var intB = (this.b * 255) | 0;
  2128. var intA = (this.a * 255) | 0;
  2129. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2130. };
  2131. /**
  2132. * Computes a new Color4 converted from the current one to linear space
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.prototype.toLinearSpace = function () {
  2136. var convertedColor = new Color4();
  2137. this.toLinearSpaceToRef(convertedColor);
  2138. return convertedColor;
  2139. };
  2140. /**
  2141. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2142. * @param convertedColor defines the Color4 object where to store the linear space version
  2143. * @returns the unmodified Color4
  2144. */
  2145. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2146. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2147. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2148. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2149. convertedColor.a = this.a;
  2150. return this;
  2151. };
  2152. /**
  2153. * Computes a new Color4 converted from the current one to gamma space
  2154. * @returns a new Color4 object
  2155. */
  2156. Color4.prototype.toGammaSpace = function () {
  2157. var convertedColor = new Color4();
  2158. this.toGammaSpaceToRef(convertedColor);
  2159. return convertedColor;
  2160. };
  2161. /**
  2162. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2163. * @param convertedColor defines the Color4 object where to store the gamma space version
  2164. * @returns the unmodified Color4
  2165. */
  2166. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2167. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2168. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2169. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2170. convertedColor.a = this.a;
  2171. return this;
  2172. };
  2173. // Statics
  2174. /**
  2175. * Creates a new Color4 from the string containing valid hexadecimal values
  2176. * @param hex defines a string containing valid hexadecimal values
  2177. * @returns a new Color4 object
  2178. */
  2179. Color4.FromHexString = function (hex) {
  2180. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2181. return new Color4(0.0, 0.0, 0.0, 0.0);
  2182. }
  2183. var r = parseInt(hex.substring(1, 3), 16);
  2184. var g = parseInt(hex.substring(3, 5), 16);
  2185. var b = parseInt(hex.substring(5, 7), 16);
  2186. var a = parseInt(hex.substring(7, 9), 16);
  2187. return Color4.FromInts(r, g, b, a);
  2188. };
  2189. /**
  2190. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2191. * @param left defines the start value
  2192. * @param right defines the end value
  2193. * @param amount defines the gradient factor
  2194. * @returns a new Color4 object
  2195. */
  2196. Color4.Lerp = function (left, right, amount) {
  2197. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2198. Color4.LerpToRef(left, right, amount, result);
  2199. return result;
  2200. };
  2201. /**
  2202. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2203. * @param left defines the start value
  2204. * @param right defines the end value
  2205. * @param amount defines the gradient factor
  2206. * @param result defines the Color4 object where to store data
  2207. */
  2208. Color4.LerpToRef = function (left, right, amount, result) {
  2209. result.r = left.r + (right.r - left.r) * amount;
  2210. result.g = left.g + (right.g - left.g) * amount;
  2211. result.b = left.b + (right.b - left.b) * amount;
  2212. result.a = left.a + (right.a - left.a) * amount;
  2213. };
  2214. /**
  2215. * Creates a new Color4 from a Color3 and an alpha value
  2216. * @param color3 defines the source Color3 to read from
  2217. * @param alpha defines the alpha component (1.0 by default)
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.FromColor3 = function (color3, alpha) {
  2221. if (alpha === void 0) { alpha = 1.0; }
  2222. return new Color4(color3.r, color3.g, color3.b, alpha);
  2223. };
  2224. /**
  2225. * Creates a new Color4 from the starting index element of the given array
  2226. * @param array defines the source array to read from
  2227. * @param offset defines the offset in the source array
  2228. * @returns a new Color4 object
  2229. */
  2230. Color4.FromArray = function (array, offset) {
  2231. if (offset === void 0) { offset = 0; }
  2232. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2233. };
  2234. /**
  2235. * Creates a new Color3 from integer values (< 256)
  2236. * @param r defines the red component to read from (value between 0 and 255)
  2237. * @param g defines the green component to read from (value between 0 and 255)
  2238. * @param b defines the blue component to read from (value between 0 and 255)
  2239. * @param a defines the alpha component to read from (value between 0 and 255)
  2240. * @returns a new Color3 object
  2241. */
  2242. Color4.FromInts = function (r, g, b, a) {
  2243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2244. };
  2245. /**
  2246. * Check the content of a given array and convert it to an array containing RGBA data
  2247. * If the original array was already containing count * 4 values then it is returned directly
  2248. * @param colors defines the array to check
  2249. * @param count defines the number of RGBA data to expect
  2250. * @returns an array containing count * 4 values (RGBA)
  2251. */
  2252. Color4.CheckColors4 = function (colors, count) {
  2253. // Check if color3 was used
  2254. if (colors.length === count * 3) {
  2255. var colors4 = [];
  2256. for (var index = 0; index < colors.length; index += 3) {
  2257. var newIndex = (index / 3) * 4;
  2258. colors4[newIndex] = colors[index];
  2259. colors4[newIndex + 1] = colors[index + 1];
  2260. colors4[newIndex + 2] = colors[index + 2];
  2261. colors4[newIndex + 3] = 1.0;
  2262. }
  2263. return colors4;
  2264. }
  2265. return colors;
  2266. };
  2267. return Color4;
  2268. }());
  2269. BABYLON.Color4 = Color4;
  2270. /**
  2271. * Class representing a vector containing 2 coordinates
  2272. */
  2273. var Vector2 = /** @class */ (function () {
  2274. /**
  2275. * Creates a new Vector2 from the given x and y coordinates
  2276. * @param x defines the first coordinate
  2277. * @param y defines the second coordinate
  2278. */
  2279. function Vector2(
  2280. /** defines the first coordinate */
  2281. x,
  2282. /** defines the second coordinate */
  2283. y) {
  2284. if (x === void 0) { x = 0; }
  2285. if (y === void 0) { y = 0; }
  2286. this.x = x;
  2287. this.y = y;
  2288. }
  2289. /**
  2290. * Gets a string with the Vector2 coordinates
  2291. * @returns a string with the Vector2 coordinates
  2292. */
  2293. Vector2.prototype.toString = function () {
  2294. return "{X: " + this.x + " Y:" + this.y + "}";
  2295. };
  2296. /**
  2297. * Gets class name
  2298. * @returns the string "Vector2"
  2299. */
  2300. Vector2.prototype.getClassName = function () {
  2301. return "Vector2";
  2302. };
  2303. /**
  2304. * Gets current vector hash code
  2305. * @returns the Vector2 hash code as a number
  2306. */
  2307. Vector2.prototype.getHashCode = function () {
  2308. var hash = this.x || 0;
  2309. hash = (hash * 397) ^ (this.y || 0);
  2310. return hash;
  2311. };
  2312. // Operators
  2313. /**
  2314. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2315. * @param array defines the source array
  2316. * @param index defines the offset in source array
  2317. * @returns the current Vector2
  2318. */
  2319. Vector2.prototype.toArray = function (array, index) {
  2320. if (index === void 0) { index = 0; }
  2321. array[index] = this.x;
  2322. array[index + 1] = this.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Copy the current vector to an array
  2327. * @returns a new array with 2 elements: the Vector2 coordinates.
  2328. */
  2329. Vector2.prototype.asArray = function () {
  2330. var result = new Array();
  2331. this.toArray(result, 0);
  2332. return result;
  2333. };
  2334. /**
  2335. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2336. * @param source defines the source Vector2
  2337. * @returns the current updated Vector2
  2338. */
  2339. Vector2.prototype.copyFrom = function (source) {
  2340. this.x = source.x;
  2341. this.y = source.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Sets the Vector2 coordinates with the given floats
  2346. * @param x defines the first coordinate
  2347. * @param y defines the second coordinate
  2348. * @returns the current updated Vector2
  2349. */
  2350. Vector2.prototype.copyFromFloats = function (x, y) {
  2351. this.x = x;
  2352. this.y = y;
  2353. return this;
  2354. };
  2355. /**
  2356. * Sets the Vector2 coordinates with the given floats
  2357. * @param x defines the first coordinate
  2358. * @param y defines the second coordinate
  2359. * @returns the current updated Vector2
  2360. */
  2361. Vector2.prototype.set = function (x, y) {
  2362. return this.copyFromFloats(x, y);
  2363. };
  2364. /**
  2365. * Add another vector with the current one
  2366. * @param otherVector defines the other vector
  2367. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2368. */
  2369. Vector2.prototype.add = function (otherVector) {
  2370. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2371. };
  2372. /**
  2373. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @param result defines the target vector
  2376. * @returns the unmodified current Vector2
  2377. */
  2378. Vector2.prototype.addToRef = function (otherVector, result) {
  2379. result.x = this.x + otherVector.x;
  2380. result.y = this.y + otherVector.y;
  2381. return this;
  2382. };
  2383. /**
  2384. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2385. * @param otherVector defines the other vector
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.addInPlace = function (otherVector) {
  2389. this.x += otherVector.x;
  2390. this.y += otherVector.y;
  2391. return this;
  2392. };
  2393. /**
  2394. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2395. * @param otherVector defines the other vector
  2396. * @returns a new Vector2
  2397. */
  2398. Vector2.prototype.addVector3 = function (otherVector) {
  2399. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2400. };
  2401. /**
  2402. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2403. * @param otherVector defines the other vector
  2404. * @returns a new Vector2
  2405. */
  2406. Vector2.prototype.subtract = function (otherVector) {
  2407. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2408. };
  2409. /**
  2410. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2411. * @param otherVector defines the other vector
  2412. * @param result defines the target vector
  2413. * @returns the unmodified current Vector2
  2414. */
  2415. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2416. result.x = this.x - otherVector.x;
  2417. result.y = this.y - otherVector.y;
  2418. return this;
  2419. };
  2420. /**
  2421. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns the current updated Vector2
  2424. */
  2425. Vector2.prototype.subtractInPlace = function (otherVector) {
  2426. this.x -= otherVector.x;
  2427. this.y -= otherVector.y;
  2428. return this;
  2429. };
  2430. /**
  2431. * Multiplies in place the current Vector2 coordinates by the given ones
  2432. * @param otherVector defines the other vector
  2433. * @returns the current updated Vector2
  2434. */
  2435. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2436. this.x *= otherVector.x;
  2437. this.y *= otherVector.y;
  2438. return this;
  2439. };
  2440. /**
  2441. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2442. * @param otherVector defines the other vector
  2443. * @returns a new Vector2
  2444. */
  2445. Vector2.prototype.multiply = function (otherVector) {
  2446. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2447. };
  2448. /**
  2449. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2450. * @param otherVector defines the other vector
  2451. * @param result defines the target vector
  2452. * @returns the unmodified current Vector2
  2453. */
  2454. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2455. result.x = this.x * otherVector.x;
  2456. result.y = this.y * otherVector.y;
  2457. return this;
  2458. };
  2459. /**
  2460. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2461. * @param x defines the first coordinate
  2462. * @param y defines the second coordinate
  2463. * @returns a new Vector2
  2464. */
  2465. Vector2.prototype.multiplyByFloats = function (x, y) {
  2466. return new Vector2(this.x * x, this.y * y);
  2467. };
  2468. /**
  2469. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2470. * @param otherVector defines the other vector
  2471. * @returns a new Vector2
  2472. */
  2473. Vector2.prototype.divide = function (otherVector) {
  2474. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2475. };
  2476. /**
  2477. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2478. * @param otherVector defines the other vector
  2479. * @param result defines the target vector
  2480. * @returns the unmodified current Vector2
  2481. */
  2482. Vector2.prototype.divideToRef = function (otherVector, result) {
  2483. result.x = this.x / otherVector.x;
  2484. result.y = this.y / otherVector.y;
  2485. return this;
  2486. };
  2487. /**
  2488. * Divides the current Vector2 coordinates by the given ones
  2489. * @param otherVector defines the other vector
  2490. * @returns the current updated Vector2
  2491. */
  2492. Vector2.prototype.divideInPlace = function (otherVector) {
  2493. return this.divideToRef(otherVector, this);
  2494. };
  2495. /**
  2496. * Gets a new Vector2 with current Vector2 negated coordinates
  2497. * @returns a new Vector2
  2498. */
  2499. Vector2.prototype.negate = function () {
  2500. return new Vector2(-this.x, -this.y);
  2501. };
  2502. /**
  2503. * Multiply the Vector2 coordinates by scale
  2504. * @param scale defines the scaling factor
  2505. * @returns the current updated Vector2
  2506. */
  2507. Vector2.prototype.scaleInPlace = function (scale) {
  2508. this.x *= scale;
  2509. this.y *= scale;
  2510. return this;
  2511. };
  2512. /**
  2513. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2514. * @param scale defines the scaling factor
  2515. * @returns a new Vector2
  2516. */
  2517. Vector2.prototype.scale = function (scale) {
  2518. var result = new Vector2(0, 0);
  2519. this.scaleToRef(scale, result);
  2520. return result;
  2521. };
  2522. /**
  2523. * Scale the current Vector2 values by a factor to a given Vector2
  2524. * @param scale defines the scale factor
  2525. * @param result defines the Vector2 object where to store the result
  2526. * @returns the unmodified current Vector2
  2527. */
  2528. Vector2.prototype.scaleToRef = function (scale, result) {
  2529. result.x = this.x * scale;
  2530. result.y = this.y * scale;
  2531. return this;
  2532. };
  2533. /**
  2534. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2535. * @param scale defines the scale factor
  2536. * @param result defines the Vector2 object where to store the result
  2537. * @returns the unmodified current Vector2
  2538. */
  2539. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2540. result.x += this.x * scale;
  2541. result.y += this.y * scale;
  2542. return this;
  2543. };
  2544. /**
  2545. * Gets a boolean if two vectors are equals
  2546. * @param otherVector defines the other vector
  2547. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2548. */
  2549. Vector2.prototype.equals = function (otherVector) {
  2550. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2551. };
  2552. /**
  2553. * Gets a boolean if two vectors are equals (using an epsilon value)
  2554. * @param otherVector defines the other vector
  2555. * @param epsilon defines the minimal distance to consider equality
  2556. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2557. */
  2558. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2559. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2560. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2561. };
  2562. /**
  2563. * Gets a new Vector2 from current Vector2 floored values
  2564. * @returns a new Vector2
  2565. */
  2566. Vector2.prototype.floor = function () {
  2567. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2568. };
  2569. /**
  2570. * Gets a new Vector2 from current Vector2 floored values
  2571. * @returns a new Vector2
  2572. */
  2573. Vector2.prototype.fract = function () {
  2574. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2575. };
  2576. // Properties
  2577. /**
  2578. * Gets the length of the vector
  2579. * @returns the vector length (float)
  2580. */
  2581. Vector2.prototype.length = function () {
  2582. return Math.sqrt(this.x * this.x + this.y * this.y);
  2583. };
  2584. /**
  2585. * Gets the vector squared length
  2586. * @returns the vector squared length (float)
  2587. */
  2588. Vector2.prototype.lengthSquared = function () {
  2589. return (this.x * this.x + this.y * this.y);
  2590. };
  2591. // Methods
  2592. /**
  2593. * Normalize the vector
  2594. * @returns the current updated Vector2
  2595. */
  2596. Vector2.prototype.normalize = function () {
  2597. var len = this.length();
  2598. if (len === 0)
  2599. return this;
  2600. var num = 1.0 / len;
  2601. this.x *= num;
  2602. this.y *= num;
  2603. return this;
  2604. };
  2605. /**
  2606. * Gets a new Vector2 copied from the Vector2
  2607. * @returns a new Vector2
  2608. */
  2609. Vector2.prototype.clone = function () {
  2610. return new Vector2(this.x, this.y);
  2611. };
  2612. // Statics
  2613. /**
  2614. * Gets a new Vector2(0, 0)
  2615. * @returns a new Vector2
  2616. */
  2617. Vector2.Zero = function () {
  2618. return new Vector2(0, 0);
  2619. };
  2620. /**
  2621. * Gets a new Vector2(1, 1)
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.One = function () {
  2625. return new Vector2(1, 1);
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set from the given index element of the given array
  2629. * @param array defines the data source
  2630. * @param offset defines the offset in the data source
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.FromArray = function (array, offset) {
  2634. if (offset === void 0) { offset = 0; }
  2635. return new Vector2(array[offset], array[offset + 1]);
  2636. };
  2637. /**
  2638. * Sets "result" from the given index element of the given array
  2639. * @param array defines the data source
  2640. * @param offset defines the offset in the data source
  2641. * @param result defines the target vector
  2642. */
  2643. Vector2.FromArrayToRef = function (array, offset, result) {
  2644. result.x = array[offset];
  2645. result.y = array[offset + 1];
  2646. };
  2647. /**
  2648. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2649. * @param value1 defines 1st point of control
  2650. * @param value2 defines 2nd point of control
  2651. * @param value3 defines 3rd point of control
  2652. * @param value4 defines 4th point of control
  2653. * @param amount defines the interpolation factor
  2654. * @returns a new Vector2
  2655. */
  2656. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2657. var squared = amount * amount;
  2658. var cubed = amount * squared;
  2659. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2660. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2661. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2662. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2663. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2664. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * 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".
  2669. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2670. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2671. * @param value defines the value to clamp
  2672. * @param min defines the lower limit
  2673. * @param max defines the upper limit
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Clamp = function (value, min, max) {
  2677. var x = value.x;
  2678. x = (x > max.x) ? max.x : x;
  2679. x = (x < min.x) ? min.x : x;
  2680. var y = value.y;
  2681. y = (y > max.y) ? max.y : y;
  2682. y = (y < min.y) ? min.y : y;
  2683. return new Vector2(x, y);
  2684. };
  2685. /**
  2686. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2687. * @param value1 defines the 1st control point
  2688. * @param tangent1 defines the outgoing tangent
  2689. * @param value2 defines the 2nd control point
  2690. * @param tangent2 defines the incoming tangent
  2691. * @param amount defines the interpolation factor
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2695. var squared = amount * amount;
  2696. var cubed = amount * squared;
  2697. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2698. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2699. var part3 = (cubed - (2.0 * squared)) + amount;
  2700. var part4 = cubed - squared;
  2701. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2702. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2707. * @param start defines the start vector
  2708. * @param end defines the end vector
  2709. * @param amount defines the interpolation factor
  2710. * @returns a new Vector2
  2711. */
  2712. Vector2.Lerp = function (start, end, amount) {
  2713. var x = start.x + ((end.x - start.x) * amount);
  2714. var y = start.y + ((end.y - start.y) * amount);
  2715. return new Vector2(x, y);
  2716. };
  2717. /**
  2718. * Gets the dot product of the vector "left" and the vector "right"
  2719. * @param left defines first vector
  2720. * @param right defines second vector
  2721. * @returns the dot product (float)
  2722. */
  2723. Vector2.Dot = function (left, right) {
  2724. return left.x * right.x + left.y * right.y;
  2725. };
  2726. /**
  2727. * Returns a new Vector2 equal to the normalized given vector
  2728. * @param vector defines the vector to normalize
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Normalize = function (vector) {
  2732. var newVector = vector.clone();
  2733. newVector.normalize();
  2734. return newVector;
  2735. };
  2736. /**
  2737. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2738. * @param left defines 1st vector
  2739. * @param right defines 2nd vector
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Minimize = function (left, right) {
  2743. var x = (left.x < right.x) ? left.x : right.x;
  2744. var y = (left.y < right.y) ? left.y : right.y;
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2749. * @param left defines 1st vector
  2750. * @param right defines 2nd vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Maximize = function (left, right) {
  2754. var x = (left.x > right.x) ? left.x : right.x;
  2755. var y = (left.y > right.y) ? left.y : right.y;
  2756. return new Vector2(x, y);
  2757. };
  2758. /**
  2759. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2760. * @param vector defines the vector to transform
  2761. * @param transformation defines the matrix to apply
  2762. * @returns a new Vector2
  2763. */
  2764. Vector2.Transform = function (vector, transformation) {
  2765. var r = Vector2.Zero();
  2766. Vector2.TransformToRef(vector, transformation, r);
  2767. return r;
  2768. };
  2769. /**
  2770. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2771. * @param vector defines the vector to transform
  2772. * @param transformation defines the matrix to apply
  2773. * @param result defines the target vector
  2774. */
  2775. Vector2.TransformToRef = function (vector, transformation, result) {
  2776. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2777. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2778. result.x = x;
  2779. result.y = y;
  2780. };
  2781. /**
  2782. * Determines if a given vector is included in a triangle
  2783. * @param p defines the vector to test
  2784. * @param p0 defines 1st triangle point
  2785. * @param p1 defines 2nd triangle point
  2786. * @param p2 defines 3rd triangle point
  2787. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2788. */
  2789. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2790. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2791. var sign = a < 0 ? -1 : 1;
  2792. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2793. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2794. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2795. };
  2796. /**
  2797. * Gets the distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the distance between vectors
  2801. */
  2802. Vector2.Distance = function (value1, value2) {
  2803. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2804. };
  2805. /**
  2806. * Returns the squared distance between the vectors "value1" and "value2"
  2807. * @param value1 defines first vector
  2808. * @param value2 defines second vector
  2809. * @returns the squared distance between vectors
  2810. */
  2811. Vector2.DistanceSquared = function (value1, value2) {
  2812. var x = value1.x - value2.x;
  2813. var y = value1.y - value2.y;
  2814. return (x * x) + (y * y);
  2815. };
  2816. /**
  2817. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2818. * @param value1 defines first vector
  2819. * @param value2 defines second vector
  2820. * @returns a new Vector2
  2821. */
  2822. Vector2.Center = function (value1, value2) {
  2823. var center = value1.add(value2);
  2824. center.scaleInPlace(0.5);
  2825. return center;
  2826. };
  2827. /**
  2828. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2829. * @param p defines the middle point
  2830. * @param segA defines one point of the segment
  2831. * @param segB defines the other point of the segment
  2832. * @returns the shortest distance
  2833. */
  2834. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2835. var l2 = Vector2.DistanceSquared(segA, segB);
  2836. if (l2 === 0.0) {
  2837. return Vector2.Distance(p, segA);
  2838. }
  2839. var v = segB.subtract(segA);
  2840. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2841. var proj = segA.add(v.multiplyByFloats(t, t));
  2842. return Vector2.Distance(p, proj);
  2843. };
  2844. return Vector2;
  2845. }());
  2846. BABYLON.Vector2 = Vector2;
  2847. /**
  2848. * Classed used to store (x,y,z) vector representation
  2849. * A Vector3 is the main object used in 3D geometry
  2850. * It can represent etiher the coordinates of a point the space, either a direction
  2851. * Reminder: Babylon.js uses a left handed forward facing system
  2852. */
  2853. var Vector3 = /** @class */ (function () {
  2854. /**
  2855. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2856. * @param x defines the first coordinates (on X axis)
  2857. * @param y defines the second coordinates (on Y axis)
  2858. * @param z defines the third coordinates (on Z axis)
  2859. */
  2860. function Vector3(
  2861. /**
  2862. * Defines the first coordinates (on X axis)
  2863. */
  2864. x,
  2865. /**
  2866. * Defines the second coordinates (on Y axis)
  2867. */
  2868. y,
  2869. /**
  2870. * Defines the third coordinates (on Z axis)
  2871. */
  2872. z) {
  2873. if (x === void 0) { x = 0; }
  2874. if (y === void 0) { y = 0; }
  2875. if (z === void 0) { z = 0; }
  2876. this.x = x;
  2877. this.y = y;
  2878. this.z = z;
  2879. }
  2880. /**
  2881. * Creates a string representation of the Vector3
  2882. * @returns a string with the Vector3 coordinates.
  2883. */
  2884. Vector3.prototype.toString = function () {
  2885. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2886. };
  2887. /**
  2888. * Gets the class name
  2889. * @returns the string "Vector3"
  2890. */
  2891. Vector3.prototype.getClassName = function () {
  2892. return "Vector3";
  2893. };
  2894. /**
  2895. * Creates the Vector3 hash code
  2896. * @returns a number which tends to be unique between Vector3 instances
  2897. */
  2898. Vector3.prototype.getHashCode = function () {
  2899. var hash = this.x || 0;
  2900. hash = (hash * 397) ^ (this.y || 0);
  2901. hash = (hash * 397) ^ (this.z || 0);
  2902. return hash;
  2903. };
  2904. // Operators
  2905. /**
  2906. * Creates an array containing three elements : the coordinates of the Vector3
  2907. * @returns a new array of numbers
  2908. */
  2909. Vector3.prototype.asArray = function () {
  2910. var result = [];
  2911. this.toArray(result, 0);
  2912. return result;
  2913. };
  2914. /**
  2915. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2916. * @param array defines the destination array
  2917. * @param index defines the offset in the destination array
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.toArray = function (array, index) {
  2921. if (index === void 0) { index = 0; }
  2922. array[index] = this.x;
  2923. array[index + 1] = this.y;
  2924. array[index + 2] = this.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2929. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2930. */
  2931. Vector3.prototype.toQuaternion = function () {
  2932. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2933. };
  2934. /**
  2935. * Adds the given vector to the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.addInPlace = function (otherVector) {
  2940. this.x += otherVector.x;
  2941. this.y += otherVector.y;
  2942. this.z += otherVector.z;
  2943. return this;
  2944. };
  2945. /**
  2946. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2947. * @param otherVector defines the second operand
  2948. * @returns the resulting Vector3
  2949. */
  2950. Vector3.prototype.add = function (otherVector) {
  2951. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2952. };
  2953. /**
  2954. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2955. * @param otherVector defines the second operand
  2956. * @param result defines the Vector3 object where to store the result
  2957. * @returns the current Vector3
  2958. */
  2959. Vector3.prototype.addToRef = function (otherVector, result) {
  2960. result.x = this.x + otherVector.x;
  2961. result.y = this.y + otherVector.y;
  2962. result.z = this.z + otherVector.z;
  2963. return this;
  2964. };
  2965. /**
  2966. * Subtract the given vector from the current Vector3
  2967. * @param otherVector defines the second operand
  2968. * @returns the current updated Vector3
  2969. */
  2970. Vector3.prototype.subtractInPlace = function (otherVector) {
  2971. this.x -= otherVector.x;
  2972. this.y -= otherVector.y;
  2973. this.z -= otherVector.z;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2978. * @param otherVector defines the second operand
  2979. * @returns the resulting Vector3
  2980. */
  2981. Vector3.prototype.subtract = function (otherVector) {
  2982. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2983. };
  2984. /**
  2985. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2986. * @param otherVector defines the second operand
  2987. * @param result defines the Vector3 object where to store the result
  2988. * @returns the current Vector3
  2989. */
  2990. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2991. result.x = this.x - otherVector.x;
  2992. result.y = this.y - otherVector.y;
  2993. result.z = this.z - otherVector.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the resulting Vector3
  3002. */
  3003. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3004. return new Vector3(this.x - x, this.y - y, this.z - z);
  3005. };
  3006. /**
  3007. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3015. result.x = this.x - x;
  3016. result.y = this.y - y;
  3017. result.z = this.z - z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3022. * @returns a new Vector3
  3023. */
  3024. Vector3.prototype.negate = function () {
  3025. return new Vector3(-this.x, -this.y, -this.z);
  3026. };
  3027. /**
  3028. * Multiplies the Vector3 coordinates by the float "scale"
  3029. * @param scale defines the multiplier factor
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.scaleInPlace = function (scale) {
  3033. this.x *= scale;
  3034. this.y *= scale;
  3035. this.z *= scale;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3040. * @param scale defines the multiplier factor
  3041. * @returns a new Vector3
  3042. */
  3043. Vector3.prototype.scale = function (scale) {
  3044. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3045. };
  3046. /**
  3047. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3048. * @param scale defines the multiplier factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the current Vector3
  3051. */
  3052. Vector3.prototype.scaleToRef = function (scale, result) {
  3053. result.x = this.x * scale;
  3054. result.y = this.y * scale;
  3055. result.z = this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3060. * @param scale defines the scale factor
  3061. * @param result defines the Vector3 object where to store the result
  3062. * @returns the unmodified current Vector3
  3063. */
  3064. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3065. result.x += this.x * scale;
  3066. result.y += this.y * scale;
  3067. result.z += this.z * scale;
  3068. return this;
  3069. };
  3070. /**
  3071. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3072. * @param otherVector defines the second operand
  3073. * @returns true if both vectors are equals
  3074. */
  3075. Vector3.prototype.equals = function (otherVector) {
  3076. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3077. };
  3078. /**
  3079. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3080. * @param otherVector defines the second operand
  3081. * @param epsilon defines the minimal distance to define values as equals
  3082. * @returns true if both vectors are distant less than epsilon
  3083. */
  3084. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3085. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3086. 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);
  3087. };
  3088. /**
  3089. * Returns true if the current Vector3 coordinates equals the given floats
  3090. * @param x defines the x coordinate of the operand
  3091. * @param y defines the y coordinate of the operand
  3092. * @param z defines the z coordinate of the operand
  3093. * @returns true if both vectors are equals
  3094. */
  3095. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3096. return this.x === x && this.y === y && this.z === z;
  3097. };
  3098. /**
  3099. * Multiplies the current Vector3 coordinates by the given ones
  3100. * @param otherVector defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3104. this.x *= otherVector.x;
  3105. this.y *= otherVector.y;
  3106. this.z *= otherVector.z;
  3107. return this;
  3108. };
  3109. /**
  3110. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3111. * @param otherVector defines the second operand
  3112. * @returns the new Vector3
  3113. */
  3114. Vector3.prototype.multiply = function (otherVector) {
  3115. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3116. };
  3117. /**
  3118. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3119. * @param otherVector defines the second operand
  3120. * @param result defines the Vector3 object where to store the result
  3121. * @returns the current Vector3
  3122. */
  3123. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3124. result.x = this.x * otherVector.x;
  3125. result.y = this.y * otherVector.y;
  3126. result.z = this.z * otherVector.z;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3131. * @param x defines the x coordinate of the operand
  3132. * @param y defines the y coordinate of the operand
  3133. * @param z defines the z coordinate of the operand
  3134. * @returns the new Vector3
  3135. */
  3136. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3137. return new Vector3(this.x * x, this.y * y, this.z * z);
  3138. };
  3139. /**
  3140. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.divide = function (otherVector) {
  3145. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.divideToRef = function (otherVector, result) {
  3154. result.x = this.x / otherVector.x;
  3155. result.y = this.y / otherVector.y;
  3156. result.z = this.z / otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Divides the current Vector3 coordinates by the given ones.
  3161. * @param otherVector defines the second operand
  3162. * @returns the current updated Vector3
  3163. */
  3164. Vector3.prototype.divideInPlace = function (otherVector) {
  3165. return this.divideToRef(otherVector, this);
  3166. };
  3167. /**
  3168. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3169. * @param other defines the second operand
  3170. * @returns the current updated Vector3
  3171. */
  3172. Vector3.prototype.minimizeInPlace = function (other) {
  3173. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  3174. };
  3175. /**
  3176. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3177. * @param other defines the second operand
  3178. * @returns the current updated Vector3
  3179. */
  3180. Vector3.prototype.maximizeInPlace = function (other) {
  3181. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  3182. };
  3183. /**
  3184. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  3185. * @param x defines the x coordinate of the operand
  3186. * @param y defines the y coordinate of the operand
  3187. * @param z defines the z coordinate of the operand
  3188. * @returns the current updated Vector3
  3189. */
  3190. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  3191. this.x = Math.min(this.x, x);
  3192. this.y = Math.min(this.y, y);
  3193. this.z = Math.min(this.z, z);
  3194. return this;
  3195. };
  3196. /**
  3197. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  3198. * @param x defines the x coordinate of the operand
  3199. * @param y defines the y coordinate of the operand
  3200. * @param z defines the z coordinate of the operand
  3201. * @returns the current updated Vector3
  3202. */
  3203. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  3204. this.x = Math.max(this.x, x);
  3205. this.y = Math.max(this.y, y);
  3206. this.z = Math.max(this.z, z);
  3207. return this;
  3208. };
  3209. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3210. /**
  3211. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3212. */
  3213. get: function () {
  3214. var absX = Math.abs(this.x);
  3215. var absY = Math.abs(this.y);
  3216. if (absX !== absY) {
  3217. return true;
  3218. }
  3219. var absZ = Math.abs(this.z);
  3220. if (absX !== absZ) {
  3221. return true;
  3222. }
  3223. if (absY !== absZ) {
  3224. return true;
  3225. }
  3226. return false;
  3227. },
  3228. enumerable: true,
  3229. configurable: true
  3230. });
  3231. /**
  3232. * Gets a new Vector3 from current Vector3 floored values
  3233. * @returns a new Vector3
  3234. */
  3235. Vector3.prototype.floor = function () {
  3236. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3237. };
  3238. /**
  3239. * Gets a new Vector3 from current Vector3 floored values
  3240. * @returns a new Vector3
  3241. */
  3242. Vector3.prototype.fract = function () {
  3243. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3244. };
  3245. // Properties
  3246. /**
  3247. * Gets the length of the Vector3
  3248. * @returns the length of the Vecto3
  3249. */
  3250. Vector3.prototype.length = function () {
  3251. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3252. };
  3253. /**
  3254. * Gets the squared length of the Vector3
  3255. * @returns squared length of the Vector3
  3256. */
  3257. Vector3.prototype.lengthSquared = function () {
  3258. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3259. };
  3260. /**
  3261. * Normalize the current Vector3.
  3262. * Please note that this is an in place operation.
  3263. * @returns the current updated Vector3
  3264. */
  3265. Vector3.prototype.normalize = function () {
  3266. var len = this.length();
  3267. if (len === 0 || len === 1.0)
  3268. return this;
  3269. var num = 1.0 / len;
  3270. this.x *= num;
  3271. this.y *= num;
  3272. this.z *= num;
  3273. return this;
  3274. };
  3275. /**
  3276. * Normalize the current Vector3 to a new vector
  3277. * @returns the new Vector3
  3278. */
  3279. Vector3.prototype.normalizeToNew = function () {
  3280. var normalized = new Vector3(0, 0, 0);
  3281. this.normalizeToRef(normalized);
  3282. return normalized;
  3283. };
  3284. /**
  3285. * Normalize the current Vector3 to the reference
  3286. * @param reference define the Vector3 to update
  3287. * @returns the updated Vector3
  3288. */
  3289. Vector3.prototype.normalizeToRef = function (reference) {
  3290. var len = this.length();
  3291. if (len === 0 || len === 1.0) {
  3292. reference.set(this.x, this.y, this.z);
  3293. return reference;
  3294. }
  3295. var scale = 1.0 / len;
  3296. this.scaleToRef(scale, reference);
  3297. return reference;
  3298. };
  3299. /**
  3300. * Creates a new Vector3 copied from the current Vector3
  3301. * @returns the new Vector3
  3302. */
  3303. Vector3.prototype.clone = function () {
  3304. return new Vector3(this.x, this.y, this.z);
  3305. };
  3306. /**
  3307. * Copies the given vector coordinates to the current Vector3 ones
  3308. * @param source defines the source Vector3
  3309. * @returns the current updated Vector3
  3310. */
  3311. Vector3.prototype.copyFrom = function (source) {
  3312. this.x = source.x;
  3313. this.y = source.y;
  3314. this.z = source.z;
  3315. return this;
  3316. };
  3317. /**
  3318. * Copies the given floats to the current Vector3 coordinates
  3319. * @param x defines the x coordinate of the operand
  3320. * @param y defines the y coordinate of the operand
  3321. * @param z defines the z coordinate of the operand
  3322. * @returns the current updated Vector3
  3323. */
  3324. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3325. this.x = x;
  3326. this.y = y;
  3327. this.z = z;
  3328. return this;
  3329. };
  3330. /**
  3331. * Copies the given floats to the current Vector3 coordinates
  3332. * @param x defines the x coordinate of the operand
  3333. * @param y defines the y coordinate of the operand
  3334. * @param z defines the z coordinate of the operand
  3335. * @returns the current updated Vector3
  3336. */
  3337. Vector3.prototype.set = function (x, y, z) {
  3338. return this.copyFromFloats(x, y, z);
  3339. };
  3340. // Statics
  3341. /**
  3342. * Get the clip factor between two vectors
  3343. * @param vector0 defines the first operand
  3344. * @param vector1 defines the second operand
  3345. * @param axis defines the axis to use
  3346. * @param size defines the size along the axis
  3347. * @returns the clip factor
  3348. */
  3349. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3350. var d0 = Vector3.Dot(vector0, axis) - size;
  3351. var d1 = Vector3.Dot(vector1, axis) - size;
  3352. var s = d0 / (d0 - d1);
  3353. return s;
  3354. };
  3355. /**
  3356. * Get angle between two vectors
  3357. * @param vector0 angle between vector0 and vector1
  3358. * @param vector1 angle between vector0 and vector1
  3359. * @param normal direction of the normal
  3360. * @return the angle between vector0 and vector1
  3361. */
  3362. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3363. var v0 = vector0.clone().normalize();
  3364. var v1 = vector1.clone().normalize();
  3365. var dot = Vector3.Dot(v0, v1);
  3366. var n = Vector3.Cross(v0, v1);
  3367. if (Vector3.Dot(n, normal) > 0) {
  3368. return Math.acos(dot);
  3369. }
  3370. return -Math.acos(dot);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 set from the index "offset" of the given array
  3374. * @param array defines the source array
  3375. * @param offset defines the offset in the source array
  3376. * @returns the new Vector3
  3377. */
  3378. Vector3.FromArray = function (array, offset) {
  3379. if (!offset) {
  3380. offset = 0;
  3381. }
  3382. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3383. };
  3384. /**
  3385. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3386. * This function is deprecated. Use FromArray instead
  3387. * @param array defines the source array
  3388. * @param offset defines the offset in the source array
  3389. * @returns the new Vector3
  3390. */
  3391. Vector3.FromFloatArray = function (array, offset) {
  3392. return Vector3.FromArray(array, offset);
  3393. };
  3394. /**
  3395. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3396. * @param array defines the source array
  3397. * @param offset defines the offset in the source array
  3398. * @param result defines the Vector3 where to store the result
  3399. */
  3400. Vector3.FromArrayToRef = function (array, offset, result) {
  3401. result.x = array[offset];
  3402. result.y = array[offset + 1];
  3403. result.z = array[offset + 2];
  3404. };
  3405. /**
  3406. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3407. * This function is deprecated. Use FromArrayToRef instead.
  3408. * @param array defines the source array
  3409. * @param offset defines the offset in the source array
  3410. * @param result defines the Vector3 where to store the result
  3411. */
  3412. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3413. return Vector3.FromArrayToRef(array, offset, result);
  3414. };
  3415. /**
  3416. * Sets the given vector "result" with the given floats.
  3417. * @param x defines the x coordinate of the source
  3418. * @param y defines the y coordinate of the source
  3419. * @param z defines the z coordinate of the source
  3420. * @param result defines the Vector3 where to store the result
  3421. */
  3422. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3423. result.x = x;
  3424. result.y = y;
  3425. result.z = z;
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3429. * @returns a new empty Vector3
  3430. */
  3431. Vector3.Zero = function () {
  3432. return new Vector3(0.0, 0.0, 0.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3436. * @returns a new unit Vector3
  3437. */
  3438. Vector3.One = function () {
  3439. return new Vector3(1.0, 1.0, 1.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3443. * @returns a new up Vector3
  3444. */
  3445. Vector3.Up = function () {
  3446. return new Vector3(0.0, 1.0, 0.0);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3450. * @returns a new down Vector3
  3451. */
  3452. Vector3.Down = function () {
  3453. return new Vector3(0.0, -1.0, 0.0);
  3454. };
  3455. /**
  3456. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3457. * @returns a new forward Vector3
  3458. */
  3459. Vector3.Forward = function () {
  3460. return new Vector3(0.0, 0.0, 1.0);
  3461. };
  3462. /**
  3463. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3464. * @returns a new forward Vector3
  3465. */
  3466. Vector3.Backward = function () {
  3467. return new Vector3(0.0, 0.0, -1.0);
  3468. };
  3469. /**
  3470. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3471. * @returns a new right Vector3
  3472. */
  3473. Vector3.Right = function () {
  3474. return new Vector3(1.0, 0.0, 0.0);
  3475. };
  3476. /**
  3477. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3478. * @returns a new left Vector3
  3479. */
  3480. Vector3.Left = function () {
  3481. return new Vector3(-1.0, 0.0, 0.0);
  3482. };
  3483. /**
  3484. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3485. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3486. * @param vector defines the Vector3 to transform
  3487. * @param transformation defines the transformation matrix
  3488. * @returns the transformed Vector3
  3489. */
  3490. Vector3.TransformCoordinates = function (vector, transformation) {
  3491. var result = Vector3.Zero();
  3492. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3493. return result;
  3494. };
  3495. /**
  3496. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3497. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3498. * @param vector defines the Vector3 to transform
  3499. * @param transformation defines the transformation matrix
  3500. * @param result defines the Vector3 where to store the result
  3501. */
  3502. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3503. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3504. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3505. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3506. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3507. result.x = x / w;
  3508. result.y = y / w;
  3509. result.z = z / w;
  3510. };
  3511. /**
  3512. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3513. * This method computes tranformed coordinates only, not transformed direction vectors
  3514. * @param x define the x coordinate of the source vector
  3515. * @param y define the y coordinate of the source vector
  3516. * @param z define the z coordinate of the source vector
  3517. * @param transformation defines the transformation matrix
  3518. * @param result defines the Vector3 where to store the result
  3519. */
  3520. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3521. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3522. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3523. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3524. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3525. result.x = rx / rw;
  3526. result.y = ry / rw;
  3527. result.z = rz / rw;
  3528. };
  3529. /**
  3530. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3531. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3532. * @param vector defines the Vector3 to transform
  3533. * @param transformation defines the transformation matrix
  3534. * @returns the new Vector3
  3535. */
  3536. Vector3.TransformNormal = function (vector, transformation) {
  3537. var result = Vector3.Zero();
  3538. Vector3.TransformNormalToRef(vector, transformation, result);
  3539. return result;
  3540. };
  3541. /**
  3542. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3543. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3544. * @param vector defines the Vector3 to transform
  3545. * @param transformation defines the transformation matrix
  3546. * @param result defines the Vector3 where to store the result
  3547. */
  3548. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3549. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3550. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3551. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3552. result.x = x;
  3553. result.y = y;
  3554. result.z = z;
  3555. };
  3556. /**
  3557. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3558. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3559. * @param x define the x coordinate of the source vector
  3560. * @param y define the y coordinate of the source vector
  3561. * @param z define the z coordinate of the source vector
  3562. * @param transformation defines the transformation matrix
  3563. * @param result defines the Vector3 where to store the result
  3564. */
  3565. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3566. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3567. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3568. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3569. };
  3570. /**
  3571. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3572. * @param value1 defines the first control point
  3573. * @param value2 defines the second control point
  3574. * @param value3 defines the third control point
  3575. * @param value4 defines the fourth control point
  3576. * @param amount defines the amount on the spline to use
  3577. * @returns the new Vector3
  3578. */
  3579. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3580. var squared = amount * amount;
  3581. var cubed = amount * squared;
  3582. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3583. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3584. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3585. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3586. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3587. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3588. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3589. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3590. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3591. return new Vector3(x, y, z);
  3592. };
  3593. /**
  3594. * 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"
  3595. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3596. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3597. * @param value defines the current value
  3598. * @param min defines the lower range value
  3599. * @param max defines the upper range value
  3600. * @returns the new Vector3
  3601. */
  3602. Vector3.Clamp = function (value, min, max) {
  3603. var x = value.x;
  3604. x = (x > max.x) ? max.x : x;
  3605. x = (x < min.x) ? min.x : x;
  3606. var y = value.y;
  3607. y = (y > max.y) ? max.y : y;
  3608. y = (y < min.y) ? min.y : y;
  3609. var z = value.z;
  3610. z = (z > max.z) ? max.z : z;
  3611. z = (z < min.z) ? min.z : z;
  3612. return new Vector3(x, y, z);
  3613. };
  3614. /**
  3615. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3616. * @param value1 defines the first control point
  3617. * @param tangent1 defines the first tangent vector
  3618. * @param value2 defines the second control point
  3619. * @param tangent2 defines the second tangent vector
  3620. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3621. * @returns the new Vector3
  3622. */
  3623. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3624. var squared = amount * amount;
  3625. var cubed = amount * squared;
  3626. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3627. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3628. var part3 = (cubed - (2.0 * squared)) + amount;
  3629. var part4 = cubed - squared;
  3630. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3631. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3632. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3633. return new Vector3(x, y, z);
  3634. };
  3635. /**
  3636. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3637. * @param start defines the start value
  3638. * @param end defines the end value
  3639. * @param amount max defines amount between both (between 0 and 1)
  3640. * @returns the new Vector3
  3641. */
  3642. Vector3.Lerp = function (start, end, amount) {
  3643. var result = new Vector3(0, 0, 0);
  3644. Vector3.LerpToRef(start, end, amount, result);
  3645. return result;
  3646. };
  3647. /**
  3648. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3649. * @param start defines the start value
  3650. * @param end defines the end value
  3651. * @param amount max defines amount between both (between 0 and 1)
  3652. * @param result defines the Vector3 where to store the result
  3653. */
  3654. Vector3.LerpToRef = function (start, end, amount, result) {
  3655. result.x = start.x + ((end.x - start.x) * amount);
  3656. result.y = start.y + ((end.y - start.y) * amount);
  3657. result.z = start.z + ((end.z - start.z) * amount);
  3658. };
  3659. /**
  3660. * Returns the dot product (float) between the vectors "left" and "right"
  3661. * @param left defines the left operand
  3662. * @param right defines the right operand
  3663. * @returns the dot product
  3664. */
  3665. Vector3.Dot = function (left, right) {
  3666. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3667. };
  3668. /**
  3669. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3670. * The cross product is then orthogonal to both "left" and "right"
  3671. * @param left defines the left operand
  3672. * @param right defines the right operand
  3673. * @returns the cross product
  3674. */
  3675. Vector3.Cross = function (left, right) {
  3676. var result = Vector3.Zero();
  3677. Vector3.CrossToRef(left, right, result);
  3678. return result;
  3679. };
  3680. /**
  3681. * Sets the given vector "result" with the cross product of "left" and "right"
  3682. * The cross product is then orthogonal to both "left" and "right"
  3683. * @param left defines the left operand
  3684. * @param right defines the right operand
  3685. * @param result defines the Vector3 where to store the result
  3686. */
  3687. Vector3.CrossToRef = function (left, right, result) {
  3688. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3689. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3690. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3691. result.copyFrom(MathTmp.Vector3[0]);
  3692. };
  3693. /**
  3694. * Returns a new Vector3 as the normalization of the given vector
  3695. * @param vector defines the Vector3 to normalize
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Normalize = function (vector) {
  3699. var result = Vector3.Zero();
  3700. Vector3.NormalizeToRef(vector, result);
  3701. return result;
  3702. };
  3703. /**
  3704. * Sets the given vector "result" with the normalization of the given first vector
  3705. * @param vector defines the Vector3 to normalize
  3706. * @param result defines the Vector3 where to store the result
  3707. */
  3708. Vector3.NormalizeToRef = function (vector, result) {
  3709. result.copyFrom(vector);
  3710. result.normalize();
  3711. };
  3712. /**
  3713. * Project a Vector3 onto screen space
  3714. * @param vector defines the Vector3 to project
  3715. * @param world defines the world matrix to use
  3716. * @param transform defines the transform (view x projection) matrix to use
  3717. * @param viewport defines the screen viewport to use
  3718. * @returns the new Vector3
  3719. */
  3720. Vector3.Project = function (vector, world, transform, viewport) {
  3721. var cw = viewport.width;
  3722. var ch = viewport.height;
  3723. var cx = viewport.x;
  3724. var cy = viewport.y;
  3725. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3726. 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);
  3727. var matrix = MathTmp.Matrix[0];
  3728. world.multiplyToRef(transform, matrix);
  3729. matrix.multiplyToRef(viewportMatrix, matrix);
  3730. return Vector3.TransformCoordinates(vector, matrix);
  3731. };
  3732. /**
  3733. * Unproject from screen space to object space
  3734. * @param source defines the screen space Vector3 to use
  3735. * @param viewportWidth defines the current width of the viewport
  3736. * @param viewportHeight defines the current height of the viewport
  3737. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3738. * @param transform defines the transform (view x projection) matrix to use
  3739. * @returns the new Vector3
  3740. */
  3741. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3742. var matrix = MathTmp.Matrix[0];
  3743. world.multiplyToRef(transform, matrix);
  3744. matrix.invert();
  3745. source.x = source.x / viewportWidth * 2 - 1;
  3746. source.y = -(source.y / viewportHeight * 2 - 1);
  3747. var vector = Vector3.TransformCoordinates(source, matrix);
  3748. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3749. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3750. vector = vector.scale(1.0 / num);
  3751. }
  3752. return vector;
  3753. };
  3754. /**
  3755. * Unproject from screen space to object space
  3756. * @param source defines the screen space Vector3 to use
  3757. * @param viewportWidth defines the current width of the viewport
  3758. * @param viewportHeight defines the current height of the viewport
  3759. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3760. * @param view defines the view matrix to use
  3761. * @param projection defines the projection matrix to use
  3762. * @returns the new Vector3
  3763. */
  3764. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3765. var result = Vector3.Zero();
  3766. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3767. return result;
  3768. };
  3769. /**
  3770. * Unproject from screen space to object space
  3771. * @param source defines the screen space Vector3 to use
  3772. * @param viewportWidth defines the current width of the viewport
  3773. * @param viewportHeight defines the current height of the viewport
  3774. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3775. * @param view defines the view matrix to use
  3776. * @param projection defines the projection matrix to use
  3777. * @param result defines the Vector3 where to store the result
  3778. */
  3779. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3780. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3781. };
  3782. /**
  3783. * Unproject from screen space to object space
  3784. * @param sourceX defines the screen space x coordinate to use
  3785. * @param sourceY defines the screen space y coordinate to use
  3786. * @param sourceZ defines the screen space z coordinate to use
  3787. * @param viewportWidth defines the current width of the viewport
  3788. * @param viewportHeight defines the current height of the viewport
  3789. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3790. * @param view defines the view matrix to use
  3791. * @param projection defines the projection matrix to use
  3792. * @param result defines the Vector3 where to store the result
  3793. */
  3794. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3795. var matrix = MathTmp.Matrix[0];
  3796. world.multiplyToRef(view, matrix);
  3797. matrix.multiplyToRef(projection, matrix);
  3798. matrix.invert();
  3799. var screenSource = MathTmp.Vector3[0];
  3800. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3801. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3802. screenSource.z = 2 * sourceZ - 1.0;
  3803. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3804. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3805. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3806. result.scaleInPlace(1.0 / num);
  3807. }
  3808. };
  3809. /**
  3810. * Gets the minimal coordinate values between two Vector3
  3811. * @param left defines the first operand
  3812. * @param right defines the second operand
  3813. * @returns the new Vector3
  3814. */
  3815. Vector3.Minimize = function (left, right) {
  3816. var min = left.clone();
  3817. min.minimizeInPlace(right);
  3818. return min;
  3819. };
  3820. /**
  3821. * Gets the maximal coordinate values between two Vector3
  3822. * @param left defines the first operand
  3823. * @param right defines the second operand
  3824. * @returns the new Vector3
  3825. */
  3826. Vector3.Maximize = function (left, right) {
  3827. var max = left.clone();
  3828. max.maximizeInPlace(right);
  3829. return max;
  3830. };
  3831. /**
  3832. * Returns the distance between the vectors "value1" and "value2"
  3833. * @param value1 defines the first operand
  3834. * @param value2 defines the second operand
  3835. * @returns the distance
  3836. */
  3837. Vector3.Distance = function (value1, value2) {
  3838. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3839. };
  3840. /**
  3841. * Returns the squared distance between the vectors "value1" and "value2"
  3842. * @param value1 defines the first operand
  3843. * @param value2 defines the second operand
  3844. * @returns the squared distance
  3845. */
  3846. Vector3.DistanceSquared = function (value1, value2) {
  3847. var x = value1.x - value2.x;
  3848. var y = value1.y - value2.y;
  3849. var z = value1.z - value2.z;
  3850. return (x * x) + (y * y) + (z * z);
  3851. };
  3852. /**
  3853. * Returns a new Vector3 located at the center between "value1" and "value2"
  3854. * @param value1 defines the first operand
  3855. * @param value2 defines the second operand
  3856. * @returns the new Vector3
  3857. */
  3858. Vector3.Center = function (value1, value2) {
  3859. var center = value1.add(value2);
  3860. center.scaleInPlace(0.5);
  3861. return center;
  3862. };
  3863. /**
  3864. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3865. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3866. * to something in order to rotate it from its local system to the given target system
  3867. * Note: axis1, axis2 and axis3 are normalized during this operation
  3868. * @param axis1 defines the first axis
  3869. * @param axis2 defines the second axis
  3870. * @param axis3 defines the third axis
  3871. * @returns a new Vector3
  3872. */
  3873. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3874. var rotation = Vector3.Zero();
  3875. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3876. return rotation;
  3877. };
  3878. /**
  3879. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3880. * @param axis1 defines the first axis
  3881. * @param axis2 defines the second axis
  3882. * @param axis3 defines the third axis
  3883. * @param ref defines the Vector3 where to store the result
  3884. */
  3885. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3886. var quat = MathTmp.Quaternion[0];
  3887. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3888. quat.toEulerAnglesToRef(ref);
  3889. };
  3890. return Vector3;
  3891. }());
  3892. BABYLON.Vector3 = Vector3;
  3893. /**
  3894. * Vector4 class created for EulerAngle class conversion to Quaternion
  3895. */
  3896. var Vector4 = /** @class */ (function () {
  3897. /**
  3898. * Creates a Vector4 object from the given floats.
  3899. * @param x x value of the vector
  3900. * @param y y value of the vector
  3901. * @param z z value of the vector
  3902. * @param w w value of the vector
  3903. */
  3904. function Vector4(
  3905. /** x value of the vector */
  3906. x,
  3907. /** y value of the vector */
  3908. y,
  3909. /** z value of the vector */
  3910. z,
  3911. /** w value of the vector */
  3912. w) {
  3913. this.x = x;
  3914. this.y = y;
  3915. this.z = z;
  3916. this.w = w;
  3917. }
  3918. /**
  3919. * Returns the string with the Vector4 coordinates.
  3920. * @returns a string containing all the vector values
  3921. */
  3922. Vector4.prototype.toString = function () {
  3923. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3924. };
  3925. /**
  3926. * Returns the string "Vector4".
  3927. * @returns "Vector4"
  3928. */
  3929. Vector4.prototype.getClassName = function () {
  3930. return "Vector4";
  3931. };
  3932. /**
  3933. * Returns the Vector4 hash code.
  3934. * @returns a unique hash code
  3935. */
  3936. Vector4.prototype.getHashCode = function () {
  3937. var hash = this.x || 0;
  3938. hash = (hash * 397) ^ (this.y || 0);
  3939. hash = (hash * 397) ^ (this.z || 0);
  3940. hash = (hash * 397) ^ (this.w || 0);
  3941. return hash;
  3942. };
  3943. // Operators
  3944. /**
  3945. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3946. * @returns the resulting array
  3947. */
  3948. Vector4.prototype.asArray = function () {
  3949. var result = new Array();
  3950. this.toArray(result, 0);
  3951. return result;
  3952. };
  3953. /**
  3954. * Populates the given array from the given index with the Vector4 coordinates.
  3955. * @param array array to populate
  3956. * @param index index of the array to start at (default: 0)
  3957. * @returns the Vector4.
  3958. */
  3959. Vector4.prototype.toArray = function (array, index) {
  3960. if (index === undefined) {
  3961. index = 0;
  3962. }
  3963. array[index] = this.x;
  3964. array[index + 1] = this.y;
  3965. array[index + 2] = this.z;
  3966. array[index + 3] = this.w;
  3967. return this;
  3968. };
  3969. /**
  3970. * Adds the given vector to the current Vector4.
  3971. * @param otherVector the vector to add
  3972. * @returns the updated Vector4.
  3973. */
  3974. Vector4.prototype.addInPlace = function (otherVector) {
  3975. this.x += otherVector.x;
  3976. this.y += otherVector.y;
  3977. this.z += otherVector.z;
  3978. this.w += otherVector.w;
  3979. return this;
  3980. };
  3981. /**
  3982. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3983. * @param otherVector the vector to add
  3984. * @returns the resulting vector
  3985. */
  3986. Vector4.prototype.add = function (otherVector) {
  3987. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3988. };
  3989. /**
  3990. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3991. * @param otherVector the vector to add
  3992. * @param result the vector to store the result
  3993. * @returns the current Vector4.
  3994. */
  3995. Vector4.prototype.addToRef = function (otherVector, result) {
  3996. result.x = this.x + otherVector.x;
  3997. result.y = this.y + otherVector.y;
  3998. result.z = this.z + otherVector.z;
  3999. result.w = this.w + otherVector.w;
  4000. return this;
  4001. };
  4002. /**
  4003. * Subtract in place the given vector from the current Vector4.
  4004. * @param otherVector the vector to subtract
  4005. * @returns the updated Vector4.
  4006. */
  4007. Vector4.prototype.subtractInPlace = function (otherVector) {
  4008. this.x -= otherVector.x;
  4009. this.y -= otherVector.y;
  4010. this.z -= otherVector.z;
  4011. this.w -= otherVector.w;
  4012. return this;
  4013. };
  4014. /**
  4015. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4016. * @param otherVector the vector to add
  4017. * @returns the new vector with the result
  4018. */
  4019. Vector4.prototype.subtract = function (otherVector) {
  4020. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4021. };
  4022. /**
  4023. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4024. * @param otherVector the vector to subtract
  4025. * @param result the vector to store the result
  4026. * @returns the current Vector4.
  4027. */
  4028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4029. result.x = this.x - otherVector.x;
  4030. result.y = this.y - otherVector.y;
  4031. result.z = this.z - otherVector.z;
  4032. result.w = this.w - otherVector.w;
  4033. return this;
  4034. };
  4035. /**
  4036. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4037. */
  4038. /**
  4039. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4040. * @param x value to subtract
  4041. * @param y value to subtract
  4042. * @param z value to subtract
  4043. * @param w value to subtract
  4044. * @returns new vector containing the result
  4045. */
  4046. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4047. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4048. };
  4049. /**
  4050. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4051. * @param x value to subtract
  4052. * @param y value to subtract
  4053. * @param z value to subtract
  4054. * @param w value to subtract
  4055. * @param result the vector to store the result in
  4056. * @returns the current Vector4.
  4057. */
  4058. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4059. result.x = this.x - x;
  4060. result.y = this.y - y;
  4061. result.z = this.z - z;
  4062. result.w = this.w - w;
  4063. return this;
  4064. };
  4065. /**
  4066. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4067. * @returns a new vector with the negated values
  4068. */
  4069. Vector4.prototype.negate = function () {
  4070. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4071. };
  4072. /**
  4073. * Multiplies the current Vector4 coordinates by scale (float).
  4074. * @param scale the number to scale with
  4075. * @returns the updated Vector4.
  4076. */
  4077. Vector4.prototype.scaleInPlace = function (scale) {
  4078. this.x *= scale;
  4079. this.y *= scale;
  4080. this.z *= scale;
  4081. this.w *= scale;
  4082. return this;
  4083. };
  4084. /**
  4085. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4086. * @param scale the number to scale with
  4087. * @returns a new vector with the result
  4088. */
  4089. Vector4.prototype.scale = function (scale) {
  4090. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4091. };
  4092. /**
  4093. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4094. * @param scale the number to scale with
  4095. * @param result a vector to store the result in
  4096. * @returns the current Vector4.
  4097. */
  4098. Vector4.prototype.scaleToRef = function (scale, result) {
  4099. result.x = this.x * scale;
  4100. result.y = this.y * scale;
  4101. result.z = this.z * scale;
  4102. result.w = this.w * scale;
  4103. return this;
  4104. };
  4105. /**
  4106. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4107. * @param scale defines the scale factor
  4108. * @param result defines the Vector4 object where to store the result
  4109. * @returns the unmodified current Vector4
  4110. */
  4111. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4112. result.x += this.x * scale;
  4113. result.y += this.y * scale;
  4114. result.z += this.z * scale;
  4115. result.w += this.w * scale;
  4116. return this;
  4117. };
  4118. /**
  4119. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4120. * @param otherVector the vector to compare against
  4121. * @returns true if they are equal
  4122. */
  4123. Vector4.prototype.equals = function (otherVector) {
  4124. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4125. };
  4126. /**
  4127. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4128. * @param otherVector vector to compare against
  4129. * @param epsilon (Default: very small number)
  4130. * @returns true if they are equal
  4131. */
  4132. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4133. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4134. return otherVector
  4135. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4136. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4137. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4138. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4139. };
  4140. /**
  4141. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4142. * @param x x value to compare against
  4143. * @param y y value to compare against
  4144. * @param z z value to compare against
  4145. * @param w w value to compare against
  4146. * @returns true if equal
  4147. */
  4148. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4149. return this.x === x && this.y === y && this.z === z && this.w === w;
  4150. };
  4151. /**
  4152. * Multiplies in place the current Vector4 by the given one.
  4153. * @param otherVector vector to multiple with
  4154. * @returns the updated Vector4.
  4155. */
  4156. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4157. this.x *= otherVector.x;
  4158. this.y *= otherVector.y;
  4159. this.z *= otherVector.z;
  4160. this.w *= otherVector.w;
  4161. return this;
  4162. };
  4163. /**
  4164. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4165. * @param otherVector vector to multiple with
  4166. * @returns resulting new vector
  4167. */
  4168. Vector4.prototype.multiply = function (otherVector) {
  4169. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4170. };
  4171. /**
  4172. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4173. * @param otherVector vector to multiple with
  4174. * @param result vector to store the result
  4175. * @returns the current Vector4.
  4176. */
  4177. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4178. result.x = this.x * otherVector.x;
  4179. result.y = this.y * otherVector.y;
  4180. result.z = this.z * otherVector.z;
  4181. result.w = this.w * otherVector.w;
  4182. return this;
  4183. };
  4184. /**
  4185. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4186. * @param x x value multiply with
  4187. * @param y y value multiply with
  4188. * @param z z value multiply with
  4189. * @param w w value multiply with
  4190. * @returns resulting new vector
  4191. */
  4192. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4193. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4197. * @param otherVector vector to devide with
  4198. * @returns resulting new vector
  4199. */
  4200. Vector4.prototype.divide = function (otherVector) {
  4201. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4202. };
  4203. /**
  4204. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4205. * @param otherVector vector to devide with
  4206. * @param result vector to store the result
  4207. * @returns the current Vector4.
  4208. */
  4209. Vector4.prototype.divideToRef = function (otherVector, result) {
  4210. result.x = this.x / otherVector.x;
  4211. result.y = this.y / otherVector.y;
  4212. result.z = this.z / otherVector.z;
  4213. result.w = this.w / otherVector.w;
  4214. return this;
  4215. };
  4216. /**
  4217. * Divides the current Vector3 coordinates by the given ones.
  4218. * @param otherVector vector to devide with
  4219. * @returns the updated Vector3.
  4220. */
  4221. Vector4.prototype.divideInPlace = function (otherVector) {
  4222. return this.divideToRef(otherVector, this);
  4223. };
  4224. /**
  4225. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4226. * @param other defines the second operand
  4227. * @returns the current updated Vector4
  4228. */
  4229. Vector4.prototype.minimizeInPlace = function (other) {
  4230. if (other.x < this.x)
  4231. this.x = other.x;
  4232. if (other.y < this.y)
  4233. this.y = other.y;
  4234. if (other.z < this.z)
  4235. this.z = other.z;
  4236. if (other.w < this.w)
  4237. this.w = other.w;
  4238. return this;
  4239. };
  4240. /**
  4241. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4242. * @param other defines the second operand
  4243. * @returns the current updated Vector4
  4244. */
  4245. Vector4.prototype.maximizeInPlace = function (other) {
  4246. if (other.x > this.x)
  4247. this.x = other.x;
  4248. if (other.y > this.y)
  4249. this.y = other.y;
  4250. if (other.z > this.z)
  4251. this.z = other.z;
  4252. if (other.w > this.w)
  4253. this.w = other.w;
  4254. return this;
  4255. };
  4256. /**
  4257. * Gets a new Vector4 from current Vector4 floored values
  4258. * @returns a new Vector4
  4259. */
  4260. Vector4.prototype.floor = function () {
  4261. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4262. };
  4263. /**
  4264. * Gets a new Vector4 from current Vector3 floored values
  4265. * @returns a new Vector4
  4266. */
  4267. Vector4.prototype.fract = function () {
  4268. 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));
  4269. };
  4270. // Properties
  4271. /**
  4272. * Returns the Vector4 length (float).
  4273. * @returns the length
  4274. */
  4275. Vector4.prototype.length = function () {
  4276. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4277. };
  4278. /**
  4279. * Returns the Vector4 squared length (float).
  4280. * @returns the length squared
  4281. */
  4282. Vector4.prototype.lengthSquared = function () {
  4283. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4284. };
  4285. // Methods
  4286. /**
  4287. * Normalizes in place the Vector4.
  4288. * @returns the updated Vector4.
  4289. */
  4290. Vector4.prototype.normalize = function () {
  4291. var len = this.length();
  4292. if (len === 0)
  4293. return this;
  4294. var num = 1.0 / len;
  4295. this.x *= num;
  4296. this.y *= num;
  4297. this.z *= num;
  4298. this.w *= num;
  4299. return this;
  4300. };
  4301. /**
  4302. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4303. * @returns this converted to a new vector3
  4304. */
  4305. Vector4.prototype.toVector3 = function () {
  4306. return new Vector3(this.x, this.y, this.z);
  4307. };
  4308. /**
  4309. * Returns a new Vector4 copied from the current one.
  4310. * @returns the new cloned vector
  4311. */
  4312. Vector4.prototype.clone = function () {
  4313. return new Vector4(this.x, this.y, this.z, this.w);
  4314. };
  4315. /**
  4316. * Updates the current Vector4 with the given one coordinates.
  4317. * @param source the source vector to copy from
  4318. * @returns the updated Vector4.
  4319. */
  4320. Vector4.prototype.copyFrom = function (source) {
  4321. this.x = source.x;
  4322. this.y = source.y;
  4323. this.z = source.z;
  4324. this.w = source.w;
  4325. return this;
  4326. };
  4327. /**
  4328. * Updates the current Vector4 coordinates with the given floats.
  4329. * @param x float to copy from
  4330. * @param y float to copy from
  4331. * @param z float to copy from
  4332. * @param w float to copy from
  4333. * @returns the updated Vector4.
  4334. */
  4335. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4336. this.x = x;
  4337. this.y = y;
  4338. this.z = z;
  4339. this.w = w;
  4340. return this;
  4341. };
  4342. /**
  4343. * Updates the current Vector4 coordinates with the given floats.
  4344. * @param x float to set from
  4345. * @param y float to set from
  4346. * @param z float to set from
  4347. * @param w float to set from
  4348. * @returns the updated Vector4.
  4349. */
  4350. Vector4.prototype.set = function (x, y, z, w) {
  4351. return this.copyFromFloats(x, y, z, w);
  4352. };
  4353. // Statics
  4354. /**
  4355. * Returns a new Vector4 set from the starting index of the given array.
  4356. * @param array the array to pull values from
  4357. * @param offset the offset into the array to start at
  4358. * @returns the new vector
  4359. */
  4360. Vector4.FromArray = function (array, offset) {
  4361. if (!offset) {
  4362. offset = 0;
  4363. }
  4364. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4365. };
  4366. /**
  4367. * Updates the given vector "result" from the starting index of the given array.
  4368. * @param array the array to pull values from
  4369. * @param offset the offset into the array to start at
  4370. * @param result the vector to store the result in
  4371. */
  4372. Vector4.FromArrayToRef = function (array, offset, result) {
  4373. result.x = array[offset];
  4374. result.y = array[offset + 1];
  4375. result.z = array[offset + 2];
  4376. result.w = array[offset + 3];
  4377. };
  4378. /**
  4379. * Updates the given vector "result" from the starting index of the given Float32Array.
  4380. * @param array the array to pull values from
  4381. * @param offset the offset into the array to start at
  4382. * @param result the vector to store the result in
  4383. */
  4384. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4385. Vector4.FromArrayToRef(array, offset, result);
  4386. };
  4387. /**
  4388. * Updates the given vector "result" coordinates from the given floats.
  4389. * @param x float to set from
  4390. * @param y float to set from
  4391. * @param z float to set from
  4392. * @param w float to set from
  4393. * @param result the vector to the floats in
  4394. */
  4395. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4396. result.x = x;
  4397. result.y = y;
  4398. result.z = z;
  4399. result.w = w;
  4400. };
  4401. /**
  4402. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4403. * @returns the new vector
  4404. */
  4405. Vector4.Zero = function () {
  4406. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4407. };
  4408. /**
  4409. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4410. * @returns the new vector
  4411. */
  4412. Vector4.One = function () {
  4413. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4414. };
  4415. /**
  4416. * Returns a new normalized Vector4 from the given one.
  4417. * @param vector the vector to normalize
  4418. * @returns the vector
  4419. */
  4420. Vector4.Normalize = function (vector) {
  4421. var result = Vector4.Zero();
  4422. Vector4.NormalizeToRef(vector, result);
  4423. return result;
  4424. };
  4425. /**
  4426. * Updates the given vector "result" from the normalization of the given one.
  4427. * @param vector the vector to normalize
  4428. * @param result the vector to store the result in
  4429. */
  4430. Vector4.NormalizeToRef = function (vector, result) {
  4431. result.copyFrom(vector);
  4432. result.normalize();
  4433. };
  4434. /**
  4435. * Returns a vector with the minimum values from the left and right vectors
  4436. * @param left left vector to minimize
  4437. * @param right right vector to minimize
  4438. * @returns a new vector with the minimum of the left and right vector values
  4439. */
  4440. Vector4.Minimize = function (left, right) {
  4441. var min = left.clone();
  4442. min.minimizeInPlace(right);
  4443. return min;
  4444. };
  4445. /**
  4446. * Returns a vector with the maximum values from the left and right vectors
  4447. * @param left left vector to maximize
  4448. * @param right right vector to maximize
  4449. * @returns a new vector with the maximum of the left and right vector values
  4450. */
  4451. Vector4.Maximize = function (left, right) {
  4452. var max = left.clone();
  4453. max.maximizeInPlace(right);
  4454. return max;
  4455. };
  4456. /**
  4457. * Returns the distance (float) between the vectors "value1" and "value2".
  4458. * @param value1 value to calulate the distance between
  4459. * @param value2 value to calulate the distance between
  4460. * @return the distance between the two vectors
  4461. */
  4462. Vector4.Distance = function (value1, value2) {
  4463. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4464. };
  4465. /**
  4466. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4467. * @param value1 value to calulate the distance between
  4468. * @param value2 value to calulate the distance between
  4469. * @return the distance between the two vectors squared
  4470. */
  4471. Vector4.DistanceSquared = function (value1, value2) {
  4472. var x = value1.x - value2.x;
  4473. var y = value1.y - value2.y;
  4474. var z = value1.z - value2.z;
  4475. var w = value1.w - value2.w;
  4476. return (x * x) + (y * y) + (z * z) + (w * w);
  4477. };
  4478. /**
  4479. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4480. * @param value1 value to calulate the center between
  4481. * @param value2 value to calulate the center between
  4482. * @return the center between the two vectors
  4483. */
  4484. Vector4.Center = function (value1, value2) {
  4485. var center = value1.add(value2);
  4486. center.scaleInPlace(0.5);
  4487. return center;
  4488. };
  4489. /**
  4490. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4491. * This methods computes transformed normalized direction vectors only.
  4492. * @param vector the vector to transform
  4493. * @param transformation the transformation matrix to apply
  4494. * @returns the new vector
  4495. */
  4496. Vector4.TransformNormal = function (vector, transformation) {
  4497. var result = Vector4.Zero();
  4498. Vector4.TransformNormalToRef(vector, transformation, result);
  4499. return result;
  4500. };
  4501. /**
  4502. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4503. * This methods computes transformed normalized direction vectors only.
  4504. * @param vector the vector to transform
  4505. * @param transformation the transformation matrix to apply
  4506. * @param result the vector to store the result in
  4507. */
  4508. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4509. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4510. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4511. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4512. result.x = x;
  4513. result.y = y;
  4514. result.z = z;
  4515. result.w = vector.w;
  4516. };
  4517. /**
  4518. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4519. * This methods computes transformed normalized direction vectors only.
  4520. * @param x value to transform
  4521. * @param y value to transform
  4522. * @param z value to transform
  4523. * @param w value to transform
  4524. * @param transformation the transformation matrix to apply
  4525. * @param result the vector to store the results in
  4526. */
  4527. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4528. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4529. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4530. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4531. result.w = w;
  4532. };
  4533. return Vector4;
  4534. }());
  4535. BABYLON.Vector4 = Vector4;
  4536. /**
  4537. * Size containing widht and height
  4538. */
  4539. var Size = /** @class */ (function () {
  4540. /**
  4541. * Creates a Size object from the given width and height (floats).
  4542. * @param width width of the new size
  4543. * @param height height of the new size
  4544. */
  4545. function Size(width, height) {
  4546. this.width = width;
  4547. this.height = height;
  4548. }
  4549. /**
  4550. * Returns a string with the Size width and height
  4551. * @returns a string with the Size width and height
  4552. */
  4553. Size.prototype.toString = function () {
  4554. return "{W: " + this.width + ", H: " + this.height + "}";
  4555. };
  4556. /**
  4557. * "Size"
  4558. * @returns the string "Size"
  4559. */
  4560. Size.prototype.getClassName = function () {
  4561. return "Size";
  4562. };
  4563. /**
  4564. * Returns the Size hash code.
  4565. * @returns a hash code for a unique width and height
  4566. */
  4567. Size.prototype.getHashCode = function () {
  4568. var hash = this.width || 0;
  4569. hash = (hash * 397) ^ (this.height || 0);
  4570. return hash;
  4571. };
  4572. /**
  4573. * Updates the current size from the given one.
  4574. * @param src the given size
  4575. */
  4576. Size.prototype.copyFrom = function (src) {
  4577. this.width = src.width;
  4578. this.height = src.height;
  4579. };
  4580. /**
  4581. * Updates in place the current Size from the given floats.
  4582. * @param width width of the new size
  4583. * @param height height of the new size
  4584. * @returns the updated Size.
  4585. */
  4586. Size.prototype.copyFromFloats = function (width, height) {
  4587. this.width = width;
  4588. this.height = height;
  4589. return this;
  4590. };
  4591. /**
  4592. * Updates in place the current Size from the given floats.
  4593. * @param width width to set
  4594. * @param height height to set
  4595. * @returns the updated Size.
  4596. */
  4597. Size.prototype.set = function (width, height) {
  4598. return this.copyFromFloats(width, height);
  4599. };
  4600. /**
  4601. * Multiplies the width and height by numbers
  4602. * @param w factor to multiple the width by
  4603. * @param h factor to multiple the height by
  4604. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4605. */
  4606. Size.prototype.multiplyByFloats = function (w, h) {
  4607. return new Size(this.width * w, this.height * h);
  4608. };
  4609. /**
  4610. * Clones the size
  4611. * @returns a new Size copied from the given one.
  4612. */
  4613. Size.prototype.clone = function () {
  4614. return new Size(this.width, this.height);
  4615. };
  4616. /**
  4617. * True if the current Size and the given one width and height are strictly equal.
  4618. * @param other the other size to compare against
  4619. * @returns True if the current Size and the given one width and height are strictly equal.
  4620. */
  4621. Size.prototype.equals = function (other) {
  4622. if (!other) {
  4623. return false;
  4624. }
  4625. return (this.width === other.width) && (this.height === other.height);
  4626. };
  4627. Object.defineProperty(Size.prototype, "surface", {
  4628. /**
  4629. * The surface of the Size : width * height (float).
  4630. */
  4631. get: function () {
  4632. return this.width * this.height;
  4633. },
  4634. enumerable: true,
  4635. configurable: true
  4636. });
  4637. /**
  4638. * Create a new size of zero
  4639. * @returns a new Size set to (0.0, 0.0)
  4640. */
  4641. Size.Zero = function () {
  4642. return new Size(0.0, 0.0);
  4643. };
  4644. /**
  4645. * Sums the width and height of two sizes
  4646. * @param otherSize size to add to this size
  4647. * @returns a new Size set as the addition result of the current Size and the given one.
  4648. */
  4649. Size.prototype.add = function (otherSize) {
  4650. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4651. return r;
  4652. };
  4653. /**
  4654. * Subtracts the width and height of two
  4655. * @param otherSize size to subtract to this size
  4656. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4657. */
  4658. Size.prototype.subtract = function (otherSize) {
  4659. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4660. return r;
  4661. };
  4662. /**
  4663. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4664. * @param start starting size to lerp between
  4665. * @param end end size to lerp between
  4666. * @param amount amount to lerp between the start and end values
  4667. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4668. */
  4669. Size.Lerp = function (start, end, amount) {
  4670. var w = start.width + ((end.width - start.width) * amount);
  4671. var h = start.height + ((end.height - start.height) * amount);
  4672. return new Size(w, h);
  4673. };
  4674. return Size;
  4675. }());
  4676. BABYLON.Size = Size;
  4677. /**
  4678. * Class used to store quaternion data
  4679. * @see https://en.wikipedia.org/wiki/Quaternion
  4680. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4681. */
  4682. var Quaternion = /** @class */ (function () {
  4683. /**
  4684. * Creates a new Quaternion from the given floats
  4685. * @param x defines the first component (0 by default)
  4686. * @param y defines the second component (0 by default)
  4687. * @param z defines the third component (0 by default)
  4688. * @param w defines the fourth component (1.0 by default)
  4689. */
  4690. function Quaternion(
  4691. /** defines the first component (0 by default) */
  4692. x,
  4693. /** defines the second component (0 by default) */
  4694. y,
  4695. /** defines the third component (0 by default) */
  4696. z,
  4697. /** defines the fourth component (1.0 by default) */
  4698. w) {
  4699. if (x === void 0) { x = 0.0; }
  4700. if (y === void 0) { y = 0.0; }
  4701. if (z === void 0) { z = 0.0; }
  4702. if (w === void 0) { w = 1.0; }
  4703. this.x = x;
  4704. this.y = y;
  4705. this.z = z;
  4706. this.w = w;
  4707. }
  4708. /**
  4709. * Gets a string representation for the current quaternion
  4710. * @returns a string with the Quaternion coordinates
  4711. */
  4712. Quaternion.prototype.toString = function () {
  4713. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4714. };
  4715. /**
  4716. * Gets the class name of the quaternion
  4717. * @returns the string "Quaternion"
  4718. */
  4719. Quaternion.prototype.getClassName = function () {
  4720. return "Quaternion";
  4721. };
  4722. /**
  4723. * Gets a hash code for this quaternion
  4724. * @returns the quaternion hash code
  4725. */
  4726. Quaternion.prototype.getHashCode = function () {
  4727. var hash = this.x || 0;
  4728. hash = (hash * 397) ^ (this.y || 0);
  4729. hash = (hash * 397) ^ (this.z || 0);
  4730. hash = (hash * 397) ^ (this.w || 0);
  4731. return hash;
  4732. };
  4733. /**
  4734. * Copy the quaternion to an array
  4735. * @returns a new array populated with 4 elements from the quaternion coordinates
  4736. */
  4737. Quaternion.prototype.asArray = function () {
  4738. return [this.x, this.y, this.z, this.w];
  4739. };
  4740. /**
  4741. * Check if two quaternions are equals
  4742. * @param otherQuaternion defines the second operand
  4743. * @return true if the current quaternion and the given one coordinates are strictly equals
  4744. */
  4745. Quaternion.prototype.equals = function (otherQuaternion) {
  4746. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4747. };
  4748. /**
  4749. * Clone the current quaternion
  4750. * @returns a new quaternion copied from the current one
  4751. */
  4752. Quaternion.prototype.clone = function () {
  4753. return new Quaternion(this.x, this.y, this.z, this.w);
  4754. };
  4755. /**
  4756. * Copy a quaternion to the current one
  4757. * @param other defines the other quaternion
  4758. * @returns the updated current quaternion
  4759. */
  4760. Quaternion.prototype.copyFrom = function (other) {
  4761. this.x = other.x;
  4762. this.y = other.y;
  4763. this.z = other.z;
  4764. this.w = other.w;
  4765. return this;
  4766. };
  4767. /**
  4768. * Updates the current quaternion with the given float coordinates
  4769. * @param x defines the x coordinate
  4770. * @param y defines the y coordinate
  4771. * @param z defines the z coordinate
  4772. * @param w defines the w coordinate
  4773. * @returns the updated current quaternion
  4774. */
  4775. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4776. this.x = x;
  4777. this.y = y;
  4778. this.z = z;
  4779. this.w = w;
  4780. return this;
  4781. };
  4782. /**
  4783. * Updates the current quaternion from the given float coordinates
  4784. * @param x defines the x coordinate
  4785. * @param y defines the y coordinate
  4786. * @param z defines the z coordinate
  4787. * @param w defines the w coordinate
  4788. * @returns the updated current quaternion
  4789. */
  4790. Quaternion.prototype.set = function (x, y, z, w) {
  4791. return this.copyFromFloats(x, y, z, w);
  4792. };
  4793. /**
  4794. * Adds two quaternions
  4795. * @param other defines the second operand
  4796. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4797. */
  4798. Quaternion.prototype.add = function (other) {
  4799. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4800. };
  4801. /**
  4802. * Add a quaternion to the current one
  4803. * @param other defines the quaternion to add
  4804. * @returns the current quaternion
  4805. */
  4806. Quaternion.prototype.addInPlace = function (other) {
  4807. this.x += other.x;
  4808. this.y += other.y;
  4809. this.z += other.z;
  4810. this.w += other.w;
  4811. return this;
  4812. };
  4813. /**
  4814. * Subtract two quaternions
  4815. * @param other defines the second operand
  4816. * @returns a new quaternion as the subtraction result of the given one from the current one
  4817. */
  4818. Quaternion.prototype.subtract = function (other) {
  4819. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4820. };
  4821. /**
  4822. * Multiplies the current quaternion by a scale factor
  4823. * @param value defines the scale factor
  4824. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4825. */
  4826. Quaternion.prototype.scale = function (value) {
  4827. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4828. };
  4829. /**
  4830. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4831. * @param scale defines the scale factor
  4832. * @param result defines the Quaternion object where to store the result
  4833. * @returns the unmodified current quaternion
  4834. */
  4835. Quaternion.prototype.scaleToRef = function (scale, result) {
  4836. result.x = this.x * scale;
  4837. result.y = this.y * scale;
  4838. result.z = this.z * scale;
  4839. result.w = this.w * scale;
  4840. return this;
  4841. };
  4842. /**
  4843. * Multiplies in place the current quaternion by a scale factor
  4844. * @param value defines the scale factor
  4845. * @returns the current modified quaternion
  4846. */
  4847. Quaternion.prototype.scaleInPlace = function (value) {
  4848. this.x *= value;
  4849. this.y *= value;
  4850. this.z *= value;
  4851. this.w *= value;
  4852. return this;
  4853. };
  4854. /**
  4855. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4856. * @param scale defines the scale factor
  4857. * @param result defines the Quaternion object where to store the result
  4858. * @returns the unmodified current quaternion
  4859. */
  4860. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4861. result.x += this.x * scale;
  4862. result.y += this.y * scale;
  4863. result.z += this.z * scale;
  4864. result.w += this.w * scale;
  4865. return this;
  4866. };
  4867. /**
  4868. * Multiplies two quaternions
  4869. * @param q1 defines the second operand
  4870. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4871. */
  4872. Quaternion.prototype.multiply = function (q1) {
  4873. var result = new Quaternion(0, 0, 0, 1.0);
  4874. this.multiplyToRef(q1, result);
  4875. return result;
  4876. };
  4877. /**
  4878. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4879. * @param q1 defines the second operand
  4880. * @param result defines the target quaternion
  4881. * @returns the current quaternion
  4882. */
  4883. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4884. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4885. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4886. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4887. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4888. result.copyFromFloats(x, y, z, w);
  4889. return this;
  4890. };
  4891. /**
  4892. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4893. * @param q1 defines the second operand
  4894. * @returns the currentupdated quaternion
  4895. */
  4896. Quaternion.prototype.multiplyInPlace = function (q1) {
  4897. this.multiplyToRef(q1, this);
  4898. return this;
  4899. };
  4900. /**
  4901. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4902. * @param ref defines the target quaternion
  4903. * @returns the current quaternion
  4904. */
  4905. Quaternion.prototype.conjugateToRef = function (ref) {
  4906. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4907. return this;
  4908. };
  4909. /**
  4910. * Conjugates in place (1-q) the current quaternion
  4911. * @returns the current updated quaternion
  4912. */
  4913. Quaternion.prototype.conjugateInPlace = function () {
  4914. this.x *= -1;
  4915. this.y *= -1;
  4916. this.z *= -1;
  4917. return this;
  4918. };
  4919. /**
  4920. * Conjugates in place (1-q) the current quaternion
  4921. * @returns a new quaternion
  4922. */
  4923. Quaternion.prototype.conjugate = function () {
  4924. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4925. return result;
  4926. };
  4927. /**
  4928. * Gets length of current quaternion
  4929. * @returns the quaternion length (float)
  4930. */
  4931. Quaternion.prototype.length = function () {
  4932. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4933. };
  4934. /**
  4935. * Normalize in place the current quaternion
  4936. * @returns the current updated quaternion
  4937. */
  4938. Quaternion.prototype.normalize = function () {
  4939. var length = 1.0 / this.length();
  4940. this.x *= length;
  4941. this.y *= length;
  4942. this.z *= length;
  4943. this.w *= length;
  4944. return this;
  4945. };
  4946. /**
  4947. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4948. * @param order is a reserved parameter and is ignore for now
  4949. * @returns a new Vector3 containing the Euler angles
  4950. */
  4951. Quaternion.prototype.toEulerAngles = function (order) {
  4952. if (order === void 0) { order = "YZX"; }
  4953. var result = Vector3.Zero();
  4954. this.toEulerAnglesToRef(result, order);
  4955. return result;
  4956. };
  4957. /**
  4958. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4959. * @param result defines the vector which will be filled with the Euler angles
  4960. * @param order is a reserved parameter and is ignore for now
  4961. * @returns the current unchanged quaternion
  4962. */
  4963. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4964. if (order === void 0) { order = "YZX"; }
  4965. var qz = this.z;
  4966. var qx = this.x;
  4967. var qy = this.y;
  4968. var qw = this.w;
  4969. var sqw = qw * qw;
  4970. var sqz = qz * qz;
  4971. var sqx = qx * qx;
  4972. var sqy = qy * qy;
  4973. var zAxisY = qy * qz - qx * qw;
  4974. var limit = .4999999;
  4975. if (zAxisY < -limit) {
  4976. result.y = 2 * Math.atan2(qy, qw);
  4977. result.x = Math.PI / 2;
  4978. result.z = 0;
  4979. }
  4980. else if (zAxisY > limit) {
  4981. result.y = 2 * Math.atan2(qy, qw);
  4982. result.x = -Math.PI / 2;
  4983. result.z = 0;
  4984. }
  4985. else {
  4986. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4987. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4988. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4989. }
  4990. return this;
  4991. };
  4992. /**
  4993. * Updates the given rotation matrix with the current quaternion values
  4994. * @param result defines the target matrix
  4995. * @returns the current unchanged quaternion
  4996. */
  4997. Quaternion.prototype.toRotationMatrix = function (result) {
  4998. var xx = this.x * this.x;
  4999. var yy = this.y * this.y;
  5000. var zz = this.z * this.z;
  5001. var xy = this.x * this.y;
  5002. var zw = this.z * this.w;
  5003. var zx = this.z * this.x;
  5004. var yw = this.y * this.w;
  5005. var yz = this.y * this.z;
  5006. var xw = this.x * this.w;
  5007. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5008. result.m[1] = 2.0 * (xy + zw);
  5009. result.m[2] = 2.0 * (zx - yw);
  5010. result.m[3] = 0;
  5011. result.m[4] = 2.0 * (xy - zw);
  5012. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5013. result.m[6] = 2.0 * (yz + xw);
  5014. result.m[7] = 0;
  5015. result.m[8] = 2.0 * (zx + yw);
  5016. result.m[9] = 2.0 * (yz - xw);
  5017. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5018. result.m[11] = 0;
  5019. result.m[12] = 0;
  5020. result.m[13] = 0;
  5021. result.m[14] = 0;
  5022. result.m[15] = 1.0;
  5023. result._markAsUpdated();
  5024. return this;
  5025. };
  5026. /**
  5027. * Updates the current quaternion from the given rotation matrix values
  5028. * @param matrix defines the source matrix
  5029. * @returns the current updated quaternion
  5030. */
  5031. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5032. Quaternion.FromRotationMatrixToRef(matrix, this);
  5033. return this;
  5034. };
  5035. // Statics
  5036. /**
  5037. * Creates a new quaternion from a rotation matrix
  5038. * @param matrix defines the source matrix
  5039. * @returns a new quaternion created from the given rotation matrix values
  5040. */
  5041. Quaternion.FromRotationMatrix = function (matrix) {
  5042. var result = new Quaternion();
  5043. Quaternion.FromRotationMatrixToRef(matrix, result);
  5044. return result;
  5045. };
  5046. /**
  5047. * Updates the given quaternion with the given rotation matrix values
  5048. * @param matrix defines the source matrix
  5049. * @param result defines the target quaternion
  5050. */
  5051. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5052. var data = matrix.m;
  5053. var m11 = data[0], m12 = data[4], m13 = data[8];
  5054. var m21 = data[1], m22 = data[5], m23 = data[9];
  5055. var m31 = data[2], m32 = data[6], m33 = data[10];
  5056. var trace = m11 + m22 + m33;
  5057. var s;
  5058. if (trace > 0) {
  5059. s = 0.5 / Math.sqrt(trace + 1.0);
  5060. result.w = 0.25 / s;
  5061. result.x = (m32 - m23) * s;
  5062. result.y = (m13 - m31) * s;
  5063. result.z = (m21 - m12) * s;
  5064. }
  5065. else if (m11 > m22 && m11 > m33) {
  5066. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5067. result.w = (m32 - m23) / s;
  5068. result.x = 0.25 * s;
  5069. result.y = (m12 + m21) / s;
  5070. result.z = (m13 + m31) / s;
  5071. }
  5072. else if (m22 > m33) {
  5073. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5074. result.w = (m13 - m31) / s;
  5075. result.x = (m12 + m21) / s;
  5076. result.y = 0.25 * s;
  5077. result.z = (m23 + m32) / s;
  5078. }
  5079. else {
  5080. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5081. result.w = (m21 - m12) / s;
  5082. result.x = (m13 + m31) / s;
  5083. result.y = (m23 + m32) / s;
  5084. result.z = 0.25 * s;
  5085. }
  5086. };
  5087. /**
  5088. * Returns the dot product (float) between the quaternions "left" and "right"
  5089. * @param left defines the left operand
  5090. * @param right defines the right operand
  5091. * @returns the dot product
  5092. */
  5093. Quaternion.Dot = function (left, right) {
  5094. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5095. };
  5096. /**
  5097. * Checks if the two quaternions are close to each other
  5098. * @param quat0 defines the first quaternion to check
  5099. * @param quat1 defines the second quaternion to check
  5100. * @returns true if the two quaternions are close to each other
  5101. */
  5102. Quaternion.AreClose = function (quat0, quat1) {
  5103. var dot = Quaternion.Dot(quat0, quat1);
  5104. return dot >= 0;
  5105. };
  5106. /**
  5107. * Creates an empty quaternion
  5108. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5109. */
  5110. Quaternion.Zero = function () {
  5111. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5112. };
  5113. /**
  5114. * Inverse a given quaternion
  5115. * @param q defines the source quaternion
  5116. * @returns a new quaternion as the inverted current quaternion
  5117. */
  5118. Quaternion.Inverse = function (q) {
  5119. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5120. };
  5121. /**
  5122. * Creates an identity quaternion
  5123. * @returns the identity quaternion
  5124. */
  5125. Quaternion.Identity = function () {
  5126. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5127. };
  5128. /**
  5129. * Gets a boolean indicating if the given quaternion is identity
  5130. * @param quaternion defines the quaternion to check
  5131. * @returns true if the quaternion is identity
  5132. */
  5133. Quaternion.IsIdentity = function (quaternion) {
  5134. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5135. };
  5136. /**
  5137. * Creates a quaternion from a rotation around an axis
  5138. * @param axis defines the axis to use
  5139. * @param angle defines the angle to use
  5140. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5141. */
  5142. Quaternion.RotationAxis = function (axis, angle) {
  5143. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5144. };
  5145. /**
  5146. * Creates a rotation around an axis and stores it into the given quaternion
  5147. * @param axis defines the axis to use
  5148. * @param angle defines the angle to use
  5149. * @param result defines the target quaternion
  5150. * @returns the target quaternion
  5151. */
  5152. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5153. var sin = Math.sin(angle / 2);
  5154. axis.normalize();
  5155. result.w = Math.cos(angle / 2);
  5156. result.x = axis.x * sin;
  5157. result.y = axis.y * sin;
  5158. result.z = axis.z * sin;
  5159. return result;
  5160. };
  5161. /**
  5162. * Creates a new quaternion from data stored into an array
  5163. * @param array defines the data source
  5164. * @param offset defines the offset in the source array where the data starts
  5165. * @returns a new quaternion
  5166. */
  5167. Quaternion.FromArray = function (array, offset) {
  5168. if (!offset) {
  5169. offset = 0;
  5170. }
  5171. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5172. };
  5173. /**
  5174. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5175. * @param yaw defines the rotation around Y axis
  5176. * @param pitch defines the rotation around X axis
  5177. * @param roll defines the rotation around Z axis
  5178. * @returns the new quaternion
  5179. */
  5180. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5181. var q = new Quaternion();
  5182. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5183. return q;
  5184. };
  5185. /**
  5186. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5187. * @param yaw defines the rotation around Y axis
  5188. * @param pitch defines the rotation around X axis
  5189. * @param roll defines the rotation around Z axis
  5190. * @param result defines the target quaternion
  5191. */
  5192. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5193. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5194. var halfRoll = roll * 0.5;
  5195. var halfPitch = pitch * 0.5;
  5196. var halfYaw = yaw * 0.5;
  5197. var sinRoll = Math.sin(halfRoll);
  5198. var cosRoll = Math.cos(halfRoll);
  5199. var sinPitch = Math.sin(halfPitch);
  5200. var cosPitch = Math.cos(halfPitch);
  5201. var sinYaw = Math.sin(halfYaw);
  5202. var cosYaw = Math.cos(halfYaw);
  5203. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5204. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5205. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5206. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5207. };
  5208. /**
  5209. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5210. * @param alpha defines the rotation around first axis
  5211. * @param beta defines the rotation around second axis
  5212. * @param gamma defines the rotation around third axis
  5213. * @returns the new quaternion
  5214. */
  5215. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5216. var result = new Quaternion();
  5217. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5218. return result;
  5219. };
  5220. /**
  5221. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5222. * @param alpha defines the rotation around first axis
  5223. * @param beta defines the rotation around second axis
  5224. * @param gamma defines the rotation around third axis
  5225. * @param result defines the target quaternion
  5226. */
  5227. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5228. // Produces a quaternion from Euler angles in the z-x-z orientation
  5229. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5230. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5231. var halfBeta = beta * 0.5;
  5232. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5233. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5234. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5235. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5236. };
  5237. /**
  5238. * 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)
  5239. * @param axis1 defines the first axis
  5240. * @param axis2 defines the second axis
  5241. * @param axis3 defines the third axis
  5242. * @returns the new quaternion
  5243. */
  5244. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5245. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5246. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5247. return quat;
  5248. };
  5249. /**
  5250. * 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
  5251. * @param axis1 defines the first axis
  5252. * @param axis2 defines the second axis
  5253. * @param axis3 defines the third axis
  5254. * @param ref defines the target quaternion
  5255. */
  5256. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5257. var rotMat = MathTmp.Matrix[0];
  5258. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5259. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5260. };
  5261. /**
  5262. * Interpolates between two quaternions
  5263. * @param left defines first quaternion
  5264. * @param right defines second quaternion
  5265. * @param amount defines the gradient to use
  5266. * @returns the new interpolated quaternion
  5267. */
  5268. Quaternion.Slerp = function (left, right, amount) {
  5269. var result = Quaternion.Identity();
  5270. Quaternion.SlerpToRef(left, right, amount, result);
  5271. return result;
  5272. };
  5273. /**
  5274. * Interpolates between two quaternions and stores it into a target quaternion
  5275. * @param left defines first quaternion
  5276. * @param right defines second quaternion
  5277. * @param amount defines the gradient to use
  5278. * @param result defines the target quaternion
  5279. */
  5280. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5281. var num2;
  5282. var num3;
  5283. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5284. var flag = false;
  5285. if (num4 < 0) {
  5286. flag = true;
  5287. num4 = -num4;
  5288. }
  5289. if (num4 > 0.999999) {
  5290. num3 = 1 - amount;
  5291. num2 = flag ? -amount : amount;
  5292. }
  5293. else {
  5294. var num5 = Math.acos(num4);
  5295. var num6 = (1.0 / Math.sin(num5));
  5296. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5297. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5298. }
  5299. result.x = (num3 * left.x) + (num2 * right.x);
  5300. result.y = (num3 * left.y) + (num2 * right.y);
  5301. result.z = (num3 * left.z) + (num2 * right.z);
  5302. result.w = (num3 * left.w) + (num2 * right.w);
  5303. };
  5304. /**
  5305. * Interpolate between two quaternions using Hermite interpolation
  5306. * @param value1 defines first quaternion
  5307. * @param tangent1 defines the incoming tangent
  5308. * @param value2 defines second quaternion
  5309. * @param tangent2 defines the outgoing tangent
  5310. * @param amount defines the target quaternion
  5311. * @returns the new interpolated quaternion
  5312. */
  5313. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5314. var squared = amount * amount;
  5315. var cubed = amount * squared;
  5316. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5317. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5318. var part3 = (cubed - (2.0 * squared)) + amount;
  5319. var part4 = cubed - squared;
  5320. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5321. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5322. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5323. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5324. return new Quaternion(x, y, z, w);
  5325. };
  5326. return Quaternion;
  5327. }());
  5328. BABYLON.Quaternion = Quaternion;
  5329. /**
  5330. * Class used to store matrix data (4x4)
  5331. */
  5332. var Matrix = /** @class */ (function () {
  5333. /**
  5334. * Creates an empty matrix (filled with zeros)
  5335. */
  5336. function Matrix() {
  5337. this._isIdentity = false;
  5338. this._isIdentityDirty = true;
  5339. /**
  5340. * Gets or sets the internal data of the matrix
  5341. */
  5342. this.m = new Float32Array(16);
  5343. this._markAsUpdated();
  5344. }
  5345. /** @hidden */
  5346. Matrix.prototype._markAsUpdated = function () {
  5347. this.updateFlag = Matrix._updateFlagSeed++;
  5348. this._isIdentityDirty = true;
  5349. };
  5350. // Properties
  5351. /**
  5352. * Check if the current matrix is indentity
  5353. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5354. * @returns true is the matrix is the identity matrix
  5355. */
  5356. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5357. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5358. if (this._isIdentityDirty) {
  5359. this._isIdentityDirty = false;
  5360. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5361. this._isIdentity = false;
  5362. }
  5363. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5364. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5365. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5366. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5367. this._isIdentity = false;
  5368. }
  5369. else {
  5370. this._isIdentity = true;
  5371. }
  5372. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5373. this._isIdentity = false;
  5374. }
  5375. }
  5376. return this._isIdentity;
  5377. };
  5378. /**
  5379. * Gets the determinant of the matrix
  5380. * @returns the matrix determinant
  5381. */
  5382. Matrix.prototype.determinant = function () {
  5383. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5384. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5385. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5386. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5387. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5388. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5389. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5390. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5391. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5392. };
  5393. // Methods
  5394. /**
  5395. * Returns the matrix as a Float32Array
  5396. * @returns the matrix underlying array
  5397. */
  5398. Matrix.prototype.toArray = function () {
  5399. return this.m;
  5400. };
  5401. /**
  5402. * Returns the matrix as a Float32Array
  5403. * @returns the matrix underlying array.
  5404. */
  5405. Matrix.prototype.asArray = function () {
  5406. return this.toArray();
  5407. };
  5408. /**
  5409. * Inverts the current matrix in place
  5410. * @returns the current inverted matrix
  5411. */
  5412. Matrix.prototype.invert = function () {
  5413. this.invertToRef(this);
  5414. return this;
  5415. };
  5416. /**
  5417. * Sets all the matrix elements to zero
  5418. * @returns the current matrix
  5419. */
  5420. Matrix.prototype.reset = function () {
  5421. for (var index = 0; index < 16; index++) {
  5422. this.m[index] = 0.0;
  5423. }
  5424. this._markAsUpdated();
  5425. return this;
  5426. };
  5427. /**
  5428. * Adds the current matrix with a second one
  5429. * @param other defines the matrix to add
  5430. * @returns a new matrix as the addition of the current matrix and the given one
  5431. */
  5432. Matrix.prototype.add = function (other) {
  5433. var result = new Matrix();
  5434. this.addToRef(other, result);
  5435. return result;
  5436. };
  5437. /**
  5438. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5439. * @param other defines the matrix to add
  5440. * @param result defines the target matrix
  5441. * @returns the current matrix
  5442. */
  5443. Matrix.prototype.addToRef = function (other, result) {
  5444. for (var index = 0; index < 16; index++) {
  5445. result.m[index] = this.m[index] + other.m[index];
  5446. }
  5447. result._markAsUpdated();
  5448. return this;
  5449. };
  5450. /**
  5451. * Adds in place the given matrix to the current matrix
  5452. * @param other defines the second operand
  5453. * @returns the current updated matrix
  5454. */
  5455. Matrix.prototype.addToSelf = function (other) {
  5456. for (var index = 0; index < 16; index++) {
  5457. this.m[index] += other.m[index];
  5458. }
  5459. this._markAsUpdated();
  5460. return this;
  5461. };
  5462. /**
  5463. * Sets the given matrix to the current inverted Matrix
  5464. * @param other defines the target matrix
  5465. * @returns the unmodified current matrix
  5466. */
  5467. Matrix.prototype.invertToRef = function (other) {
  5468. var l1 = this.m[0];
  5469. var l2 = this.m[1];
  5470. var l3 = this.m[2];
  5471. var l4 = this.m[3];
  5472. var l5 = this.m[4];
  5473. var l6 = this.m[5];
  5474. var l7 = this.m[6];
  5475. var l8 = this.m[7];
  5476. var l9 = this.m[8];
  5477. var l10 = this.m[9];
  5478. var l11 = this.m[10];
  5479. var l12 = this.m[11];
  5480. var l13 = this.m[12];
  5481. var l14 = this.m[13];
  5482. var l15 = this.m[14];
  5483. var l16 = this.m[15];
  5484. var l17 = (l11 * l16) - (l12 * l15);
  5485. var l18 = (l10 * l16) - (l12 * l14);
  5486. var l19 = (l10 * l15) - (l11 * l14);
  5487. var l20 = (l9 * l16) - (l12 * l13);
  5488. var l21 = (l9 * l15) - (l11 * l13);
  5489. var l22 = (l9 * l14) - (l10 * l13);
  5490. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5491. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5492. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5493. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5494. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5495. var l28 = (l7 * l16) - (l8 * l15);
  5496. var l29 = (l6 * l16) - (l8 * l14);
  5497. var l30 = (l6 * l15) - (l7 * l14);
  5498. var l31 = (l5 * l16) - (l8 * l13);
  5499. var l32 = (l5 * l15) - (l7 * l13);
  5500. var l33 = (l5 * l14) - (l6 * l13);
  5501. var l34 = (l7 * l12) - (l8 * l11);
  5502. var l35 = (l6 * l12) - (l8 * l10);
  5503. var l36 = (l6 * l11) - (l7 * l10);
  5504. var l37 = (l5 * l12) - (l8 * l9);
  5505. var l38 = (l5 * l11) - (l7 * l9);
  5506. var l39 = (l5 * l10) - (l6 * l9);
  5507. other.m[0] = l23 * l27;
  5508. other.m[4] = l24 * l27;
  5509. other.m[8] = l25 * l27;
  5510. other.m[12] = l26 * l27;
  5511. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5512. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5513. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5514. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5515. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5516. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5517. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5518. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5519. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5520. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5521. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5522. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5523. other._markAsUpdated();
  5524. return this;
  5525. };
  5526. /**
  5527. * Inserts the translation vector (using 3 floats) in the current matrix
  5528. * @param x defines the 1st component of the translation
  5529. * @param y defines the 2nd component of the translation
  5530. * @param z defines the 3rd component of the translation
  5531. * @returns the current updated matrix
  5532. */
  5533. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5534. this.m[12] = x;
  5535. this.m[13] = y;
  5536. this.m[14] = z;
  5537. this._markAsUpdated();
  5538. return this;
  5539. };
  5540. /**
  5541. * Inserts the translation vector in the current matrix
  5542. * @param vector3 defines the translation to insert
  5543. * @returns the current updated matrix
  5544. */
  5545. Matrix.prototype.setTranslation = function (vector3) {
  5546. this.m[12] = vector3.x;
  5547. this.m[13] = vector3.y;
  5548. this.m[14] = vector3.z;
  5549. this._markAsUpdated();
  5550. return this;
  5551. };
  5552. /**
  5553. * Gets the translation value of the current matrix
  5554. * @returns a new Vector3 as the extracted translation from the matrix
  5555. */
  5556. Matrix.prototype.getTranslation = function () {
  5557. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5558. };
  5559. /**
  5560. * Fill a Vector3 with the extracted translation from the matrix
  5561. * @param result defines the Vector3 where to store the translation
  5562. * @returns the current matrix
  5563. */
  5564. Matrix.prototype.getTranslationToRef = function (result) {
  5565. result.x = this.m[12];
  5566. result.y = this.m[13];
  5567. result.z = this.m[14];
  5568. return this;
  5569. };
  5570. /**
  5571. * Remove rotation and scaling part from the matrix
  5572. * @returns the updated matrix
  5573. */
  5574. Matrix.prototype.removeRotationAndScaling = function () {
  5575. this.setRowFromFloats(0, 1, 0, 0, 0);
  5576. this.setRowFromFloats(1, 0, 1, 0, 0);
  5577. this.setRowFromFloats(2, 0, 0, 1, 0);
  5578. return this;
  5579. };
  5580. /**
  5581. * Multiply two matrices
  5582. * @param other defines the second operand
  5583. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5584. */
  5585. Matrix.prototype.multiply = function (other) {
  5586. var result = new Matrix();
  5587. this.multiplyToRef(other, result);
  5588. return result;
  5589. };
  5590. /**
  5591. * Copy the current matrix from the given one
  5592. * @param other defines the source matrix
  5593. * @returns the current updated matrix
  5594. */
  5595. Matrix.prototype.copyFrom = function (other) {
  5596. for (var index = 0; index < 16; index++) {
  5597. this.m[index] = other.m[index];
  5598. }
  5599. this._markAsUpdated();
  5600. return this;
  5601. };
  5602. /**
  5603. * Populates the given array from the starting index with the current matrix values
  5604. * @param array defines the target array
  5605. * @param offset defines the offset in the target array where to start storing values
  5606. * @returns the current matrix
  5607. */
  5608. Matrix.prototype.copyToArray = function (array, offset) {
  5609. if (offset === void 0) { offset = 0; }
  5610. for (var index = 0; index < 16; index++) {
  5611. array[offset + index] = this.m[index];
  5612. }
  5613. return this;
  5614. };
  5615. /**
  5616. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5617. * @param other defines the second operand
  5618. * @param result defines the matrix where to store the multiplication
  5619. * @returns the current matrix
  5620. */
  5621. Matrix.prototype.multiplyToRef = function (other, result) {
  5622. this.multiplyToArray(other, result.m, 0);
  5623. result._markAsUpdated();
  5624. return this;
  5625. };
  5626. /**
  5627. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5628. * @param other defines the second operand
  5629. * @param result defines the array where to store the multiplication
  5630. * @param offset defines the offset in the target array where to start storing values
  5631. * @returns the current matrix
  5632. */
  5633. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5634. var tm0 = this.m[0];
  5635. var tm1 = this.m[1];
  5636. var tm2 = this.m[2];
  5637. var tm3 = this.m[3];
  5638. var tm4 = this.m[4];
  5639. var tm5 = this.m[5];
  5640. var tm6 = this.m[6];
  5641. var tm7 = this.m[7];
  5642. var tm8 = this.m[8];
  5643. var tm9 = this.m[9];
  5644. var tm10 = this.m[10];
  5645. var tm11 = this.m[11];
  5646. var tm12 = this.m[12];
  5647. var tm13 = this.m[13];
  5648. var tm14 = this.m[14];
  5649. var tm15 = this.m[15];
  5650. var om0 = other.m[0];
  5651. var om1 = other.m[1];
  5652. var om2 = other.m[2];
  5653. var om3 = other.m[3];
  5654. var om4 = other.m[4];
  5655. var om5 = other.m[5];
  5656. var om6 = other.m[6];
  5657. var om7 = other.m[7];
  5658. var om8 = other.m[8];
  5659. var om9 = other.m[9];
  5660. var om10 = other.m[10];
  5661. var om11 = other.m[11];
  5662. var om12 = other.m[12];
  5663. var om13 = other.m[13];
  5664. var om14 = other.m[14];
  5665. var om15 = other.m[15];
  5666. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5667. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5668. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5669. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5670. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5671. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5672. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5673. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5674. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5675. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5676. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5677. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5678. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5679. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5680. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5681. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5682. return this;
  5683. };
  5684. /**
  5685. * Check equality between this matrix and a second one
  5686. * @param value defines the second matrix to compare
  5687. * @returns true is the current matrix and the given one values are strictly equal
  5688. */
  5689. Matrix.prototype.equals = function (value) {
  5690. return value &&
  5691. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5692. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5693. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5694. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5695. };
  5696. /**
  5697. * Clone the current matrix
  5698. * @returns a new matrix from the current matrix
  5699. */
  5700. Matrix.prototype.clone = function () {
  5701. 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]);
  5702. };
  5703. /**
  5704. * Returns the name of the current matrix class
  5705. * @returns the string "Matrix"
  5706. */
  5707. Matrix.prototype.getClassName = function () {
  5708. return "Matrix";
  5709. };
  5710. /**
  5711. * Gets the hash code of the current matrix
  5712. * @returns the hash code
  5713. */
  5714. Matrix.prototype.getHashCode = function () {
  5715. var hash = this.m[0] || 0;
  5716. for (var i = 1; i < 16; i++) {
  5717. hash = (hash * 397) ^ (this.m[i] || 0);
  5718. }
  5719. return hash;
  5720. };
  5721. /**
  5722. * Decomposes the current Matrix into a translation, rotation and scaling components
  5723. * @param scale defines the scale vector3 given as a reference to update
  5724. * @param rotation defines the rotation quaternion given as a reference to update
  5725. * @param translation defines the translation vector3 given as a reference to update
  5726. * @returns true if operation was successful
  5727. */
  5728. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5729. if (translation) {
  5730. translation.x = this.m[12];
  5731. translation.y = this.m[13];
  5732. translation.z = this.m[14];
  5733. }
  5734. scale = scale || MathTmp.Vector3[0];
  5735. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5736. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5737. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5738. if (this.determinant() <= 0) {
  5739. scale.y *= -1;
  5740. }
  5741. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5742. if (rotation) {
  5743. rotation.x = 0;
  5744. rotation.y = 0;
  5745. rotation.z = 0;
  5746. rotation.w = 1;
  5747. }
  5748. return false;
  5749. }
  5750. if (rotation) {
  5751. 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]);
  5752. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5753. }
  5754. return true;
  5755. };
  5756. /**
  5757. * Gets specific row of the matrix
  5758. * @param index defines the number of the row to get
  5759. * @returns the index-th row of the current matrix as a new Vector4
  5760. */
  5761. Matrix.prototype.getRow = function (index) {
  5762. if (index < 0 || index > 3) {
  5763. return null;
  5764. }
  5765. var i = index * 4;
  5766. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5767. };
  5768. /**
  5769. * Sets the index-th row of the current matrix to the vector4 values
  5770. * @param index defines the number of the row to set
  5771. * @param row defines the target vector4
  5772. * @returns the updated current matrix
  5773. */
  5774. Matrix.prototype.setRow = function (index, row) {
  5775. if (index < 0 || index > 3) {
  5776. return this;
  5777. }
  5778. var i = index * 4;
  5779. this.m[i + 0] = row.x;
  5780. this.m[i + 1] = row.y;
  5781. this.m[i + 2] = row.z;
  5782. this.m[i + 3] = row.w;
  5783. this._markAsUpdated();
  5784. return this;
  5785. };
  5786. /**
  5787. * Compute the transpose of the matrix
  5788. * @returns the new transposed matrix
  5789. */
  5790. Matrix.prototype.transpose = function () {
  5791. return Matrix.Transpose(this);
  5792. };
  5793. /**
  5794. * Compute the transpose of the matrix and store it in a given matrix
  5795. * @param result defines the target matrix
  5796. * @returns the current matrix
  5797. */
  5798. Matrix.prototype.transposeToRef = function (result) {
  5799. Matrix.TransposeToRef(this, result);
  5800. return this;
  5801. };
  5802. /**
  5803. * Sets the index-th row of the current matrix with the given 4 x float values
  5804. * @param index defines the row index
  5805. * @param x defines the x component to set
  5806. * @param y defines the y component to set
  5807. * @param z defines the z component to set
  5808. * @param w defines the w component to set
  5809. * @returns the updated current matrix
  5810. */
  5811. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5812. if (index < 0 || index > 3) {
  5813. return this;
  5814. }
  5815. var i = index * 4;
  5816. this.m[i + 0] = x;
  5817. this.m[i + 1] = y;
  5818. this.m[i + 2] = z;
  5819. this.m[i + 3] = w;
  5820. this._markAsUpdated();
  5821. return this;
  5822. };
  5823. /**
  5824. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5825. * @param scale defines the scale factor
  5826. * @returns a new matrix
  5827. */
  5828. Matrix.prototype.scale = function (scale) {
  5829. var result = new Matrix();
  5830. this.scaleToRef(scale, result);
  5831. return result;
  5832. };
  5833. /**
  5834. * Scale the current matrix values by a factor to a given result matrix
  5835. * @param scale defines the scale factor
  5836. * @param result defines the matrix to store the result
  5837. * @returns the current matrix
  5838. */
  5839. Matrix.prototype.scaleToRef = function (scale, result) {
  5840. for (var index = 0; index < 16; index++) {
  5841. result.m[index] = this.m[index] * scale;
  5842. }
  5843. result._markAsUpdated();
  5844. return this;
  5845. };
  5846. /**
  5847. * Scale the current matrix values by a factor and add the result to a given matrix
  5848. * @param scale defines the scale factor
  5849. * @param result defines the Matrix to store the result
  5850. * @returns the current matrix
  5851. */
  5852. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5853. for (var index = 0; index < 16; index++) {
  5854. result.m[index] += this.m[index] * scale;
  5855. }
  5856. result._markAsUpdated();
  5857. return this;
  5858. };
  5859. /**
  5860. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5861. * @param ref matrix to store the result
  5862. */
  5863. Matrix.prototype.toNormalMatrix = function (ref) {
  5864. this.invertToRef(ref);
  5865. ref.transpose();
  5866. var m = ref.m;
  5867. 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);
  5868. };
  5869. /**
  5870. * Gets only rotation part of the current matrix
  5871. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5872. */
  5873. Matrix.prototype.getRotationMatrix = function () {
  5874. var result = Matrix.Identity();
  5875. this.getRotationMatrixToRef(result);
  5876. return result;
  5877. };
  5878. /**
  5879. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5880. * @param result defines the target matrix to store data to
  5881. * @returns the current matrix
  5882. */
  5883. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5884. var m = this.m;
  5885. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5886. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5887. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5888. if (this.determinant() <= 0) {
  5889. sy *= -1;
  5890. }
  5891. if (sx === 0 || sy === 0 || sz === 0) {
  5892. Matrix.IdentityToRef(result);
  5893. }
  5894. else {
  5895. 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);
  5896. }
  5897. return this;
  5898. };
  5899. // Statics
  5900. /**
  5901. * Creates a matrix from an array
  5902. * @param array defines the source array
  5903. * @param offset defines an offset in the source array
  5904. * @returns a new Matrix set from the starting index of the given array
  5905. */
  5906. Matrix.FromArray = function (array, offset) {
  5907. var result = new Matrix();
  5908. if (!offset) {
  5909. offset = 0;
  5910. }
  5911. Matrix.FromArrayToRef(array, offset, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Copy the content of an array into a given matrix
  5916. * @param array defines the source array
  5917. * @param offset defines an offset in the source array
  5918. * @param result defines the target matrix
  5919. */
  5920. Matrix.FromArrayToRef = function (array, offset, result) {
  5921. for (var index = 0; index < 16; index++) {
  5922. result.m[index] = array[index + offset];
  5923. }
  5924. result._markAsUpdated();
  5925. };
  5926. /**
  5927. * Stores an array into a matrix after having multiplied each component by a given factor
  5928. * @param array defines the source array
  5929. * @param offset defines the offset in the source array
  5930. * @param scale defines the scaling factor
  5931. * @param result defines the target matrix
  5932. */
  5933. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5934. for (var index = 0; index < 16; index++) {
  5935. result.m[index] = array[index + offset] * scale;
  5936. }
  5937. result._markAsUpdated();
  5938. };
  5939. /**
  5940. * Stores a list of values (16) inside a given matrix
  5941. * @param initialM11 defines 1st value of 1st row
  5942. * @param initialM12 defines 2nd value of 1st row
  5943. * @param initialM13 defines 3rd value of 1st row
  5944. * @param initialM14 defines 4th value of 1st row
  5945. * @param initialM21 defines 1st value of 2nd row
  5946. * @param initialM22 defines 2nd value of 2nd row
  5947. * @param initialM23 defines 3rd value of 2nd row
  5948. * @param initialM24 defines 4th value of 2nd row
  5949. * @param initialM31 defines 1st value of 3rd row
  5950. * @param initialM32 defines 2nd value of 3rd row
  5951. * @param initialM33 defines 3rd value of 3rd row
  5952. * @param initialM34 defines 4th value of 3rd row
  5953. * @param initialM41 defines 1st value of 4th row
  5954. * @param initialM42 defines 2nd value of 4th row
  5955. * @param initialM43 defines 3rd value of 4th row
  5956. * @param initialM44 defines 4th value of 4th row
  5957. * @param result defines the target matrix
  5958. */
  5959. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5960. result.m[0] = initialM11;
  5961. result.m[1] = initialM12;
  5962. result.m[2] = initialM13;
  5963. result.m[3] = initialM14;
  5964. result.m[4] = initialM21;
  5965. result.m[5] = initialM22;
  5966. result.m[6] = initialM23;
  5967. result.m[7] = initialM24;
  5968. result.m[8] = initialM31;
  5969. result.m[9] = initialM32;
  5970. result.m[10] = initialM33;
  5971. result.m[11] = initialM34;
  5972. result.m[12] = initialM41;
  5973. result.m[13] = initialM42;
  5974. result.m[14] = initialM43;
  5975. result.m[15] = initialM44;
  5976. result._markAsUpdated();
  5977. };
  5978. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5979. /**
  5980. * Gets an identity matrix that must not be updated
  5981. */
  5982. get: function () {
  5983. return Matrix._identityReadOnly;
  5984. },
  5985. enumerable: true,
  5986. configurable: true
  5987. });
  5988. /**
  5989. * Creates new matrix from a list of values (16)
  5990. * @param initialM11 defines 1st value of 1st row
  5991. * @param initialM12 defines 2nd value of 1st row
  5992. * @param initialM13 defines 3rd value of 1st row
  5993. * @param initialM14 defines 4th value of 1st row
  5994. * @param initialM21 defines 1st value of 2nd row
  5995. * @param initialM22 defines 2nd value of 2nd row
  5996. * @param initialM23 defines 3rd value of 2nd row
  5997. * @param initialM24 defines 4th value of 2nd row
  5998. * @param initialM31 defines 1st value of 3rd row
  5999. * @param initialM32 defines 2nd value of 3rd row
  6000. * @param initialM33 defines 3rd value of 3rd row
  6001. * @param initialM34 defines 4th value of 3rd row
  6002. * @param initialM41 defines 1st value of 4th row
  6003. * @param initialM42 defines 2nd value of 4th row
  6004. * @param initialM43 defines 3rd value of 4th row
  6005. * @param initialM44 defines 4th value of 4th row
  6006. * @returns the new matrix
  6007. */
  6008. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  6009. var result = new Matrix();
  6010. result.m[0] = initialM11;
  6011. result.m[1] = initialM12;
  6012. result.m[2] = initialM13;
  6013. result.m[3] = initialM14;
  6014. result.m[4] = initialM21;
  6015. result.m[5] = initialM22;
  6016. result.m[6] = initialM23;
  6017. result.m[7] = initialM24;
  6018. result.m[8] = initialM31;
  6019. result.m[9] = initialM32;
  6020. result.m[10] = initialM33;
  6021. result.m[11] = initialM34;
  6022. result.m[12] = initialM41;
  6023. result.m[13] = initialM42;
  6024. result.m[14] = initialM43;
  6025. result.m[15] = initialM44;
  6026. return result;
  6027. };
  6028. /**
  6029. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6030. * @param scale defines the scale vector3
  6031. * @param rotation defines the rotation quaternion
  6032. * @param translation defines the translation vector3
  6033. * @returns a new matrix
  6034. */
  6035. Matrix.Compose = function (scale, rotation, translation) {
  6036. var result = Matrix.Identity();
  6037. Matrix.ComposeToRef(scale, rotation, translation, result);
  6038. return result;
  6039. };
  6040. /**
  6041. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6042. * @param scale defines the scale vector3
  6043. * @param rotation defines the rotation quaternion
  6044. * @param translation defines the translation vector3
  6045. * @param result defines the target matrix
  6046. */
  6047. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6048. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6049. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6050. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6051. result.setTranslation(translation);
  6052. };
  6053. /**
  6054. * Creates a new identity matrix
  6055. * @returns a new identity matrix
  6056. */
  6057. Matrix.Identity = function () {
  6058. 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);
  6059. };
  6060. /**
  6061. * Creates a new identity matrix and stores the result in a given matrix
  6062. * @param result defines the target matrix
  6063. */
  6064. Matrix.IdentityToRef = function (result) {
  6065. 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);
  6066. };
  6067. /**
  6068. * Creates a new zero matrix
  6069. * @returns a new zero matrix
  6070. */
  6071. Matrix.Zero = function () {
  6072. 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);
  6073. };
  6074. /**
  6075. * Creates a new rotation matrix for "angle" radians around the X axis
  6076. * @param angle defines the angle (in radians) to use
  6077. * @return the new matrix
  6078. */
  6079. Matrix.RotationX = function (angle) {
  6080. var result = new Matrix();
  6081. Matrix.RotationXToRef(angle, result);
  6082. return result;
  6083. };
  6084. /**
  6085. * Creates a new matrix as the invert of a given matrix
  6086. * @param source defines the source matrix
  6087. * @returns the new matrix
  6088. */
  6089. Matrix.Invert = function (source) {
  6090. var result = new Matrix();
  6091. source.invertToRef(result);
  6092. return result;
  6093. };
  6094. /**
  6095. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6096. * @param angle defines the angle (in radians) to use
  6097. * @param result defines the target matrix
  6098. */
  6099. Matrix.RotationXToRef = function (angle, result) {
  6100. var s = Math.sin(angle);
  6101. var c = Math.cos(angle);
  6102. result.m[0] = 1.0;
  6103. result.m[15] = 1.0;
  6104. result.m[5] = c;
  6105. result.m[10] = c;
  6106. result.m[9] = -s;
  6107. result.m[6] = s;
  6108. result.m[1] = 0.0;
  6109. result.m[2] = 0.0;
  6110. result.m[3] = 0.0;
  6111. result.m[4] = 0.0;
  6112. result.m[7] = 0.0;
  6113. result.m[8] = 0.0;
  6114. result.m[11] = 0.0;
  6115. result.m[12] = 0.0;
  6116. result.m[13] = 0.0;
  6117. result.m[14] = 0.0;
  6118. result._markAsUpdated();
  6119. };
  6120. /**
  6121. * Creates a new rotation matrix for "angle" radians around the Y axis
  6122. * @param angle defines the angle (in radians) to use
  6123. * @return the new matrix
  6124. */
  6125. Matrix.RotationY = function (angle) {
  6126. var result = new Matrix();
  6127. Matrix.RotationYToRef(angle, result);
  6128. return result;
  6129. };
  6130. /**
  6131. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6132. * @param angle defines the angle (in radians) to use
  6133. * @param result defines the target matrix
  6134. */
  6135. Matrix.RotationYToRef = function (angle, result) {
  6136. var s = Math.sin(angle);
  6137. var c = Math.cos(angle);
  6138. result.m[5] = 1.0;
  6139. result.m[15] = 1.0;
  6140. result.m[0] = c;
  6141. result.m[2] = -s;
  6142. result.m[8] = s;
  6143. result.m[10] = c;
  6144. result.m[1] = 0.0;
  6145. result.m[3] = 0.0;
  6146. result.m[4] = 0.0;
  6147. result.m[6] = 0.0;
  6148. result.m[7] = 0.0;
  6149. result.m[9] = 0.0;
  6150. result.m[11] = 0.0;
  6151. result.m[12] = 0.0;
  6152. result.m[13] = 0.0;
  6153. result.m[14] = 0.0;
  6154. result._markAsUpdated();
  6155. };
  6156. /**
  6157. * Creates a new rotation matrix for "angle" radians around the Z axis
  6158. * @param angle defines the angle (in radians) to use
  6159. * @return the new matrix
  6160. */
  6161. Matrix.RotationZ = function (angle) {
  6162. var result = new Matrix();
  6163. Matrix.RotationZToRef(angle, result);
  6164. return result;
  6165. };
  6166. /**
  6167. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6168. * @param angle defines the angle (in radians) to use
  6169. * @param result defines the target matrix
  6170. */
  6171. Matrix.RotationZToRef = function (angle, result) {
  6172. var s = Math.sin(angle);
  6173. var c = Math.cos(angle);
  6174. result.m[10] = 1.0;
  6175. result.m[15] = 1.0;
  6176. result.m[0] = c;
  6177. result.m[1] = s;
  6178. result.m[4] = -s;
  6179. result.m[5] = c;
  6180. result.m[2] = 0.0;
  6181. result.m[3] = 0.0;
  6182. result.m[6] = 0.0;
  6183. result.m[7] = 0.0;
  6184. result.m[8] = 0.0;
  6185. result.m[9] = 0.0;
  6186. result.m[11] = 0.0;
  6187. result.m[12] = 0.0;
  6188. result.m[13] = 0.0;
  6189. result.m[14] = 0.0;
  6190. result._markAsUpdated();
  6191. };
  6192. /**
  6193. * Creates a new rotation matrix for "angle" radians around the given axis
  6194. * @param axis defines the axis to use
  6195. * @param angle defines the angle (in radians) to use
  6196. * @return the new matrix
  6197. */
  6198. Matrix.RotationAxis = function (axis, angle) {
  6199. var result = Matrix.Zero();
  6200. Matrix.RotationAxisToRef(axis, angle, result);
  6201. return result;
  6202. };
  6203. /**
  6204. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6205. * @param axis defines the axis to use
  6206. * @param angle defines the angle (in radians) to use
  6207. * @param result defines the target matrix
  6208. */
  6209. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6210. var s = Math.sin(-angle);
  6211. var c = Math.cos(-angle);
  6212. var c1 = 1 - c;
  6213. axis.normalize();
  6214. result.m[0] = (axis.x * axis.x) * c1 + c;
  6215. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6216. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6217. result.m[3] = 0.0;
  6218. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6219. result.m[5] = (axis.y * axis.y) * c1 + c;
  6220. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6221. result.m[7] = 0.0;
  6222. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6223. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6224. result.m[10] = (axis.z * axis.z) * c1 + c;
  6225. result.m[11] = 0.0;
  6226. result.m[15] = 1.0;
  6227. result._markAsUpdated();
  6228. };
  6229. /**
  6230. * Creates a rotation matrix
  6231. * @param yaw defines the yaw angle in radians (Y axis)
  6232. * @param pitch defines the pitch angle in radians (X axis)
  6233. * @param roll defines the roll angle in radians (X axis)
  6234. * @returns the new rotation matrix
  6235. */
  6236. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6237. var result = new Matrix();
  6238. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6239. return result;
  6240. };
  6241. /**
  6242. * Creates a rotation matrix and stores it in a given matrix
  6243. * @param yaw defines the yaw angle in radians (Y axis)
  6244. * @param pitch defines the pitch angle in radians (X axis)
  6245. * @param roll defines the roll angle in radians (X axis)
  6246. * @param result defines the target matrix
  6247. */
  6248. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6249. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6250. this._tempQuaternion.toRotationMatrix(result);
  6251. };
  6252. /**
  6253. * Creates a scaling matrix
  6254. * @param x defines the scale factor on X axis
  6255. * @param y defines the scale factor on Y axis
  6256. * @param z defines the scale factor on Z axis
  6257. * @returns the new matrix
  6258. */
  6259. Matrix.Scaling = function (x, y, z) {
  6260. var result = Matrix.Zero();
  6261. Matrix.ScalingToRef(x, y, z, result);
  6262. return result;
  6263. };
  6264. /**
  6265. * Creates a scaling matrix and stores it in a given matrix
  6266. * @param x defines the scale factor on X axis
  6267. * @param y defines the scale factor on Y axis
  6268. * @param z defines the scale factor on Z axis
  6269. * @param result defines the target matrix
  6270. */
  6271. Matrix.ScalingToRef = function (x, y, z, result) {
  6272. result.m[0] = x;
  6273. result.m[1] = 0.0;
  6274. result.m[2] = 0.0;
  6275. result.m[3] = 0.0;
  6276. result.m[4] = 0.0;
  6277. result.m[5] = y;
  6278. result.m[6] = 0.0;
  6279. result.m[7] = 0.0;
  6280. result.m[8] = 0.0;
  6281. result.m[9] = 0.0;
  6282. result.m[10] = z;
  6283. result.m[11] = 0.0;
  6284. result.m[12] = 0.0;
  6285. result.m[13] = 0.0;
  6286. result.m[14] = 0.0;
  6287. result.m[15] = 1.0;
  6288. result._markAsUpdated();
  6289. };
  6290. /**
  6291. * Creates a translation matrix
  6292. * @param x defines the translation on X axis
  6293. * @param y defines the translation on Y axis
  6294. * @param z defines the translationon Z axis
  6295. * @returns the new matrix
  6296. */
  6297. Matrix.Translation = function (x, y, z) {
  6298. var result = Matrix.Identity();
  6299. Matrix.TranslationToRef(x, y, z, result);
  6300. return result;
  6301. };
  6302. /**
  6303. * Creates a translation matrix and stores it in a given matrix
  6304. * @param x defines the translation on X axis
  6305. * @param y defines the translation on Y axis
  6306. * @param z defines the translationon Z axis
  6307. * @param result defines the target matrix
  6308. */
  6309. Matrix.TranslationToRef = function (x, y, z, result) {
  6310. 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);
  6311. };
  6312. /**
  6313. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6314. * @param startValue defines the start value
  6315. * @param endValue defines the end value
  6316. * @param gradient defines the gradient factor
  6317. * @returns the new matrix
  6318. */
  6319. Matrix.Lerp = function (startValue, endValue, gradient) {
  6320. var result = Matrix.Zero();
  6321. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6322. return result;
  6323. };
  6324. /**
  6325. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6326. * @param startValue defines the start value
  6327. * @param endValue defines the end value
  6328. * @param gradient defines the gradient factor
  6329. * @param result defines the Matrix object where to store data
  6330. */
  6331. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6332. for (var index = 0; index < 16; index++) {
  6333. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6334. }
  6335. result._markAsUpdated();
  6336. };
  6337. /**
  6338. * Builds a new matrix whose values are computed by:
  6339. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6340. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6341. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6342. * @param startValue defines the first matrix
  6343. * @param endValue defines the second matrix
  6344. * @param gradient defines the gradient between the two matrices
  6345. * @returns the new matrix
  6346. */
  6347. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6348. var result = Matrix.Zero();
  6349. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6350. return result;
  6351. };
  6352. /**
  6353. * Update a matrix to values which are computed by:
  6354. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6355. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6356. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6357. * @param startValue defines the first matrix
  6358. * @param endValue defines the second matrix
  6359. * @param gradient defines the gradient between the two matrices
  6360. * @param result defines the target matrix
  6361. */
  6362. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6363. var startScale = MathTmp.Vector3[0];
  6364. var startRotation = MathTmp.Quaternion[0];
  6365. var startTranslation = MathTmp.Vector3[1];
  6366. startValue.decompose(startScale, startRotation, startTranslation);
  6367. var endScale = MathTmp.Vector3[2];
  6368. var endRotation = MathTmp.Quaternion[1];
  6369. var endTranslation = MathTmp.Vector3[3];
  6370. endValue.decompose(endScale, endRotation, endTranslation);
  6371. var resultScale = MathTmp.Vector3[4];
  6372. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6373. var resultRotation = MathTmp.Quaternion[2];
  6374. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6375. var resultTranslation = MathTmp.Vector3[5];
  6376. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6377. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6378. };
  6379. /**
  6380. * 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"
  6381. * This function works in left handed mode
  6382. * @param eye defines the final position of the entity
  6383. * @param target defines where the entity should look at
  6384. * @param up defines the up vector for the entity
  6385. * @returns the new matrix
  6386. */
  6387. Matrix.LookAtLH = function (eye, target, up) {
  6388. var result = Matrix.Zero();
  6389. Matrix.LookAtLHToRef(eye, target, up, result);
  6390. return result;
  6391. };
  6392. /**
  6393. * 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".
  6394. * This function works in left handed mode
  6395. * @param eye defines the final position of the entity
  6396. * @param target defines where the entity should look at
  6397. * @param up defines the up vector for the entity
  6398. * @param result defines the target matrix
  6399. */
  6400. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6401. // Z axis
  6402. target.subtractToRef(eye, this._zAxis);
  6403. this._zAxis.normalize();
  6404. // X axis
  6405. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6406. if (this._xAxis.lengthSquared() === 0) {
  6407. this._xAxis.x = 1.0;
  6408. }
  6409. else {
  6410. this._xAxis.normalize();
  6411. }
  6412. // Y axis
  6413. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6414. this._yAxis.normalize();
  6415. // Eye angles
  6416. var ex = -Vector3.Dot(this._xAxis, eye);
  6417. var ey = -Vector3.Dot(this._yAxis, eye);
  6418. var ez = -Vector3.Dot(this._zAxis, eye);
  6419. 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);
  6420. };
  6421. /**
  6422. * 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"
  6423. * This function works in right handed mode
  6424. * @param eye defines the final position of the entity
  6425. * @param target defines where the entity should look at
  6426. * @param up defines the up vector for the entity
  6427. * @returns the new matrix
  6428. */
  6429. Matrix.LookAtRH = function (eye, target, up) {
  6430. var result = Matrix.Zero();
  6431. Matrix.LookAtRHToRef(eye, target, up, result);
  6432. return result;
  6433. };
  6434. /**
  6435. * 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".
  6436. * This function works in right handed mode
  6437. * @param eye defines the final position of the entity
  6438. * @param target defines where the entity should look at
  6439. * @param up defines the up vector for the entity
  6440. * @param result defines the target matrix
  6441. */
  6442. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6443. // Z axis
  6444. eye.subtractToRef(target, this._zAxis);
  6445. this._zAxis.normalize();
  6446. // X axis
  6447. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6448. if (this._xAxis.lengthSquared() === 0) {
  6449. this._xAxis.x = 1.0;
  6450. }
  6451. else {
  6452. this._xAxis.normalize();
  6453. }
  6454. // Y axis
  6455. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6456. this._yAxis.normalize();
  6457. // Eye angles
  6458. var ex = -Vector3.Dot(this._xAxis, eye);
  6459. var ey = -Vector3.Dot(this._yAxis, eye);
  6460. var ez = -Vector3.Dot(this._zAxis, eye);
  6461. 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);
  6462. };
  6463. /**
  6464. * Create a left-handed orthographic projection matrix
  6465. * @param width defines the viewport width
  6466. * @param height defines the viewport height
  6467. * @param znear defines the near clip plane
  6468. * @param zfar defines the far clip plane
  6469. * @returns a new matrix as a left-handed orthographic projection matrix
  6470. */
  6471. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6472. var matrix = Matrix.Zero();
  6473. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6474. return matrix;
  6475. };
  6476. /**
  6477. * Store a left-handed orthographic projection to a given matrix
  6478. * @param width defines the viewport width
  6479. * @param height defines the viewport height
  6480. * @param znear defines the near clip plane
  6481. * @param zfar defines the far clip plane
  6482. * @param result defines the target matrix
  6483. */
  6484. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6485. var n = znear;
  6486. var f = zfar;
  6487. var a = 2.0 / width;
  6488. var b = 2.0 / height;
  6489. var c = 2.0 / (f - n);
  6490. var d = -(f + n) / (f - n);
  6491. 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);
  6492. };
  6493. /**
  6494. * Create a left-handed orthographic projection matrix
  6495. * @param left defines the viewport left coordinate
  6496. * @param right defines the viewport right coordinate
  6497. * @param bottom defines the viewport bottom coordinate
  6498. * @param top defines the viewport top coordinate
  6499. * @param znear defines the near clip plane
  6500. * @param zfar defines the far clip plane
  6501. * @returns a new matrix as a left-handed orthographic projection matrix
  6502. */
  6503. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6504. var matrix = Matrix.Zero();
  6505. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6506. return matrix;
  6507. };
  6508. /**
  6509. * Stores a left-handed orthographic projection into a given matrix
  6510. * @param left defines the viewport left coordinate
  6511. * @param right defines the viewport right coordinate
  6512. * @param bottom defines the viewport bottom coordinate
  6513. * @param top defines the viewport top coordinate
  6514. * @param znear defines the near clip plane
  6515. * @param zfar defines the far clip plane
  6516. * @param result defines the target matrix
  6517. */
  6518. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6519. var n = znear;
  6520. var f = zfar;
  6521. var a = 2.0 / (right - left);
  6522. var b = 2.0 / (top - bottom);
  6523. var c = 2.0 / (f - n);
  6524. var d = -(f + n) / (f - n);
  6525. var i0 = (left + right) / (left - right);
  6526. var i1 = (top + bottom) / (bottom - top);
  6527. 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);
  6528. };
  6529. /**
  6530. * Creates a right-handed orthographic projection matrix
  6531. * @param left defines the viewport left coordinate
  6532. * @param right defines the viewport right coordinate
  6533. * @param bottom defines the viewport bottom coordinate
  6534. * @param top defines the viewport top coordinate
  6535. * @param znear defines the near clip plane
  6536. * @param zfar defines the far clip plane
  6537. * @returns a new matrix as a right-handed orthographic projection matrix
  6538. */
  6539. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6540. var matrix = Matrix.Zero();
  6541. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6542. return matrix;
  6543. };
  6544. /**
  6545. * Stores a right-handed orthographic projection into a given matrix
  6546. * @param left defines the viewport left coordinate
  6547. * @param right defines the viewport right coordinate
  6548. * @param bottom defines the viewport bottom coordinate
  6549. * @param top defines the viewport top coordinate
  6550. * @param znear defines the near clip plane
  6551. * @param zfar defines the far clip plane
  6552. * @param result defines the target matrix
  6553. */
  6554. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6555. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6556. result.m[10] *= -1.0;
  6557. };
  6558. /**
  6559. * Creates a left-handed perspective projection matrix
  6560. * @param width defines the viewport width
  6561. * @param height defines the viewport height
  6562. * @param znear defines the near clip plane
  6563. * @param zfar defines the far clip plane
  6564. * @returns a new matrix as a left-handed perspective projection matrix
  6565. */
  6566. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6567. var matrix = Matrix.Zero();
  6568. var n = znear;
  6569. var f = zfar;
  6570. var a = 2.0 * n / width;
  6571. var b = 2.0 * n / height;
  6572. var c = (f + n) / (f - n);
  6573. var d = -2.0 * f * n / (f - n);
  6574. 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);
  6575. return matrix;
  6576. };
  6577. /**
  6578. * Creates a left-handed perspective projection matrix
  6579. * @param fov defines the horizontal field of view
  6580. * @param aspect defines the aspect ratio
  6581. * @param znear defines the near clip plane
  6582. * @param zfar defines the far clip plane
  6583. * @returns a new matrix as a left-handed perspective projection matrix
  6584. */
  6585. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6586. var matrix = Matrix.Zero();
  6587. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6588. return matrix;
  6589. };
  6590. /**
  6591. * Stores a left-handed perspective projection into a given matrix
  6592. * @param fov defines the horizontal field of view
  6593. * @param aspect defines the aspect ratio
  6594. * @param znear defines the near clip plane
  6595. * @param zfar defines the far clip plane
  6596. * @param result defines the target matrix
  6597. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6598. */
  6599. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6600. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6601. var n = znear;
  6602. var f = zfar;
  6603. var t = 1.0 / (Math.tan(fov * 0.5));
  6604. var a = isVerticalFovFixed ? (t / aspect) : t;
  6605. var b = isVerticalFovFixed ? t : (t * aspect);
  6606. var c = (f + n) / (f - n);
  6607. var d = -2.0 * f * n / (f - n);
  6608. 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);
  6609. };
  6610. /**
  6611. * Creates a right-handed perspective projection matrix
  6612. * @param fov defines the horizontal field of view
  6613. * @param aspect defines the aspect ratio
  6614. * @param znear defines the near clip plane
  6615. * @param zfar defines the far clip plane
  6616. * @returns a new matrix as a right-handed perspective projection matrix
  6617. */
  6618. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6619. var matrix = Matrix.Zero();
  6620. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6621. return matrix;
  6622. };
  6623. /**
  6624. * Stores a right-handed perspective projection into a given matrix
  6625. * @param fov defines the horizontal field of view
  6626. * @param aspect defines the aspect ratio
  6627. * @param znear defines the near clip plane
  6628. * @param zfar defines the far clip plane
  6629. * @param result defines the target matrix
  6630. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6631. */
  6632. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6633. //alternatively this could be expressed as:
  6634. // m = PerspectiveFovLHToRef
  6635. // m[10] *= -1.0;
  6636. // m[11] *= -1.0;
  6637. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6638. var n = znear;
  6639. var f = zfar;
  6640. var t = 1.0 / (Math.tan(fov * 0.5));
  6641. var a = isVerticalFovFixed ? (t / aspect) : t;
  6642. var b = isVerticalFovFixed ? t : (t * aspect);
  6643. var c = -(f + n) / (f - n);
  6644. var d = -2 * f * n / (f - n);
  6645. 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);
  6646. };
  6647. /**
  6648. * Stores a perspective projection for WebVR info a given matrix
  6649. * @param fov defines the field of view
  6650. * @param znear defines the near clip plane
  6651. * @param zfar defines the far clip plane
  6652. * @param result defines the target matrix
  6653. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6654. */
  6655. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6656. if (rightHanded === void 0) { rightHanded = false; }
  6657. var rightHandedFactor = rightHanded ? -1 : 1;
  6658. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6659. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6660. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6661. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6662. var xScale = 2.0 / (leftTan + rightTan);
  6663. var yScale = 2.0 / (upTan + downTan);
  6664. result.m[0] = xScale;
  6665. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6666. result.m[5] = yScale;
  6667. result.m[6] = result.m[7] = 0.0;
  6668. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6669. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6670. result.m[10] = -zfar / (znear - zfar);
  6671. result.m[11] = 1.0 * rightHandedFactor;
  6672. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6673. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6674. result._markAsUpdated();
  6675. };
  6676. /**
  6677. * Computes a complete transformation matrix
  6678. * @param viewport defines the viewport to use
  6679. * @param world defines the world matrix
  6680. * @param view defines the view matrix
  6681. * @param projection defines the projection matrix
  6682. * @param zmin defines the near clip plane
  6683. * @param zmax defines the far clip plane
  6684. * @returns the transformation matrix
  6685. */
  6686. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6687. var cw = viewport.width;
  6688. var ch = viewport.height;
  6689. var cx = viewport.x;
  6690. var cy = viewport.y;
  6691. 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);
  6692. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6693. };
  6694. /**
  6695. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6696. * @param matrix defines the matrix to use
  6697. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6698. */
  6699. Matrix.GetAsMatrix2x2 = function (matrix) {
  6700. return new Float32Array([
  6701. matrix.m[0], matrix.m[1],
  6702. matrix.m[4], matrix.m[5]
  6703. ]);
  6704. };
  6705. /**
  6706. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6707. * @param matrix defines the matrix to use
  6708. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6709. */
  6710. Matrix.GetAsMatrix3x3 = function (matrix) {
  6711. return new Float32Array([
  6712. matrix.m[0], matrix.m[1], matrix.m[2],
  6713. matrix.m[4], matrix.m[5], matrix.m[6],
  6714. matrix.m[8], matrix.m[9], matrix.m[10]
  6715. ]);
  6716. };
  6717. /**
  6718. * Compute the transpose of a given matrix
  6719. * @param matrix defines the matrix to transpose
  6720. * @returns the new matrix
  6721. */
  6722. Matrix.Transpose = function (matrix) {
  6723. var result = new Matrix();
  6724. Matrix.TransposeToRef(matrix, result);
  6725. return result;
  6726. };
  6727. /**
  6728. * Compute the transpose of a matrix and store it in a target matrix
  6729. * @param matrix defines the matrix to transpose
  6730. * @param result defines the target matrix
  6731. */
  6732. Matrix.TransposeToRef = function (matrix, result) {
  6733. result.m[0] = matrix.m[0];
  6734. result.m[1] = matrix.m[4];
  6735. result.m[2] = matrix.m[8];
  6736. result.m[3] = matrix.m[12];
  6737. result.m[4] = matrix.m[1];
  6738. result.m[5] = matrix.m[5];
  6739. result.m[6] = matrix.m[9];
  6740. result.m[7] = matrix.m[13];
  6741. result.m[8] = matrix.m[2];
  6742. result.m[9] = matrix.m[6];
  6743. result.m[10] = matrix.m[10];
  6744. result.m[11] = matrix.m[14];
  6745. result.m[12] = matrix.m[3];
  6746. result.m[13] = matrix.m[7];
  6747. result.m[14] = matrix.m[11];
  6748. result.m[15] = matrix.m[15];
  6749. };
  6750. /**
  6751. * Computes a reflection matrix from a plane
  6752. * @param plane defines the reflection plane
  6753. * @returns a new matrix
  6754. */
  6755. Matrix.Reflection = function (plane) {
  6756. var matrix = new Matrix();
  6757. Matrix.ReflectionToRef(plane, matrix);
  6758. return matrix;
  6759. };
  6760. /**
  6761. * Computes a reflection matrix from a plane
  6762. * @param plane defines the reflection plane
  6763. * @param result defines the target matrix
  6764. */
  6765. Matrix.ReflectionToRef = function (plane, result) {
  6766. plane.normalize();
  6767. var x = plane.normal.x;
  6768. var y = plane.normal.y;
  6769. var z = plane.normal.z;
  6770. var temp = -2 * x;
  6771. var temp2 = -2 * y;
  6772. var temp3 = -2 * z;
  6773. result.m[0] = (temp * x) + 1;
  6774. result.m[1] = temp2 * x;
  6775. result.m[2] = temp3 * x;
  6776. result.m[3] = 0.0;
  6777. result.m[4] = temp * y;
  6778. result.m[5] = (temp2 * y) + 1;
  6779. result.m[6] = temp3 * y;
  6780. result.m[7] = 0.0;
  6781. result.m[8] = temp * z;
  6782. result.m[9] = temp2 * z;
  6783. result.m[10] = (temp3 * z) + 1;
  6784. result.m[11] = 0.0;
  6785. result.m[12] = temp * plane.d;
  6786. result.m[13] = temp2 * plane.d;
  6787. result.m[14] = temp3 * plane.d;
  6788. result.m[15] = 1.0;
  6789. result._markAsUpdated();
  6790. };
  6791. /**
  6792. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6793. * @param xaxis defines the value of the 1st axis
  6794. * @param yaxis defines the value of the 2nd axis
  6795. * @param zaxis defines the value of the 3rd axis
  6796. * @param result defines the target matrix
  6797. */
  6798. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6799. result.m[0] = xaxis.x;
  6800. result.m[1] = xaxis.y;
  6801. result.m[2] = xaxis.z;
  6802. result.m[3] = 0.0;
  6803. result.m[4] = yaxis.x;
  6804. result.m[5] = yaxis.y;
  6805. result.m[6] = yaxis.z;
  6806. result.m[7] = 0.0;
  6807. result.m[8] = zaxis.x;
  6808. result.m[9] = zaxis.y;
  6809. result.m[10] = zaxis.z;
  6810. result.m[11] = 0.0;
  6811. result.m[12] = 0.0;
  6812. result.m[13] = 0.0;
  6813. result.m[14] = 0.0;
  6814. result.m[15] = 1.0;
  6815. result._markAsUpdated();
  6816. };
  6817. /**
  6818. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6819. * @param quat defines the quaternion to use
  6820. * @param result defines the target matrix
  6821. */
  6822. Matrix.FromQuaternionToRef = function (quat, result) {
  6823. var xx = quat.x * quat.x;
  6824. var yy = quat.y * quat.y;
  6825. var zz = quat.z * quat.z;
  6826. var xy = quat.x * quat.y;
  6827. var zw = quat.z * quat.w;
  6828. var zx = quat.z * quat.x;
  6829. var yw = quat.y * quat.w;
  6830. var yz = quat.y * quat.z;
  6831. var xw = quat.x * quat.w;
  6832. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6833. result.m[1] = 2.0 * (xy + zw);
  6834. result.m[2] = 2.0 * (zx - yw);
  6835. result.m[3] = 0.0;
  6836. result.m[4] = 2.0 * (xy - zw);
  6837. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6838. result.m[6] = 2.0 * (yz + xw);
  6839. result.m[7] = 0.0;
  6840. result.m[8] = 2.0 * (zx + yw);
  6841. result.m[9] = 2.0 * (yz - xw);
  6842. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6843. result.m[11] = 0.0;
  6844. result.m[12] = 0.0;
  6845. result.m[13] = 0.0;
  6846. result.m[14] = 0.0;
  6847. result.m[15] = 1.0;
  6848. result._markAsUpdated();
  6849. };
  6850. Matrix._tempQuaternion = new Quaternion();
  6851. Matrix._xAxis = Vector3.Zero();
  6852. Matrix._yAxis = Vector3.Zero();
  6853. Matrix._zAxis = Vector3.Zero();
  6854. Matrix._updateFlagSeed = 0;
  6855. Matrix._identityReadOnly = Matrix.Identity();
  6856. return Matrix;
  6857. }());
  6858. BABYLON.Matrix = Matrix;
  6859. /**
  6860. * Represens a plane by the equation ax + by + cz + d = 0
  6861. */
  6862. var Plane = /** @class */ (function () {
  6863. /**
  6864. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6865. * @param a a component of the plane
  6866. * @param b b component of the plane
  6867. * @param c c component of the plane
  6868. * @param d d component of the plane
  6869. */
  6870. function Plane(a, b, c, d) {
  6871. this.normal = new Vector3(a, b, c);
  6872. this.d = d;
  6873. }
  6874. /**
  6875. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6876. */
  6877. Plane.prototype.asArray = function () {
  6878. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6879. };
  6880. // Methods
  6881. /**
  6882. * @returns a new plane copied from the current Plane.
  6883. */
  6884. Plane.prototype.clone = function () {
  6885. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6886. };
  6887. /**
  6888. * @returns the string "Plane".
  6889. */
  6890. Plane.prototype.getClassName = function () {
  6891. return "Plane";
  6892. };
  6893. /**
  6894. * @returns the Plane hash code.
  6895. */
  6896. Plane.prototype.getHashCode = function () {
  6897. var hash = this.normal.getHashCode();
  6898. hash = (hash * 397) ^ (this.d || 0);
  6899. return hash;
  6900. };
  6901. /**
  6902. * Normalize the current Plane in place.
  6903. * @returns the updated Plane.
  6904. */
  6905. Plane.prototype.normalize = function () {
  6906. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6907. var magnitude = 0.0;
  6908. if (norm !== 0) {
  6909. magnitude = 1.0 / norm;
  6910. }
  6911. this.normal.x *= magnitude;
  6912. this.normal.y *= magnitude;
  6913. this.normal.z *= magnitude;
  6914. this.d *= magnitude;
  6915. return this;
  6916. };
  6917. /**
  6918. * Applies a transformation the plane and returns the result
  6919. * @param transformation the transformation matrix to be applied to the plane
  6920. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6921. */
  6922. Plane.prototype.transform = function (transformation) {
  6923. var transposedMatrix = Matrix.Transpose(transformation);
  6924. var x = this.normal.x;
  6925. var y = this.normal.y;
  6926. var z = this.normal.z;
  6927. var d = this.d;
  6928. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6929. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6930. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6931. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6932. return new Plane(normalX, normalY, normalZ, finalD);
  6933. };
  6934. /**
  6935. * Calcualtte the dot product between the point and the plane normal
  6936. * @param point point to calculate the dot product with
  6937. * @returns the dot product (float) of the point coordinates and the plane normal.
  6938. */
  6939. Plane.prototype.dotCoordinate = function (point) {
  6940. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6941. };
  6942. /**
  6943. * Updates the current Plane from the plane defined by the three given points.
  6944. * @param point1 one of the points used to contruct the plane
  6945. * @param point2 one of the points used to contruct the plane
  6946. * @param point3 one of the points used to contruct the plane
  6947. * @returns the updated Plane.
  6948. */
  6949. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6950. var x1 = point2.x - point1.x;
  6951. var y1 = point2.y - point1.y;
  6952. var z1 = point2.z - point1.z;
  6953. var x2 = point3.x - point1.x;
  6954. var y2 = point3.y - point1.y;
  6955. var z2 = point3.z - point1.z;
  6956. var yz = (y1 * z2) - (z1 * y2);
  6957. var xz = (z1 * x2) - (x1 * z2);
  6958. var xy = (x1 * y2) - (y1 * x2);
  6959. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6960. var invPyth;
  6961. if (pyth !== 0) {
  6962. invPyth = 1.0 / pyth;
  6963. }
  6964. else {
  6965. invPyth = 0.0;
  6966. }
  6967. this.normal.x = yz * invPyth;
  6968. this.normal.y = xz * invPyth;
  6969. this.normal.z = xy * invPyth;
  6970. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6971. return this;
  6972. };
  6973. /**
  6974. * Checks if the plane is facing a given direction
  6975. * @param direction the direction to check if the plane is facing
  6976. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  6977. * @returns True is the vector "direction" is the same side than the plane normal.
  6978. */
  6979. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6980. var dot = Vector3.Dot(this.normal, direction);
  6981. return (dot <= epsilon);
  6982. };
  6983. /**
  6984. * Calculates the distance to a point
  6985. * @param point point to calculate distance to
  6986. * @returns the signed distance (float) from the given point to the Plane.
  6987. */
  6988. Plane.prototype.signedDistanceTo = function (point) {
  6989. return Vector3.Dot(point, this.normal) + this.d;
  6990. };
  6991. // Statics
  6992. /**
  6993. * Creates a plane from an array
  6994. * @param array the array to create a plane from
  6995. * @returns a new Plane from the given array.
  6996. */
  6997. Plane.FromArray = function (array) {
  6998. return new Plane(array[0], array[1], array[2], array[3]);
  6999. };
  7000. /**
  7001. * Creates a plane from three points
  7002. * @param point1 point used to create the plane
  7003. * @param point2 point used to create the plane
  7004. * @param point3 point used to create the plane
  7005. * @returns a new Plane defined by the three given points.
  7006. */
  7007. Plane.FromPoints = function (point1, point2, point3) {
  7008. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7009. result.copyFromPoints(point1, point2, point3);
  7010. return result;
  7011. };
  7012. /**
  7013. * Creates a plane from an origin point and a normal
  7014. * @param origin origin of the plane to be constructed
  7015. * @param normal normal of the plane to be constructed
  7016. * @returns a new Plane the normal vector to this plane at the given origin point.
  7017. * Note : the vector "normal" is updated because normalized.
  7018. */
  7019. Plane.FromPositionAndNormal = function (origin, normal) {
  7020. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7021. normal.normalize();
  7022. result.normal = normal;
  7023. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7024. return result;
  7025. };
  7026. /**
  7027. * Calculates the distance from a plane and a point
  7028. * @param origin origin of the plane to be constructed
  7029. * @param normal normal of the plane to be constructed
  7030. * @param point point to calculate distance to
  7031. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7032. */
  7033. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7034. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7035. return Vector3.Dot(point, normal) + d;
  7036. };
  7037. return Plane;
  7038. }());
  7039. BABYLON.Plane = Plane;
  7040. /**
  7041. * Class used to represent a viewport on screen
  7042. */
  7043. var Viewport = /** @class */ (function () {
  7044. /**
  7045. * Creates a Viewport object located at (x, y) and sized (width, height)
  7046. * @param x defines viewport left coordinate
  7047. * @param y defines viewport top coordinate
  7048. * @param width defines the viewport width
  7049. * @param height defines the viewport height
  7050. */
  7051. function Viewport(
  7052. /** viewport left coordinate */
  7053. x,
  7054. /** viewport top coordinate */
  7055. y,
  7056. /**viewport width */
  7057. width,
  7058. /** viewport height */
  7059. height) {
  7060. this.x = x;
  7061. this.y = y;
  7062. this.width = width;
  7063. this.height = height;
  7064. }
  7065. /**
  7066. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7067. * @param renderWidthOrEngine defines either an engine or the rendering width
  7068. * @param renderHeight defines the rendering height
  7069. * @returns a new Viewport
  7070. */
  7071. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7072. if (renderWidthOrEngine.getRenderWidth) {
  7073. var engine = renderWidthOrEngine;
  7074. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7075. }
  7076. var renderWidth = renderWidthOrEngine;
  7077. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7078. };
  7079. /**
  7080. * Returns a new Viewport copied from the current one
  7081. * @returns a new Viewport
  7082. */
  7083. Viewport.prototype.clone = function () {
  7084. return new Viewport(this.x, this.y, this.width, this.height);
  7085. };
  7086. return Viewport;
  7087. }());
  7088. BABYLON.Viewport = Viewport;
  7089. /**
  7090. * Reprasents a camera frustum
  7091. */
  7092. var Frustum = /** @class */ (function () {
  7093. function Frustum() {
  7094. }
  7095. /**
  7096. * Gets the planes representing the frustum
  7097. * @param transform matrix to be applied to the returned planes
  7098. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7099. */
  7100. Frustum.GetPlanes = function (transform) {
  7101. var frustumPlanes = [];
  7102. for (var index = 0; index < 6; index++) {
  7103. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7104. }
  7105. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7106. return frustumPlanes;
  7107. };
  7108. /**
  7109. * Gets the near frustum plane transformed by the transform matrix
  7110. * @param transform transformation matrix to be applied to the resulting frustum plane
  7111. * @param frustumPlane the resuling frustum plane
  7112. */
  7113. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7114. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7115. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7116. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7117. frustumPlane.d = transform.m[15] + transform.m[14];
  7118. frustumPlane.normalize();
  7119. };
  7120. /**
  7121. * Gets the far frustum plane transformed by the transform matrix
  7122. * @param transform transformation matrix to be applied to the resulting frustum plane
  7123. * @param frustumPlane the resuling frustum plane
  7124. */
  7125. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7126. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7127. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7128. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7129. frustumPlane.d = transform.m[15] - transform.m[14];
  7130. frustumPlane.normalize();
  7131. };
  7132. /**
  7133. * Gets the left frustum plane transformed by the transform matrix
  7134. * @param transform transformation matrix to be applied to the resulting frustum plane
  7135. * @param frustumPlane the resuling frustum plane
  7136. */
  7137. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7138. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7139. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7140. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7141. frustumPlane.d = transform.m[15] + transform.m[12];
  7142. frustumPlane.normalize();
  7143. };
  7144. /**
  7145. * Gets the right frustum plane transformed by the transform matrix
  7146. * @param transform transformation matrix to be applied to the resulting frustum plane
  7147. * @param frustumPlane the resuling frustum plane
  7148. */
  7149. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7150. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7151. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7152. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7153. frustumPlane.d = transform.m[15] - transform.m[12];
  7154. frustumPlane.normalize();
  7155. };
  7156. /**
  7157. * Gets the top frustum plane transformed by the transform matrix
  7158. * @param transform transformation matrix to be applied to the resulting frustum plane
  7159. * @param frustumPlane the resuling frustum plane
  7160. */
  7161. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7162. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7163. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7164. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7165. frustumPlane.d = transform.m[15] - transform.m[13];
  7166. frustumPlane.normalize();
  7167. };
  7168. /**
  7169. * Gets the bottom frustum plane transformed by the transform matrix
  7170. * @param transform transformation matrix to be applied to the resulting frustum plane
  7171. * @param frustumPlane the resuling frustum plane
  7172. */
  7173. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7174. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7175. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7176. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7177. frustumPlane.d = transform.m[15] + transform.m[13];
  7178. frustumPlane.normalize();
  7179. };
  7180. /**
  7181. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7182. * @param transform transformation matrix to be applied to the resulting frustum planes
  7183. * @param frustumPlanes the resuling frustum planes
  7184. */
  7185. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7186. // Near
  7187. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7188. // Far
  7189. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7190. // Left
  7191. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7192. // Right
  7193. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7194. // Top
  7195. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7196. // Bottom
  7197. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7198. };
  7199. return Frustum;
  7200. }());
  7201. BABYLON.Frustum = Frustum;
  7202. /** Defines supported spaces */
  7203. var Space;
  7204. (function (Space) {
  7205. /** Local (object) space */
  7206. Space[Space["LOCAL"] = 0] = "LOCAL";
  7207. /** World space */
  7208. Space[Space["WORLD"] = 1] = "WORLD";
  7209. /** Bone space */
  7210. Space[Space["BONE"] = 2] = "BONE";
  7211. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7212. /** Defines the 3 main axes */
  7213. var Axis = /** @class */ (function () {
  7214. function Axis() {
  7215. }
  7216. /** X axis */
  7217. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7218. /** Y axis */
  7219. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7220. /** Z axis */
  7221. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7222. return Axis;
  7223. }());
  7224. BABYLON.Axis = Axis;
  7225. ;
  7226. /** Class used to represent a Bezier curve */
  7227. var BezierCurve = /** @class */ (function () {
  7228. function BezierCurve() {
  7229. }
  7230. /**
  7231. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7232. * @param t defines the time
  7233. * @param x1 defines the left coordinate on X axis
  7234. * @param y1 defines the left coordinate on Y axis
  7235. * @param x2 defines the right coordinate on X axis
  7236. * @param y2 defines the right coordinate on Y axis
  7237. * @returns the interpolated value
  7238. */
  7239. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7240. // Extract X (which is equal to time here)
  7241. var f0 = 1 - 3 * x2 + 3 * x1;
  7242. var f1 = 3 * x2 - 6 * x1;
  7243. var f2 = 3 * x1;
  7244. var refinedT = t;
  7245. for (var i = 0; i < 5; i++) {
  7246. var refinedT2 = refinedT * refinedT;
  7247. var refinedT3 = refinedT2 * refinedT;
  7248. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7249. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7250. refinedT -= (x - t) * slope;
  7251. refinedT = Math.min(1, Math.max(0, refinedT));
  7252. }
  7253. // Resolve cubic bezier for the given x
  7254. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7255. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7256. Math.pow(refinedT, 3);
  7257. };
  7258. return BezierCurve;
  7259. }());
  7260. BABYLON.BezierCurve = BezierCurve;
  7261. /**
  7262. * Defines potential orientation for back face culling
  7263. */
  7264. var Orientation;
  7265. (function (Orientation) {
  7266. /**
  7267. * Clockwise
  7268. */
  7269. Orientation[Orientation["CW"] = 0] = "CW";
  7270. /** Counter clockwise */
  7271. Orientation[Orientation["CCW"] = 1] = "CCW";
  7272. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7273. /**
  7274. * Defines angle representation
  7275. */
  7276. var Angle = /** @class */ (function () {
  7277. /**
  7278. * Creates an Angle object of "radians" radians (float).
  7279. */
  7280. function Angle(radians) {
  7281. this._radians = radians;
  7282. if (this._radians < 0.0)
  7283. this._radians += (2.0 * Math.PI);
  7284. }
  7285. /**
  7286. * Get value in degrees
  7287. * @returns the Angle value in degrees (float)
  7288. */
  7289. Angle.prototype.degrees = function () {
  7290. return this._radians * 180.0 / Math.PI;
  7291. };
  7292. /**
  7293. * Get value in radians
  7294. * @returns the Angle value in radians (float)
  7295. */
  7296. Angle.prototype.radians = function () {
  7297. return this._radians;
  7298. };
  7299. /**
  7300. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7301. * @param a defines first vector
  7302. * @param b defines second vector
  7303. * @returns a new Angle
  7304. */
  7305. Angle.BetweenTwoPoints = function (a, b) {
  7306. var delta = b.subtract(a);
  7307. var theta = Math.atan2(delta.y, delta.x);
  7308. return new Angle(theta);
  7309. };
  7310. /**
  7311. * Gets a new Angle object from the given float in radians
  7312. * @param radians defines the angle value in radians
  7313. * @returns a new Angle
  7314. */
  7315. Angle.FromRadians = function (radians) {
  7316. return new Angle(radians);
  7317. };
  7318. /**
  7319. * Gets a new Angle object from the given float in degrees
  7320. * @param degrees defines the angle value in degrees
  7321. * @returns a new Angle
  7322. */
  7323. Angle.FromDegrees = function (degrees) {
  7324. return new Angle(degrees * Math.PI / 180.0);
  7325. };
  7326. return Angle;
  7327. }());
  7328. BABYLON.Angle = Angle;
  7329. /**
  7330. * This represents an arc in a 2d space.
  7331. */
  7332. var Arc2 = /** @class */ (function () {
  7333. /**
  7334. * Creates an Arc object from the three given points : start, middle and end.
  7335. * @param startPoint Defines the start point of the arc
  7336. * @param midPoint Defines the midlle point of the arc
  7337. * @param endPoint Defines the end point of the arc
  7338. */
  7339. function Arc2(
  7340. /** Defines the start point of the arc */
  7341. startPoint,
  7342. /** Defines the mid point of the arc */
  7343. midPoint,
  7344. /** Defines the end point of the arc */
  7345. endPoint) {
  7346. this.startPoint = startPoint;
  7347. this.midPoint = midPoint;
  7348. this.endPoint = endPoint;
  7349. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7350. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7351. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7352. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7353. 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);
  7354. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7355. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7356. var a1 = this.startAngle.degrees();
  7357. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7358. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7359. // angles correction
  7360. if (a2 - a1 > +180.0)
  7361. a2 -= 360.0;
  7362. if (a2 - a1 < -180.0)
  7363. a2 += 360.0;
  7364. if (a3 - a2 > +180.0)
  7365. a3 -= 360.0;
  7366. if (a3 - a2 < -180.0)
  7367. a3 += 360.0;
  7368. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7369. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7370. }
  7371. return Arc2;
  7372. }());
  7373. BABYLON.Arc2 = Arc2;
  7374. /**
  7375. * Represents a 2D path made up of multiple 2D points
  7376. */
  7377. var Path2 = /** @class */ (function () {
  7378. /**
  7379. * Creates a Path2 object from the starting 2D coordinates x and y.
  7380. * @param x the starting points x value
  7381. * @param y the starting points y value
  7382. */
  7383. function Path2(x, y) {
  7384. this._points = new Array();
  7385. this._length = 0.0;
  7386. /**
  7387. * If the path start and end point are the same
  7388. */
  7389. this.closed = false;
  7390. this._points.push(new Vector2(x, y));
  7391. }
  7392. /**
  7393. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7394. * @param x the added points x value
  7395. * @param y the added points y value
  7396. * @returns the updated Path2.
  7397. */
  7398. Path2.prototype.addLineTo = function (x, y) {
  7399. if (this.closed) {
  7400. return this;
  7401. }
  7402. var newPoint = new Vector2(x, y);
  7403. var previousPoint = this._points[this._points.length - 1];
  7404. this._points.push(newPoint);
  7405. this._length += newPoint.subtract(previousPoint).length();
  7406. return this;
  7407. };
  7408. /**
  7409. * 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.
  7410. * @param midX middle point x value
  7411. * @param midY middle point y value
  7412. * @param endX end point x value
  7413. * @param endY end point y value
  7414. * @param numberOfSegments (default: 36)
  7415. * @returns the updated Path2.
  7416. */
  7417. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7418. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7419. if (this.closed) {
  7420. return this;
  7421. }
  7422. var startPoint = this._points[this._points.length - 1];
  7423. var midPoint = new Vector2(midX, midY);
  7424. var endPoint = new Vector2(endX, endY);
  7425. var arc = new Arc2(startPoint, midPoint, endPoint);
  7426. var increment = arc.angle.radians() / numberOfSegments;
  7427. if (arc.orientation === Orientation.CW)
  7428. increment *= -1;
  7429. var currentAngle = arc.startAngle.radians() + increment;
  7430. for (var i = 0; i < numberOfSegments; i++) {
  7431. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7432. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7433. this.addLineTo(x, y);
  7434. currentAngle += increment;
  7435. }
  7436. return this;
  7437. };
  7438. /**
  7439. * Closes the Path2.
  7440. * @returns the Path2.
  7441. */
  7442. Path2.prototype.close = function () {
  7443. this.closed = true;
  7444. return this;
  7445. };
  7446. /**
  7447. * Gets the sum of the distance between each sequential point in the path
  7448. * @returns the Path2 total length (float).
  7449. */
  7450. Path2.prototype.length = function () {
  7451. var result = this._length;
  7452. if (!this.closed) {
  7453. var lastPoint = this._points[this._points.length - 1];
  7454. var firstPoint = this._points[0];
  7455. result += (firstPoint.subtract(lastPoint).length());
  7456. }
  7457. return result;
  7458. };
  7459. /**
  7460. * Gets the points which construct the path
  7461. * @returns the Path2 internal array of points.
  7462. */
  7463. Path2.prototype.getPoints = function () {
  7464. return this._points;
  7465. };
  7466. /**
  7467. * Retreives the point at the distance aways from the starting point
  7468. * @param normalizedLengthPosition the length along the path to retreive the point from
  7469. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7470. */
  7471. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7472. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7473. return Vector2.Zero();
  7474. }
  7475. var lengthPosition = normalizedLengthPosition * this.length();
  7476. var previousOffset = 0;
  7477. for (var i = 0; i < this._points.length; i++) {
  7478. var j = (i + 1) % this._points.length;
  7479. var a = this._points[i];
  7480. var b = this._points[j];
  7481. var bToA = b.subtract(a);
  7482. var nextOffset = (bToA.length() + previousOffset);
  7483. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7484. var dir = bToA.normalize();
  7485. var localOffset = lengthPosition - previousOffset;
  7486. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7487. }
  7488. previousOffset = nextOffset;
  7489. }
  7490. return Vector2.Zero();
  7491. };
  7492. /**
  7493. * Creates a new path starting from an x and y position
  7494. * @param x starting x value
  7495. * @param y starting y value
  7496. * @returns a new Path2 starting at the coordinates (x, y).
  7497. */
  7498. Path2.StartingAt = function (x, y) {
  7499. return new Path2(x, y);
  7500. };
  7501. return Path2;
  7502. }());
  7503. BABYLON.Path2 = Path2;
  7504. /**
  7505. * Represents a 3D path made up of multiple 3D points
  7506. */
  7507. var Path3D = /** @class */ (function () {
  7508. /**
  7509. * new Path3D(path, normal, raw)
  7510. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7511. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7512. * @param path an array of Vector3, the curve axis of the Path3D
  7513. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7514. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7515. */
  7516. function Path3D(
  7517. /**
  7518. * an array of Vector3, the curve axis of the Path3D
  7519. */
  7520. path, firstNormal, raw) {
  7521. if (firstNormal === void 0) { firstNormal = null; }
  7522. this.path = path;
  7523. this._curve = new Array();
  7524. this._distances = new Array();
  7525. this._tangents = new Array();
  7526. this._normals = new Array();
  7527. this._binormals = new Array();
  7528. for (var p = 0; p < path.length; p++) {
  7529. this._curve[p] = path[p].clone(); // hard copy
  7530. }
  7531. this._raw = raw || false;
  7532. this._compute(firstNormal);
  7533. }
  7534. /**
  7535. * Returns the Path3D array of successive Vector3 designing its curve.
  7536. * @returns the Path3D array of successive Vector3 designing its curve.
  7537. */
  7538. Path3D.prototype.getCurve = function () {
  7539. return this._curve;
  7540. };
  7541. /**
  7542. * Returns an array populated with tangent vectors on each Path3D curve point.
  7543. * @returns an array populated with tangent vectors on each Path3D curve point.
  7544. */
  7545. Path3D.prototype.getTangents = function () {
  7546. return this._tangents;
  7547. };
  7548. /**
  7549. * Returns an array populated with normal vectors on each Path3D curve point.
  7550. * @returns an array populated with normal vectors on each Path3D curve point.
  7551. */
  7552. Path3D.prototype.getNormals = function () {
  7553. return this._normals;
  7554. };
  7555. /**
  7556. * Returns an array populated with binormal vectors on each Path3D curve point.
  7557. * @returns an array populated with binormal vectors on each Path3D curve point.
  7558. */
  7559. Path3D.prototype.getBinormals = function () {
  7560. return this._binormals;
  7561. };
  7562. /**
  7563. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7564. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7565. */
  7566. Path3D.prototype.getDistances = function () {
  7567. return this._distances;
  7568. };
  7569. /**
  7570. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7571. * @param path path which all values are copied into the curves points
  7572. * @param firstNormal which should be projected onto the curve
  7573. * @returns the same object updated.
  7574. */
  7575. Path3D.prototype.update = function (path, firstNormal) {
  7576. if (firstNormal === void 0) { firstNormal = null; }
  7577. for (var p = 0; p < path.length; p++) {
  7578. this._curve[p].x = path[p].x;
  7579. this._curve[p].y = path[p].y;
  7580. this._curve[p].z = path[p].z;
  7581. }
  7582. this._compute(firstNormal);
  7583. return this;
  7584. };
  7585. // private function compute() : computes tangents, normals and binormals
  7586. Path3D.prototype._compute = function (firstNormal) {
  7587. var l = this._curve.length;
  7588. // first and last tangents
  7589. this._tangents[0] = this._getFirstNonNullVector(0);
  7590. if (!this._raw) {
  7591. this._tangents[0].normalize();
  7592. }
  7593. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7594. if (!this._raw) {
  7595. this._tangents[l - 1].normalize();
  7596. }
  7597. // normals and binormals at first point : arbitrary vector with _normalVector()
  7598. var tg0 = this._tangents[0];
  7599. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7600. this._normals[0] = pp0;
  7601. if (!this._raw) {
  7602. this._normals[0].normalize();
  7603. }
  7604. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7605. if (!this._raw) {
  7606. this._binormals[0].normalize();
  7607. }
  7608. this._distances[0] = 0.0;
  7609. // normals and binormals : next points
  7610. var prev; // previous vector (segment)
  7611. var cur; // current vector (segment)
  7612. var curTang; // current tangent
  7613. // previous normal
  7614. var prevBinor; // previous binormal
  7615. for (var i = 1; i < l; i++) {
  7616. // tangents
  7617. prev = this._getLastNonNullVector(i);
  7618. if (i < l - 1) {
  7619. cur = this._getFirstNonNullVector(i);
  7620. this._tangents[i] = prev.add(cur);
  7621. this._tangents[i].normalize();
  7622. }
  7623. this._distances[i] = this._distances[i - 1] + prev.length();
  7624. // normals and binormals
  7625. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7626. curTang = this._tangents[i];
  7627. prevBinor = this._binormals[i - 1];
  7628. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7629. if (!this._raw) {
  7630. this._normals[i].normalize();
  7631. }
  7632. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7633. if (!this._raw) {
  7634. this._binormals[i].normalize();
  7635. }
  7636. }
  7637. };
  7638. // private function getFirstNonNullVector(index)
  7639. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7640. Path3D.prototype._getFirstNonNullVector = function (index) {
  7641. var i = 1;
  7642. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7643. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7644. i++;
  7645. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7646. }
  7647. return nNVector;
  7648. };
  7649. // private function getLastNonNullVector(index)
  7650. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7651. Path3D.prototype._getLastNonNullVector = function (index) {
  7652. var i = 1;
  7653. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7654. while (nLVector.length() === 0 && index > i + 1) {
  7655. i++;
  7656. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7657. }
  7658. return nLVector;
  7659. };
  7660. // private function normalVector(v0, vt, va) :
  7661. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7662. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7663. Path3D.prototype._normalVector = function (v0, vt, va) {
  7664. var normal0;
  7665. var tgl = vt.length();
  7666. if (tgl === 0.0) {
  7667. tgl = 1.0;
  7668. }
  7669. if (va === undefined || va === null) {
  7670. var point;
  7671. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7672. point = new Vector3(0.0, -1.0, 0.0);
  7673. }
  7674. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7675. point = new Vector3(1.0, 0.0, 0.0);
  7676. }
  7677. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7678. point = new Vector3(0.0, 0.0, 1.0);
  7679. }
  7680. else {
  7681. point = Vector3.Zero();
  7682. }
  7683. normal0 = Vector3.Cross(vt, point);
  7684. }
  7685. else {
  7686. normal0 = Vector3.Cross(vt, va);
  7687. Vector3.CrossToRef(normal0, vt, normal0);
  7688. }
  7689. normal0.normalize();
  7690. return normal0;
  7691. };
  7692. return Path3D;
  7693. }());
  7694. BABYLON.Path3D = Path3D;
  7695. /**
  7696. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7697. * A Curve3 is designed from a series of successive Vector3.
  7698. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7699. */
  7700. var Curve3 = /** @class */ (function () {
  7701. /**
  7702. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7703. * A Curve3 is designed from a series of successive Vector3.
  7704. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7705. * @param points points which make up the curve
  7706. */
  7707. function Curve3(points) {
  7708. this._length = 0.0;
  7709. this._points = points;
  7710. this._length = this._computeLength(points);
  7711. }
  7712. /**
  7713. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7714. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7715. * @param v1 (Vector3) the control point
  7716. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7717. * @param nbPoints (integer) the wanted number of points in the curve
  7718. * @returns the created Curve3
  7719. */
  7720. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7721. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7722. var bez = new Array();
  7723. var equation = function (t, val0, val1, val2) {
  7724. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7725. return res;
  7726. };
  7727. for (var i = 0; i <= nbPoints; i++) {
  7728. 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)));
  7729. }
  7730. return new Curve3(bez);
  7731. };
  7732. /**
  7733. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7734. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7735. * @param v1 (Vector3) the first control point
  7736. * @param v2 (Vector3) the second control point
  7737. * @param v3 (Vector3) the end point of the Cubic Bezier
  7738. * @param nbPoints (integer) the wanted number of points in the curve
  7739. * @returns the created Curve3
  7740. */
  7741. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7742. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7743. var bez = new Array();
  7744. var equation = function (t, val0, val1, val2, val3) {
  7745. 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;
  7746. return res;
  7747. };
  7748. for (var i = 0; i <= nbPoints; i++) {
  7749. 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)));
  7750. }
  7751. return new Curve3(bez);
  7752. };
  7753. /**
  7754. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7755. * @param p1 (Vector3) the origin point of the Hermite Spline
  7756. * @param t1 (Vector3) the tangent vector at the origin point
  7757. * @param p2 (Vector3) the end point of the Hermite Spline
  7758. * @param t2 (Vector3) the tangent vector at the end point
  7759. * @param nbPoints (integer) the wanted number of points in the curve
  7760. * @returns the created Curve3
  7761. */
  7762. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7763. var hermite = new Array();
  7764. var step = 1.0 / nbPoints;
  7765. for (var i = 0; i <= nbPoints; i++) {
  7766. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7767. }
  7768. return new Curve3(hermite);
  7769. };
  7770. /**
  7771. * Returns a Curve3 object along a CatmullRom Spline curve :
  7772. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7773. * @param nbPoints (integer) the wanted number of points between each curve control points
  7774. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7775. * @returns the created Curve3
  7776. */
  7777. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7778. var catmullRom = new Array();
  7779. var step = 1.0 / nbPoints;
  7780. var amount = 0.0;
  7781. if (closed) {
  7782. var pointsCount = points.length;
  7783. for (var i = 0; i < pointsCount; i++) {
  7784. amount = 0;
  7785. for (var c = 0; c < nbPoints; c++) {
  7786. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7787. amount += step;
  7788. }
  7789. }
  7790. catmullRom.push(catmullRom[0]);
  7791. }
  7792. else {
  7793. var totalPoints = new Array();
  7794. totalPoints.push(points[0].clone());
  7795. Array.prototype.push.apply(totalPoints, points);
  7796. totalPoints.push(points[points.length - 1].clone());
  7797. for (var i = 0; i < totalPoints.length - 3; i++) {
  7798. amount = 0;
  7799. for (var c = 0; c < nbPoints; c++) {
  7800. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7801. amount += step;
  7802. }
  7803. }
  7804. i--;
  7805. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7806. }
  7807. return new Curve3(catmullRom);
  7808. };
  7809. /**
  7810. * @returns the Curve3 stored array of successive Vector3
  7811. */
  7812. Curve3.prototype.getPoints = function () {
  7813. return this._points;
  7814. };
  7815. /**
  7816. * @returns the computed length (float) of the curve.
  7817. */
  7818. Curve3.prototype.length = function () {
  7819. return this._length;
  7820. };
  7821. /**
  7822. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7823. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7824. * curveA and curveB keep unchanged.
  7825. * @param curve the curve to continue from this curve
  7826. * @returns the newly constructed curve
  7827. */
  7828. Curve3.prototype.continue = function (curve) {
  7829. var lastPoint = this._points[this._points.length - 1];
  7830. var continuedPoints = this._points.slice();
  7831. var curvePoints = curve.getPoints();
  7832. for (var i = 1; i < curvePoints.length; i++) {
  7833. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7834. }
  7835. var continuedCurve = new Curve3(continuedPoints);
  7836. return continuedCurve;
  7837. };
  7838. Curve3.prototype._computeLength = function (path) {
  7839. var l = 0;
  7840. for (var i = 1; i < path.length; i++) {
  7841. l += (path[i].subtract(path[i - 1])).length();
  7842. }
  7843. return l;
  7844. };
  7845. return Curve3;
  7846. }());
  7847. BABYLON.Curve3 = Curve3;
  7848. // Vertex formats
  7849. /**
  7850. * Contains position and normal vectors for a vertex
  7851. */
  7852. var PositionNormalVertex = /** @class */ (function () {
  7853. /**
  7854. * Creates a PositionNormalVertex
  7855. * @param position the position of the vertex (defaut: 0,0,0)
  7856. * @param normal the normal of the vertex (defaut: 0,1,0)
  7857. */
  7858. function PositionNormalVertex(
  7859. /** the position of the vertex (defaut: 0,0,0) */
  7860. position,
  7861. /** the normal of the vertex (defaut: 0,1,0) */
  7862. normal) {
  7863. if (position === void 0) { position = Vector3.Zero(); }
  7864. if (normal === void 0) { normal = Vector3.Up(); }
  7865. this.position = position;
  7866. this.normal = normal;
  7867. }
  7868. /**
  7869. * Clones the PositionNormalVertex
  7870. * @returns the cloned PositionNormalVertex
  7871. */
  7872. PositionNormalVertex.prototype.clone = function () {
  7873. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7874. };
  7875. return PositionNormalVertex;
  7876. }());
  7877. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7878. /**
  7879. * Contains position, normal and uv vectors for a vertex
  7880. */
  7881. var PositionNormalTextureVertex = /** @class */ (function () {
  7882. /**
  7883. * Creates a PositionNormalTextureVertex
  7884. * @param position the position of the vertex (defaut: 0,0,0)
  7885. * @param normal the normal of the vertex (defaut: 0,1,0)
  7886. * @param uv the uv of the vertex (default: 0,0)
  7887. */
  7888. function PositionNormalTextureVertex(
  7889. /** the position of the vertex (defaut: 0,0,0) */
  7890. position,
  7891. /** the normal of the vertex (defaut: 0,1,0) */
  7892. normal,
  7893. /** the uv of the vertex (default: 0,0) */
  7894. uv) {
  7895. if (position === void 0) { position = Vector3.Zero(); }
  7896. if (normal === void 0) { normal = Vector3.Up(); }
  7897. if (uv === void 0) { uv = Vector2.Zero(); }
  7898. this.position = position;
  7899. this.normal = normal;
  7900. this.uv = uv;
  7901. }
  7902. /**
  7903. * Clones the PositionNormalTextureVertex
  7904. * @returns the cloned PositionNormalTextureVertex
  7905. */
  7906. PositionNormalTextureVertex.prototype.clone = function () {
  7907. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7908. };
  7909. return PositionNormalTextureVertex;
  7910. }());
  7911. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7912. // Temporary pre-allocated objects for engine internal use
  7913. // usage in any internal function :
  7914. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7915. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7916. /**
  7917. * @hidden
  7918. */
  7919. var Tmp = /** @class */ (function () {
  7920. function Tmp() {
  7921. }
  7922. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7923. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7924. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7925. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7926. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7927. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7928. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7929. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7930. Matrix.Zero(), Matrix.Zero(),
  7931. Matrix.Zero(), Matrix.Zero(),
  7932. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7933. return Tmp;
  7934. }());
  7935. BABYLON.Tmp = Tmp;
  7936. /**
  7937. * @hidden
  7938. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7939. */
  7940. var MathTmp = /** @class */ (function () {
  7941. function MathTmp() {
  7942. }
  7943. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7944. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7945. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7946. return MathTmp;
  7947. }());
  7948. })(BABYLON || (BABYLON = {}));
  7949. //# sourceMappingURL=babylon.math.js.map
  7950. var BABYLON;
  7951. (function (BABYLON) {
  7952. var Scalar = /** @class */ (function () {
  7953. function Scalar() {
  7954. }
  7955. /**
  7956. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7957. */
  7958. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7959. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7960. var num = a - b;
  7961. return -epsilon <= num && num <= epsilon;
  7962. };
  7963. /**
  7964. * Returns a string : the upper case translation of the number i to hexadecimal.
  7965. */
  7966. Scalar.ToHex = function (i) {
  7967. var str = i.toString(16);
  7968. if (i <= 15) {
  7969. return ("0" + str).toUpperCase();
  7970. }
  7971. return str.toUpperCase();
  7972. };
  7973. /**
  7974. * Returns -1 if value is negative and +1 is value is positive.
  7975. * Returns the value itself if it's equal to zero.
  7976. */
  7977. Scalar.Sign = function (value) {
  7978. value = +value; // convert to a number
  7979. if (value === 0 || isNaN(value))
  7980. return value;
  7981. return value > 0 ? 1 : -1;
  7982. };
  7983. /**
  7984. * Returns the value itself if it's between min and max.
  7985. * Returns min if the value is lower than min.
  7986. * Returns max if the value is greater than max.
  7987. */
  7988. Scalar.Clamp = function (value, min, max) {
  7989. if (min === void 0) { min = 0; }
  7990. if (max === void 0) { max = 1; }
  7991. return Math.min(max, Math.max(min, value));
  7992. };
  7993. /**
  7994. * Returns the log2 of value.
  7995. */
  7996. Scalar.Log2 = function (value) {
  7997. return Math.log(value) * Math.LOG2E;
  7998. };
  7999. /**
  8000. * Loops the value, so that it is never larger than length and never smaller than 0.
  8001. *
  8002. * This is similar to the modulo operator but it works with floating point numbers.
  8003. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  8004. * With t = 5 and length = 2.5, the result would be 0.0.
  8005. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  8006. */
  8007. Scalar.Repeat = function (value, length) {
  8008. return value - Math.floor(value / length) * length;
  8009. };
  8010. /**
  8011. * Normalize the value between 0.0 and 1.0 using min and max values
  8012. */
  8013. Scalar.Normalize = function (value, min, max) {
  8014. return (value - min) / (max - min);
  8015. };
  8016. /**
  8017. * Denormalize the value from 0.0 and 1.0 using min and max values
  8018. */
  8019. Scalar.Denormalize = function (normalized, min, max) {
  8020. return (normalized * (max - min) + min);
  8021. };
  8022. /**
  8023. * Calculates the shortest difference between two given angles given in degrees.
  8024. */
  8025. Scalar.DeltaAngle = function (current, target) {
  8026. var num = Scalar.Repeat(target - current, 360.0);
  8027. if (num > 180.0) {
  8028. num -= 360.0;
  8029. }
  8030. return num;
  8031. };
  8032. /**
  8033. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8034. *
  8035. * The returned value will move back and forth between 0 and length
  8036. */
  8037. Scalar.PingPong = function (tx, length) {
  8038. var t = Scalar.Repeat(tx, length * 2.0);
  8039. return length - Math.abs(t - length);
  8040. };
  8041. /**
  8042. * Interpolates between min and max with smoothing at the limits.
  8043. *
  8044. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8045. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8046. */
  8047. Scalar.SmoothStep = function (from, to, tx) {
  8048. var t = Scalar.Clamp(tx);
  8049. t = -2.0 * t * t * t + 3.0 * t * t;
  8050. return to * t + from * (1.0 - t);
  8051. };
  8052. /**
  8053. * Moves a value current towards target.
  8054. *
  8055. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8056. * Negative values of maxDelta pushes the value away from target.
  8057. */
  8058. Scalar.MoveTowards = function (current, target, maxDelta) {
  8059. var result = 0;
  8060. if (Math.abs(target - current) <= maxDelta) {
  8061. result = target;
  8062. }
  8063. else {
  8064. result = current + Scalar.Sign(target - current) * maxDelta;
  8065. }
  8066. return result;
  8067. };
  8068. /**
  8069. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8070. *
  8071. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8072. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8073. */
  8074. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8075. var num = Scalar.DeltaAngle(current, target);
  8076. var result = 0;
  8077. if (-maxDelta < num && num < maxDelta) {
  8078. result = target;
  8079. }
  8080. else {
  8081. target = current + num;
  8082. result = Scalar.MoveTowards(current, target, maxDelta);
  8083. }
  8084. return result;
  8085. };
  8086. /**
  8087. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8088. */
  8089. Scalar.Lerp = function (start, end, amount) {
  8090. return start + ((end - start) * amount);
  8091. };
  8092. /**
  8093. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8094. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8095. */
  8096. Scalar.LerpAngle = function (start, end, amount) {
  8097. var num = Scalar.Repeat(end - start, 360.0);
  8098. if (num > 180.0) {
  8099. num -= 360.0;
  8100. }
  8101. return start + num * Scalar.Clamp(amount);
  8102. };
  8103. /**
  8104. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8105. */
  8106. Scalar.InverseLerp = function (a, b, value) {
  8107. var result = 0;
  8108. if (a != b) {
  8109. result = Scalar.Clamp((value - a) / (b - a));
  8110. }
  8111. else {
  8112. result = 0.0;
  8113. }
  8114. return result;
  8115. };
  8116. /**
  8117. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8118. */
  8119. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8120. var squared = amount * amount;
  8121. var cubed = amount * squared;
  8122. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8123. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8124. var part3 = (cubed - (2.0 * squared)) + amount;
  8125. var part4 = cubed - squared;
  8126. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8127. };
  8128. /**
  8129. * Returns a random float number between and min and max values
  8130. */
  8131. Scalar.RandomRange = function (min, max) {
  8132. if (min === max)
  8133. return min;
  8134. return ((Math.random() * (max - min)) + min);
  8135. };
  8136. /**
  8137. * This function returns percentage of a number in a given range.
  8138. *
  8139. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8140. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8141. */
  8142. Scalar.RangeToPercent = function (number, min, max) {
  8143. return ((number - min) / (max - min));
  8144. };
  8145. /**
  8146. * This function returns number that corresponds to the percentage in a given range.
  8147. *
  8148. * PercentToRange(0.34,0,100) will return 34.
  8149. */
  8150. Scalar.PercentToRange = function (percent, min, max) {
  8151. return ((max - min) * percent + min);
  8152. };
  8153. /**
  8154. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8155. * @param angle The angle to normalize in radian.
  8156. * @return The converted angle.
  8157. */
  8158. Scalar.NormalizeRadians = function (angle) {
  8159. // More precise but slower version kept for reference.
  8160. // angle = angle % Tools.TwoPi;
  8161. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8162. //if (angle > Math.PI) {
  8163. // angle -= Tools.TwoPi;
  8164. //}
  8165. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8166. return angle;
  8167. };
  8168. /**
  8169. * Two pi constants convenient for computation.
  8170. */
  8171. Scalar.TwoPi = Math.PI * 2;
  8172. return Scalar;
  8173. }());
  8174. BABYLON.Scalar = Scalar;
  8175. })(BABYLON || (BABYLON = {}));
  8176. //# sourceMappingURL=babylon.math.scalar.js.map
  8177. //# sourceMappingURL=babylon.mixins.js.map
  8178. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8179. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8180. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8181. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8182. //# sourceMappingURL=babylon.webgl2.js.map
  8183. var BABYLON;
  8184. (function (BABYLON) {
  8185. var __decoratorInitialStore = {};
  8186. var __mergedStore = {};
  8187. var _copySource = function (creationFunction, source, instanciate) {
  8188. var destination = creationFunction();
  8189. // Tags
  8190. if (BABYLON.Tags) {
  8191. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8192. }
  8193. var classStore = getMergedStore(destination);
  8194. // Properties
  8195. for (var property in classStore) {
  8196. var propertyDescriptor = classStore[property];
  8197. var sourceProperty = source[property];
  8198. var propertyType = propertyDescriptor.type;
  8199. if (sourceProperty !== undefined && sourceProperty !== null) {
  8200. switch (propertyType) {
  8201. case 0: // Value
  8202. case 6: // Mesh reference
  8203. case 11: // Camera reference
  8204. destination[property] = sourceProperty;
  8205. break;
  8206. case 1: // Texture
  8207. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8208. break;
  8209. case 2: // Color3
  8210. case 3: // FresnelParameters
  8211. case 4: // Vector2
  8212. case 5: // Vector3
  8213. case 7: // Color Curves
  8214. case 10: // Quaternion
  8215. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8216. break;
  8217. }
  8218. }
  8219. }
  8220. return destination;
  8221. };
  8222. function getDirectStore(target) {
  8223. var classKey = target.getClassName();
  8224. if (!__decoratorInitialStore[classKey]) {
  8225. __decoratorInitialStore[classKey] = {};
  8226. }
  8227. return __decoratorInitialStore[classKey];
  8228. }
  8229. /**
  8230. * Return the list of properties flagged as serializable
  8231. * @param target: host object
  8232. */
  8233. function getMergedStore(target) {
  8234. var classKey = target.getClassName();
  8235. if (__mergedStore[classKey]) {
  8236. return __mergedStore[classKey];
  8237. }
  8238. __mergedStore[classKey] = {};
  8239. var store = __mergedStore[classKey];
  8240. var currentTarget = target;
  8241. var currentKey = classKey;
  8242. while (currentKey) {
  8243. var initialStore = __decoratorInitialStore[currentKey];
  8244. for (var property in initialStore) {
  8245. store[property] = initialStore[property];
  8246. }
  8247. var parent_1 = void 0;
  8248. var done = false;
  8249. do {
  8250. parent_1 = Object.getPrototypeOf(currentTarget);
  8251. if (!parent_1.getClassName) {
  8252. done = true;
  8253. break;
  8254. }
  8255. if (parent_1.getClassName() !== currentKey) {
  8256. break;
  8257. }
  8258. currentTarget = parent_1;
  8259. } while (parent_1);
  8260. if (done) {
  8261. break;
  8262. }
  8263. currentKey = parent_1.getClassName();
  8264. currentTarget = parent_1;
  8265. }
  8266. return store;
  8267. }
  8268. function generateSerializableMember(type, sourceName) {
  8269. return function (target, propertyKey) {
  8270. var classStore = getDirectStore(target);
  8271. if (!classStore[propertyKey]) {
  8272. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8273. }
  8274. };
  8275. }
  8276. function generateExpandMember(setCallback, targetKey) {
  8277. if (targetKey === void 0) { targetKey = null; }
  8278. return function (target, propertyKey) {
  8279. var key = targetKey || ("_" + propertyKey);
  8280. Object.defineProperty(target, propertyKey, {
  8281. get: function () {
  8282. return this[key];
  8283. },
  8284. set: function (value) {
  8285. if (this[key] === value) {
  8286. return;
  8287. }
  8288. this[key] = value;
  8289. target[setCallback].apply(this);
  8290. },
  8291. enumerable: true,
  8292. configurable: true
  8293. });
  8294. };
  8295. }
  8296. function expandToProperty(callback, targetKey) {
  8297. if (targetKey === void 0) { targetKey = null; }
  8298. return generateExpandMember(callback, targetKey);
  8299. }
  8300. BABYLON.expandToProperty = expandToProperty;
  8301. function serialize(sourceName) {
  8302. return generateSerializableMember(0, sourceName); // value member
  8303. }
  8304. BABYLON.serialize = serialize;
  8305. function serializeAsTexture(sourceName) {
  8306. return generateSerializableMember(1, sourceName); // texture member
  8307. }
  8308. BABYLON.serializeAsTexture = serializeAsTexture;
  8309. function serializeAsColor3(sourceName) {
  8310. return generateSerializableMember(2, sourceName); // color3 member
  8311. }
  8312. BABYLON.serializeAsColor3 = serializeAsColor3;
  8313. function serializeAsFresnelParameters(sourceName) {
  8314. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8315. }
  8316. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8317. function serializeAsVector2(sourceName) {
  8318. return generateSerializableMember(4, sourceName); // vector2 member
  8319. }
  8320. BABYLON.serializeAsVector2 = serializeAsVector2;
  8321. function serializeAsVector3(sourceName) {
  8322. return generateSerializableMember(5, sourceName); // vector3 member
  8323. }
  8324. BABYLON.serializeAsVector3 = serializeAsVector3;
  8325. function serializeAsMeshReference(sourceName) {
  8326. return generateSerializableMember(6, sourceName); // mesh reference member
  8327. }
  8328. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8329. function serializeAsColorCurves(sourceName) {
  8330. return generateSerializableMember(7, sourceName); // color curves
  8331. }
  8332. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8333. function serializeAsColor4(sourceName) {
  8334. return generateSerializableMember(8, sourceName); // color 4
  8335. }
  8336. BABYLON.serializeAsColor4 = serializeAsColor4;
  8337. function serializeAsImageProcessingConfiguration(sourceName) {
  8338. return generateSerializableMember(9, sourceName); // image processing
  8339. }
  8340. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8341. function serializeAsQuaternion(sourceName) {
  8342. return generateSerializableMember(10, sourceName); // quaternion member
  8343. }
  8344. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8345. /**
  8346. * Decorator used to define property that can be serialized as reference to a camera
  8347. * @param sourceName defines the name of the property to decorate
  8348. */
  8349. function serializeAsCameraReference(sourceName) {
  8350. return generateSerializableMember(11, sourceName); // camera reference member
  8351. }
  8352. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8353. var SerializationHelper = /** @class */ (function () {
  8354. function SerializationHelper() {
  8355. }
  8356. SerializationHelper.Serialize = function (entity, serializationObject) {
  8357. if (!serializationObject) {
  8358. serializationObject = {};
  8359. }
  8360. // Tags
  8361. if (BABYLON.Tags) {
  8362. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8363. }
  8364. var serializedProperties = getMergedStore(entity);
  8365. // Properties
  8366. for (var property in serializedProperties) {
  8367. var propertyDescriptor = serializedProperties[property];
  8368. var targetPropertyName = propertyDescriptor.sourceName || property;
  8369. var propertyType = propertyDescriptor.type;
  8370. var sourceProperty = entity[property];
  8371. if (sourceProperty !== undefined && sourceProperty !== null) {
  8372. switch (propertyType) {
  8373. case 0: // Value
  8374. serializationObject[targetPropertyName] = sourceProperty;
  8375. break;
  8376. case 1: // Texture
  8377. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8378. break;
  8379. case 2: // Color3
  8380. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8381. break;
  8382. case 3: // FresnelParameters
  8383. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8384. break;
  8385. case 4: // Vector2
  8386. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8387. break;
  8388. case 5: // Vector3
  8389. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8390. break;
  8391. case 6: // Mesh reference
  8392. serializationObject[targetPropertyName] = sourceProperty.id;
  8393. break;
  8394. case 7: // Color Curves
  8395. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8396. break;
  8397. case 8: // Color 4
  8398. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8399. break;
  8400. case 9: // Image Processing
  8401. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8402. break;
  8403. case 10: // Quaternion
  8404. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8405. break;
  8406. case 11: // Camera reference
  8407. serializationObject[targetPropertyName] = sourceProperty.id;
  8408. break;
  8409. }
  8410. }
  8411. }
  8412. return serializationObject;
  8413. };
  8414. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8415. if (rootUrl === void 0) { rootUrl = null; }
  8416. var destination = creationFunction();
  8417. if (!rootUrl) {
  8418. rootUrl = "";
  8419. }
  8420. // Tags
  8421. if (BABYLON.Tags) {
  8422. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8423. }
  8424. var classStore = getMergedStore(destination);
  8425. // Properties
  8426. for (var property in classStore) {
  8427. var propertyDescriptor = classStore[property];
  8428. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8429. var propertyType = propertyDescriptor.type;
  8430. if (sourceProperty !== undefined && sourceProperty !== null) {
  8431. var dest = destination;
  8432. switch (propertyType) {
  8433. case 0: // Value
  8434. dest[property] = sourceProperty;
  8435. break;
  8436. case 1: // Texture
  8437. if (scene) {
  8438. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8439. }
  8440. break;
  8441. case 2: // Color3
  8442. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8443. break;
  8444. case 3: // FresnelParameters
  8445. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8446. break;
  8447. case 4: // Vector2
  8448. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8449. break;
  8450. case 5: // Vector3
  8451. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8452. break;
  8453. case 6: // Mesh reference
  8454. if (scene) {
  8455. dest[property] = scene.getLastMeshByID(sourceProperty);
  8456. }
  8457. break;
  8458. case 7: // Color Curves
  8459. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8460. break;
  8461. case 8: // Color 4
  8462. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8463. break;
  8464. case 9: // Image Processing
  8465. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8466. break;
  8467. case 10: // Quaternion
  8468. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8469. break;
  8470. case 11: // Camera reference
  8471. if (scene) {
  8472. dest[property] = scene.getCameraByID(sourceProperty);
  8473. }
  8474. break;
  8475. }
  8476. }
  8477. }
  8478. return destination;
  8479. };
  8480. SerializationHelper.Clone = function (creationFunction, source) {
  8481. return _copySource(creationFunction, source, false);
  8482. };
  8483. SerializationHelper.Instanciate = function (creationFunction, source) {
  8484. return _copySource(creationFunction, source, true);
  8485. };
  8486. return SerializationHelper;
  8487. }());
  8488. BABYLON.SerializationHelper = SerializationHelper;
  8489. })(BABYLON || (BABYLON = {}));
  8490. //# sourceMappingURL=babylon.decorators.js.map
  8491. var BABYLON;
  8492. (function (BABYLON) {
  8493. /**
  8494. * Wrapper class for promise with external resolve and reject.
  8495. */
  8496. var Deferred = /** @class */ (function () {
  8497. /**
  8498. * Constructor for this deferred object.
  8499. */
  8500. function Deferred() {
  8501. var _this = this;
  8502. this.promise = new Promise(function (resolve, reject) {
  8503. _this._resolve = resolve;
  8504. _this._reject = reject;
  8505. });
  8506. }
  8507. Object.defineProperty(Deferred.prototype, "resolve", {
  8508. /**
  8509. * The resolve method of the promise associated with this deferred object.
  8510. */
  8511. get: function () {
  8512. return this._resolve;
  8513. },
  8514. enumerable: true,
  8515. configurable: true
  8516. });
  8517. Object.defineProperty(Deferred.prototype, "reject", {
  8518. /**
  8519. * The reject method of the promise associated with this deferred object.
  8520. */
  8521. get: function () {
  8522. return this._reject;
  8523. },
  8524. enumerable: true,
  8525. configurable: true
  8526. });
  8527. return Deferred;
  8528. }());
  8529. BABYLON.Deferred = Deferred;
  8530. })(BABYLON || (BABYLON = {}));
  8531. //# sourceMappingURL=babylon.deferred.js.map
  8532. var BABYLON;
  8533. (function (BABYLON) {
  8534. /**
  8535. * A class serves as a medium between the observable and its observers
  8536. */
  8537. var EventState = /** @class */ (function () {
  8538. /**
  8539. * Create a new EventState
  8540. * @param mask defines the mask associated with this state
  8541. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8542. * @param target defines the original target of the state
  8543. * @param currentTarget defines the current target of the state
  8544. */
  8545. function EventState(mask, skipNextObservers, target, currentTarget) {
  8546. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8547. this.initalize(mask, skipNextObservers, target, currentTarget);
  8548. }
  8549. /**
  8550. * Initialize the current event state
  8551. * @param mask defines the mask associated with this state
  8552. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8553. * @param target defines the original target of the state
  8554. * @param currentTarget defines the current target of the state
  8555. * @returns the current event state
  8556. */
  8557. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8558. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8559. this.mask = mask;
  8560. this.skipNextObservers = skipNextObservers;
  8561. this.target = target;
  8562. this.currentTarget = currentTarget;
  8563. return this;
  8564. };
  8565. return EventState;
  8566. }());
  8567. BABYLON.EventState = EventState;
  8568. /**
  8569. * Represent an Observer registered to a given Observable object.
  8570. */
  8571. var Observer = /** @class */ (function () {
  8572. /**
  8573. * Creates a new observer
  8574. * @param callback defines the callback to call when the observer is notified
  8575. * @param mask defines the mask of the observer (used to filter notifications)
  8576. * @param scope defines the current scope used to restore the JS context
  8577. */
  8578. function Observer(
  8579. /**
  8580. * Defines the callback to call when the observer is notified
  8581. */
  8582. callback,
  8583. /**
  8584. * Defines the mask of the observer (used to filter notifications)
  8585. */
  8586. mask,
  8587. /**
  8588. * Defines the current scope used to restore the JS context
  8589. */
  8590. scope) {
  8591. if (scope === void 0) { scope = null; }
  8592. this.callback = callback;
  8593. this.mask = mask;
  8594. this.scope = scope;
  8595. /** @hidden */
  8596. this._willBeUnregistered = false;
  8597. /**
  8598. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8599. */
  8600. this.unregisterOnNextCall = false;
  8601. }
  8602. return Observer;
  8603. }());
  8604. BABYLON.Observer = Observer;
  8605. /**
  8606. * Represent a list of observers registered to multiple Observables object.
  8607. */
  8608. var MultiObserver = /** @class */ (function () {
  8609. function MultiObserver() {
  8610. }
  8611. /**
  8612. * Release associated resources
  8613. */
  8614. MultiObserver.prototype.dispose = function () {
  8615. if (this._observers && this._observables) {
  8616. for (var index = 0; index < this._observers.length; index++) {
  8617. this._observables[index].remove(this._observers[index]);
  8618. }
  8619. }
  8620. this._observers = null;
  8621. this._observables = null;
  8622. };
  8623. /**
  8624. * Raise a callback when one of the observable will notify
  8625. * @param observables defines a list of observables to watch
  8626. * @param callback defines the callback to call on notification
  8627. * @param mask defines the mask used to filter notifications
  8628. * @param scope defines the current scope used to restore the JS context
  8629. * @returns the new MultiObserver
  8630. */
  8631. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8632. if (mask === void 0) { mask = -1; }
  8633. if (scope === void 0) { scope = null; }
  8634. var result = new MultiObserver();
  8635. result._observers = new Array();
  8636. result._observables = observables;
  8637. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8638. var observable = observables_1[_i];
  8639. var observer = observable.add(callback, mask, false, scope);
  8640. if (observer) {
  8641. result._observers.push(observer);
  8642. }
  8643. }
  8644. return result;
  8645. };
  8646. return MultiObserver;
  8647. }());
  8648. BABYLON.MultiObserver = MultiObserver;
  8649. /**
  8650. * The Observable class is a simple implementation of the Observable pattern.
  8651. *
  8652. * 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.
  8653. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8654. * 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).
  8655. * 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.
  8656. */
  8657. var Observable = /** @class */ (function () {
  8658. /**
  8659. * Creates a new observable
  8660. * @param onObserverAdded defines a callback to call when a new observer is added
  8661. */
  8662. function Observable(onObserverAdded) {
  8663. this._observers = new Array();
  8664. this._eventState = new EventState(0);
  8665. if (onObserverAdded) {
  8666. this._onObserverAdded = onObserverAdded;
  8667. }
  8668. }
  8669. /**
  8670. * Create a new Observer with the specified callback
  8671. * @param callback the callback that will be executed for that Observer
  8672. * @param mask the mask used to filter observers
  8673. * @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.
  8674. * @param scope optional scope for the callback to be called from
  8675. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8676. * @returns the new observer created for the callback
  8677. */
  8678. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8679. if (mask === void 0) { mask = -1; }
  8680. if (insertFirst === void 0) { insertFirst = false; }
  8681. if (scope === void 0) { scope = null; }
  8682. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8683. if (!callback) {
  8684. return null;
  8685. }
  8686. var observer = new Observer(callback, mask, scope);
  8687. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8688. if (insertFirst) {
  8689. this._observers.unshift(observer);
  8690. }
  8691. else {
  8692. this._observers.push(observer);
  8693. }
  8694. if (this._onObserverAdded) {
  8695. this._onObserverAdded(observer);
  8696. }
  8697. return observer;
  8698. };
  8699. /**
  8700. * Create a new Observer with the specified callback and unregisters after the next notification
  8701. * @param callback the callback that will be executed for that Observer
  8702. * @returns the new observer created for the callback
  8703. */
  8704. Observable.prototype.addOnce = function (callback) {
  8705. return this.add(callback, undefined, undefined, undefined, true);
  8706. };
  8707. /**
  8708. * Remove an Observer from the Observable object
  8709. * @param observer the instance of the Observer to remove
  8710. * @returns false if it doesn't belong to this Observable
  8711. */
  8712. Observable.prototype.remove = function (observer) {
  8713. if (!observer) {
  8714. return false;
  8715. }
  8716. var index = this._observers.indexOf(observer);
  8717. if (index !== -1) {
  8718. this._deferUnregister(observer);
  8719. return true;
  8720. }
  8721. return false;
  8722. };
  8723. /**
  8724. * Remove a callback from the Observable object
  8725. * @param callback the callback to remove
  8726. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8727. * @returns false if it doesn't belong to this Observable
  8728. */
  8729. Observable.prototype.removeCallback = function (callback, scope) {
  8730. for (var index = 0; index < this._observers.length; index++) {
  8731. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8732. this._deferUnregister(this._observers[index]);
  8733. return true;
  8734. }
  8735. }
  8736. return false;
  8737. };
  8738. Observable.prototype._deferUnregister = function (observer) {
  8739. var _this = this;
  8740. observer.unregisterOnNextCall = false;
  8741. observer._willBeUnregistered = true;
  8742. BABYLON.Tools.SetImmediate(function () {
  8743. _this._remove(observer);
  8744. });
  8745. };
  8746. // This should only be called when not iterating over _observers to avoid callback skipping.
  8747. // Removes an observer from the _observer Array.
  8748. Observable.prototype._remove = function (observer) {
  8749. if (!observer) {
  8750. return false;
  8751. }
  8752. var index = this._observers.indexOf(observer);
  8753. if (index !== -1) {
  8754. this._observers.splice(index, 1);
  8755. return true;
  8756. }
  8757. return false;
  8758. };
  8759. /**
  8760. * Notify all Observers by calling their respective callback with the given data
  8761. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8762. * @param eventData defines the data to send to all observers
  8763. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8764. * @param target defines the original target of the state
  8765. * @param currentTarget defines the current target of the state
  8766. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8767. */
  8768. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8769. if (mask === void 0) { mask = -1; }
  8770. if (!this._observers.length) {
  8771. return true;
  8772. }
  8773. var state = this._eventState;
  8774. state.mask = mask;
  8775. state.target = target;
  8776. state.currentTarget = currentTarget;
  8777. state.skipNextObservers = false;
  8778. state.lastReturnValue = eventData;
  8779. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8780. var obs = _a[_i];
  8781. if (obs._willBeUnregistered) {
  8782. continue;
  8783. }
  8784. if (obs.mask & mask) {
  8785. if (obs.scope) {
  8786. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8787. }
  8788. else {
  8789. state.lastReturnValue = obs.callback(eventData, state);
  8790. }
  8791. if (obs.unregisterOnNextCall) {
  8792. this._deferUnregister(obs);
  8793. }
  8794. }
  8795. if (state.skipNextObservers) {
  8796. return false;
  8797. }
  8798. }
  8799. return true;
  8800. };
  8801. /**
  8802. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8803. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8804. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8805. * and it is crucial that all callbacks will be executed.
  8806. * The order of the callbacks is kept, callbacks are not executed parallel.
  8807. *
  8808. * @param eventData The data to be sent to each callback
  8809. * @param mask is used to filter observers defaults to -1
  8810. * @param target defines the callback target (see EventState)
  8811. * @param currentTarget defines he current object in the bubbling phase
  8812. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8813. */
  8814. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8815. var _this = this;
  8816. if (mask === void 0) { mask = -1; }
  8817. // create an empty promise
  8818. var p = Promise.resolve(eventData);
  8819. // no observers? return this promise.
  8820. if (!this._observers.length) {
  8821. return p;
  8822. }
  8823. var state = this._eventState;
  8824. state.mask = mask;
  8825. state.target = target;
  8826. state.currentTarget = currentTarget;
  8827. state.skipNextObservers = false;
  8828. // execute one callback after another (not using Promise.all, the order is important)
  8829. this._observers.forEach(function (obs) {
  8830. if (state.skipNextObservers) {
  8831. return;
  8832. }
  8833. if (obs._willBeUnregistered) {
  8834. return;
  8835. }
  8836. if (obs.mask & mask) {
  8837. if (obs.scope) {
  8838. p = p.then(function (lastReturnedValue) {
  8839. state.lastReturnValue = lastReturnedValue;
  8840. return obs.callback.apply(obs.scope, [eventData, state]);
  8841. });
  8842. }
  8843. else {
  8844. p = p.then(function (lastReturnedValue) {
  8845. state.lastReturnValue = lastReturnedValue;
  8846. return obs.callback(eventData, state);
  8847. });
  8848. }
  8849. if (obs.unregisterOnNextCall) {
  8850. _this._deferUnregister(obs);
  8851. }
  8852. }
  8853. });
  8854. // return the eventData
  8855. return p.then(function () { return eventData; });
  8856. };
  8857. /**
  8858. * Notify a specific observer
  8859. * @param observer defines the observer to notify
  8860. * @param eventData defines the data to be sent to each callback
  8861. * @param mask is used to filter observers defaults to -1
  8862. */
  8863. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8864. if (mask === void 0) { mask = -1; }
  8865. var state = this._eventState;
  8866. state.mask = mask;
  8867. state.skipNextObservers = false;
  8868. observer.callback(eventData, state);
  8869. };
  8870. /**
  8871. * Gets a boolean indicating if the observable has at least one observer
  8872. * @returns true is the Observable has at least one Observer registered
  8873. */
  8874. Observable.prototype.hasObservers = function () {
  8875. return this._observers.length > 0;
  8876. };
  8877. /**
  8878. * Clear the list of observers
  8879. */
  8880. Observable.prototype.clear = function () {
  8881. this._observers = new Array();
  8882. this._onObserverAdded = null;
  8883. };
  8884. /**
  8885. * Clone the current observable
  8886. * @returns a new observable
  8887. */
  8888. Observable.prototype.clone = function () {
  8889. var result = new Observable();
  8890. result._observers = this._observers.slice(0);
  8891. return result;
  8892. };
  8893. /**
  8894. * Does this observable handles observer registered with a given mask
  8895. * @param mask defines the mask to be tested
  8896. * @return whether or not one observer registered with the given mask is handeled
  8897. **/
  8898. Observable.prototype.hasSpecificMask = function (mask) {
  8899. if (mask === void 0) { mask = -1; }
  8900. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8901. var obs = _a[_i];
  8902. if (obs.mask & mask || obs.mask === mask) {
  8903. return true;
  8904. }
  8905. }
  8906. return false;
  8907. };
  8908. return Observable;
  8909. }());
  8910. BABYLON.Observable = Observable;
  8911. })(BABYLON || (BABYLON = {}));
  8912. //# sourceMappingURL=babylon.observable.js.map
  8913. var BABYLON;
  8914. (function (BABYLON) {
  8915. /**
  8916. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8917. */
  8918. var SmartArray = /** @class */ (function () {
  8919. /**
  8920. * Instantiates a Smart Array.
  8921. * @param capacity defines the default capacity of the array.
  8922. */
  8923. function SmartArray(capacity) {
  8924. /**
  8925. * The active length of the array.
  8926. */
  8927. this.length = 0;
  8928. this.data = new Array(capacity);
  8929. this._id = SmartArray._GlobalId++;
  8930. }
  8931. /**
  8932. * Pushes a value at the end of the active data.
  8933. * @param value defines the object to push in the array.
  8934. */
  8935. SmartArray.prototype.push = function (value) {
  8936. this.data[this.length++] = value;
  8937. if (this.length > this.data.length) {
  8938. this.data.length *= 2;
  8939. }
  8940. };
  8941. /**
  8942. * Iterates over the active data and apply the lambda to them.
  8943. * @param func defines the action to apply on each value.
  8944. */
  8945. SmartArray.prototype.forEach = function (func) {
  8946. for (var index = 0; index < this.length; index++) {
  8947. func(this.data[index]);
  8948. }
  8949. };
  8950. /**
  8951. * Sorts the full sets of data.
  8952. * @param compareFn defines the comparison function to apply.
  8953. */
  8954. SmartArray.prototype.sort = function (compareFn) {
  8955. this.data.sort(compareFn);
  8956. };
  8957. /**
  8958. * Resets the active data to an empty array.
  8959. */
  8960. SmartArray.prototype.reset = function () {
  8961. this.length = 0;
  8962. };
  8963. /**
  8964. * Releases all the data from the array as well as the array.
  8965. */
  8966. SmartArray.prototype.dispose = function () {
  8967. this.reset();
  8968. if (this.data) {
  8969. this.data.length = 0;
  8970. this.data = [];
  8971. }
  8972. };
  8973. /**
  8974. * Concats the active data with a given array.
  8975. * @param array defines the data to concatenate with.
  8976. */
  8977. SmartArray.prototype.concat = function (array) {
  8978. if (array.length === 0) {
  8979. return;
  8980. }
  8981. if (this.length + array.length > this.data.length) {
  8982. this.data.length = (this.length + array.length) * 2;
  8983. }
  8984. for (var index = 0; index < array.length; index++) {
  8985. this.data[this.length++] = (array.data || array)[index];
  8986. }
  8987. };
  8988. /**
  8989. * Returns the position of a value in the active data.
  8990. * @param value defines the value to find the index for
  8991. * @returns the index if found in the active data otherwise -1
  8992. */
  8993. SmartArray.prototype.indexOf = function (value) {
  8994. var position = this.data.indexOf(value);
  8995. if (position >= this.length) {
  8996. return -1;
  8997. }
  8998. return position;
  8999. };
  9000. /**
  9001. * Returns whether an element is part of the active data.
  9002. * @param value defines the value to look for
  9003. * @returns true if found in the active data otherwise false
  9004. */
  9005. SmartArray.prototype.contains = function (value) {
  9006. return this.indexOf(value) !== -1;
  9007. };
  9008. // Statics
  9009. SmartArray._GlobalId = 0;
  9010. return SmartArray;
  9011. }());
  9012. BABYLON.SmartArray = SmartArray;
  9013. /**
  9014. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9015. * The data in this array can only be present once
  9016. */
  9017. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9018. __extends(SmartArrayNoDuplicate, _super);
  9019. function SmartArrayNoDuplicate() {
  9020. var _this = _super !== null && _super.apply(this, arguments) || this;
  9021. _this._duplicateId = 0;
  9022. return _this;
  9023. }
  9024. /**
  9025. * Pushes a value at the end of the active data.
  9026. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9027. * @param value defines the object to push in the array.
  9028. */
  9029. SmartArrayNoDuplicate.prototype.push = function (value) {
  9030. _super.prototype.push.call(this, value);
  9031. if (!value.__smartArrayFlags) {
  9032. value.__smartArrayFlags = {};
  9033. }
  9034. value.__smartArrayFlags[this._id] = this._duplicateId;
  9035. };
  9036. /**
  9037. * Pushes a value at the end of the active data.
  9038. * If the data is already present, it won t be added again
  9039. * @param value defines the object to push in the array.
  9040. * @returns true if added false if it was already present
  9041. */
  9042. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9043. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9044. return false;
  9045. }
  9046. this.push(value);
  9047. return true;
  9048. };
  9049. /**
  9050. * Resets the active data to an empty array.
  9051. */
  9052. SmartArrayNoDuplicate.prototype.reset = function () {
  9053. _super.prototype.reset.call(this);
  9054. this._duplicateId++;
  9055. };
  9056. /**
  9057. * Concats the active data with a given array.
  9058. * This ensures no dupplicate will be present in the result.
  9059. * @param array defines the data to concatenate with.
  9060. */
  9061. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9062. if (array.length === 0) {
  9063. return;
  9064. }
  9065. if (this.length + array.length > this.data.length) {
  9066. this.data.length = (this.length + array.length) * 2;
  9067. }
  9068. for (var index = 0; index < array.length; index++) {
  9069. var item = (array.data || array)[index];
  9070. this.pushNoDuplicate(item);
  9071. }
  9072. };
  9073. return SmartArrayNoDuplicate;
  9074. }(SmartArray));
  9075. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9076. })(BABYLON || (BABYLON = {}));
  9077. //# sourceMappingURL=babylon.smartArray.js.map
  9078. var BABYLON;
  9079. (function (BABYLON) {
  9080. /** Class used to store color4 gradient */
  9081. var ColorGradient = /** @class */ (function () {
  9082. function ColorGradient() {
  9083. }
  9084. /**
  9085. * Will get a color picked randomly between color1 and color2.
  9086. * If color2 is undefined then color1 will be used
  9087. * @param result defines the target Color4 to store the result in
  9088. */
  9089. ColorGradient.prototype.getColorToRef = function (result) {
  9090. if (!this.color2) {
  9091. result.copyFrom(this.color1);
  9092. return;
  9093. }
  9094. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9095. };
  9096. return ColorGradient;
  9097. }());
  9098. BABYLON.ColorGradient = ColorGradient;
  9099. /** Class used to store color 3 gradient */
  9100. var Color3Gradient = /** @class */ (function () {
  9101. function Color3Gradient() {
  9102. }
  9103. return Color3Gradient;
  9104. }());
  9105. BABYLON.Color3Gradient = Color3Gradient;
  9106. /** Class used to store factor gradient */
  9107. var FactorGradient = /** @class */ (function () {
  9108. function FactorGradient() {
  9109. }
  9110. /**
  9111. * Will get a number picked randomly between factor1 and factor2.
  9112. * If factor2 is undefined then factor1 will be used
  9113. * @returns the picked number
  9114. */
  9115. FactorGradient.prototype.getFactor = function () {
  9116. if (this.factor2 === undefined) {
  9117. return this.factor1;
  9118. }
  9119. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9120. };
  9121. return FactorGradient;
  9122. }());
  9123. BABYLON.FactorGradient = FactorGradient;
  9124. /**
  9125. * Application error to support additional information when loading a file
  9126. */
  9127. var LoadFileError = /** @class */ (function (_super) {
  9128. __extends(LoadFileError, _super);
  9129. /**
  9130. * Creates a new LoadFileError
  9131. * @param message defines the message of the error
  9132. * @param request defines the optional XHR request
  9133. */
  9134. function LoadFileError(message, request) {
  9135. var _this = _super.call(this, message) || this;
  9136. _this.request = request;
  9137. _this.name = "LoadFileError";
  9138. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9139. return _this;
  9140. }
  9141. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9142. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9143. // Polyfill for Object.setPrototypeOf if necessary.
  9144. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9145. return LoadFileError;
  9146. }(Error));
  9147. BABYLON.LoadFileError = LoadFileError;
  9148. /**
  9149. * Class used to define a retry strategy when error happens while loading assets
  9150. */
  9151. var RetryStrategy = /** @class */ (function () {
  9152. function RetryStrategy() {
  9153. }
  9154. /**
  9155. * Function used to defines an exponential back off strategy
  9156. * @param maxRetries defines the maximum number of retries (3 by default)
  9157. * @param baseInterval defines the interval between retries
  9158. * @returns the strategy function to use
  9159. */
  9160. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9161. if (maxRetries === void 0) { maxRetries = 3; }
  9162. if (baseInterval === void 0) { baseInterval = 500; }
  9163. return function (url, request, retryIndex) {
  9164. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9165. return -1;
  9166. }
  9167. return Math.pow(2, retryIndex) * baseInterval;
  9168. };
  9169. };
  9170. return RetryStrategy;
  9171. }());
  9172. BABYLON.RetryStrategy = RetryStrategy;
  9173. // Screenshots
  9174. var screenshotCanvas;
  9175. var cloneValue = function (source, destinationObject) {
  9176. if (!source)
  9177. return null;
  9178. if (source instanceof BABYLON.Mesh) {
  9179. return null;
  9180. }
  9181. if (source instanceof BABYLON.SubMesh) {
  9182. return source.clone(destinationObject);
  9183. }
  9184. else if (source.clone) {
  9185. return source.clone();
  9186. }
  9187. return null;
  9188. };
  9189. /**
  9190. * Class containing a set of static utilities functions
  9191. */
  9192. var Tools = /** @class */ (function () {
  9193. function Tools() {
  9194. }
  9195. /**
  9196. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9197. * @param u defines the coordinate on X axis
  9198. * @param v defines the coordinate on Y axis
  9199. * @param width defines the width of the source data
  9200. * @param height defines the height of the source data
  9201. * @param pixels defines the source byte array
  9202. * @param color defines the output color
  9203. */
  9204. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9205. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9206. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9207. var position = (wrappedU + wrappedV * width) * 4;
  9208. color.r = pixels[position] / 255;
  9209. color.g = pixels[position + 1] / 255;
  9210. color.b = pixels[position + 2] / 255;
  9211. color.a = pixels[position + 3] / 255;
  9212. };
  9213. /**
  9214. * Interpolates between a and b via alpha
  9215. * @param a The lower value (returned when alpha = 0)
  9216. * @param b The upper value (returned when alpha = 1)
  9217. * @param alpha The interpolation-factor
  9218. * @return The mixed value
  9219. */
  9220. Tools.Mix = function (a, b, alpha) {
  9221. return a * (1 - alpha) + b * alpha;
  9222. };
  9223. /**
  9224. * Tries to instantiate a new object from a given class name
  9225. * @param className defines the class name to instantiate
  9226. * @returns the new object or null if the system was not able to do the instantiation
  9227. */
  9228. Tools.Instantiate = function (className) {
  9229. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9230. return Tools.RegisteredExternalClasses[className];
  9231. }
  9232. var arr = className.split(".");
  9233. var fn = (window || this);
  9234. for (var i = 0, len = arr.length; i < len; i++) {
  9235. fn = fn[arr[i]];
  9236. }
  9237. if (typeof fn !== "function") {
  9238. return null;
  9239. }
  9240. return fn;
  9241. };
  9242. /**
  9243. * Provides a slice function that will work even on IE
  9244. * @param data defines the array to slice
  9245. * @param start defines the start of the data (optional)
  9246. * @param end defines the end of the data (optional)
  9247. * @returns the new sliced array
  9248. */
  9249. Tools.Slice = function (data, start, end) {
  9250. if (data.slice) {
  9251. return data.slice(start, end);
  9252. }
  9253. return Array.prototype.slice.call(data, start, end);
  9254. };
  9255. /**
  9256. * Polyfill for setImmediate
  9257. * @param action defines the action to execute after the current execution block
  9258. */
  9259. Tools.SetImmediate = function (action) {
  9260. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9261. window.setImmediate(action);
  9262. }
  9263. else {
  9264. setTimeout(action, 1);
  9265. }
  9266. };
  9267. /**
  9268. * Function indicating if a number is an exponent of 2
  9269. * @param value defines the value to test
  9270. * @returns true if the value is an exponent of 2
  9271. */
  9272. Tools.IsExponentOfTwo = function (value) {
  9273. var count = 1;
  9274. do {
  9275. count *= 2;
  9276. } while (count < value);
  9277. return count === value;
  9278. };
  9279. /**
  9280. * Returns the nearest 32-bit single precision float representation of a Number
  9281. * @param value A Number. If the parameter is of a different type, it will get converted
  9282. * to a number or to NaN if it cannot be converted
  9283. * @returns number
  9284. */
  9285. Tools.FloatRound = function (value) {
  9286. if (Math.fround) {
  9287. return Math.fround(value);
  9288. }
  9289. return (Tools._tmpFloatArray[0] = value);
  9290. };
  9291. /**
  9292. * Find the next highest power of two.
  9293. * @param x Number to start search from.
  9294. * @return Next highest power of two.
  9295. */
  9296. Tools.CeilingPOT = function (x) {
  9297. x--;
  9298. x |= x >> 1;
  9299. x |= x >> 2;
  9300. x |= x >> 4;
  9301. x |= x >> 8;
  9302. x |= x >> 16;
  9303. x++;
  9304. return x;
  9305. };
  9306. /**
  9307. * Find the next lowest power of two.
  9308. * @param x Number to start search from.
  9309. * @return Next lowest power of two.
  9310. */
  9311. Tools.FloorPOT = function (x) {
  9312. x = x | (x >> 1);
  9313. x = x | (x >> 2);
  9314. x = x | (x >> 4);
  9315. x = x | (x >> 8);
  9316. x = x | (x >> 16);
  9317. return x - (x >> 1);
  9318. };
  9319. /**
  9320. * Find the nearest power of two.
  9321. * @param x Number to start search from.
  9322. * @return Next nearest power of two.
  9323. */
  9324. Tools.NearestPOT = function (x) {
  9325. var c = Tools.CeilingPOT(x);
  9326. var f = Tools.FloorPOT(x);
  9327. return (c - x) > (x - f) ? f : c;
  9328. };
  9329. /**
  9330. * Get the closest exponent of two
  9331. * @param value defines the value to approximate
  9332. * @param max defines the maximum value to return
  9333. * @param mode defines how to define the closest value
  9334. * @returns closest exponent of two of the given value
  9335. */
  9336. Tools.GetExponentOfTwo = function (value, max, mode) {
  9337. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9338. var pot;
  9339. switch (mode) {
  9340. case BABYLON.Engine.SCALEMODE_FLOOR:
  9341. pot = Tools.FloorPOT(value);
  9342. break;
  9343. case BABYLON.Engine.SCALEMODE_NEAREST:
  9344. pot = Tools.NearestPOT(value);
  9345. break;
  9346. case BABYLON.Engine.SCALEMODE_CEILING:
  9347. default:
  9348. pot = Tools.CeilingPOT(value);
  9349. break;
  9350. }
  9351. return Math.min(pot, max);
  9352. };
  9353. /**
  9354. * Extracts the filename from a path
  9355. * @param path defines the path to use
  9356. * @returns the filename
  9357. */
  9358. Tools.GetFilename = function (path) {
  9359. var index = path.lastIndexOf("/");
  9360. if (index < 0)
  9361. return path;
  9362. return path.substring(index + 1);
  9363. };
  9364. /**
  9365. * Extracts the "folder" part of a path (everything before the filename).
  9366. * @param uri The URI to extract the info from
  9367. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9368. * @returns The "folder" part of the path
  9369. */
  9370. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9371. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9372. var index = uri.lastIndexOf("/");
  9373. if (index < 0) {
  9374. if (returnUnchangedIfNoSlash) {
  9375. return uri;
  9376. }
  9377. return "";
  9378. }
  9379. return uri.substring(0, index + 1);
  9380. };
  9381. /**
  9382. * Extracts text content from a DOM element hierarchy
  9383. * @param element defines the root element
  9384. * @returns a string
  9385. */
  9386. Tools.GetDOMTextContent = function (element) {
  9387. var result = "";
  9388. var child = element.firstChild;
  9389. while (child) {
  9390. if (child.nodeType === 3) {
  9391. result += child.textContent;
  9392. }
  9393. child = child.nextSibling;
  9394. }
  9395. return result;
  9396. };
  9397. /**
  9398. * Convert an angle in radians to degrees
  9399. * @param angle defines the angle to convert
  9400. * @returns the angle in degrees
  9401. */
  9402. Tools.ToDegrees = function (angle) {
  9403. return angle * 180 / Math.PI;
  9404. };
  9405. /**
  9406. * Convert an angle in degrees to radians
  9407. * @param angle defines the angle to convert
  9408. * @returns the angle in radians
  9409. */
  9410. Tools.ToRadians = function (angle) {
  9411. return angle * Math.PI / 180;
  9412. };
  9413. /**
  9414. * Encode a buffer to a base64 string
  9415. * @param buffer defines the buffer to encode
  9416. * @returns the encoded string
  9417. */
  9418. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9419. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9420. var output = "";
  9421. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9422. var i = 0;
  9423. var bytes = new Uint8Array(buffer);
  9424. while (i < bytes.length) {
  9425. chr1 = bytes[i++];
  9426. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9427. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9428. enc1 = chr1 >> 2;
  9429. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9430. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9431. enc4 = chr3 & 63;
  9432. if (isNaN(chr2)) {
  9433. enc3 = enc4 = 64;
  9434. }
  9435. else if (isNaN(chr3)) {
  9436. enc4 = 64;
  9437. }
  9438. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9439. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9440. }
  9441. return "data:image/png;base64," + output;
  9442. };
  9443. /**
  9444. * Extracts minimum and maximum values from a list of indexed positions
  9445. * @param positions defines the positions to use
  9446. * @param indices defines the indices to the positions
  9447. * @param indexStart defines the start index
  9448. * @param indexCount defines the end index
  9449. * @param bias defines bias value to add to the result
  9450. * @return minimum and maximum values
  9451. */
  9452. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9453. if (bias === void 0) { bias = null; }
  9454. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9455. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9456. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9457. var offset = indices[index];
  9458. var x = positions[offset];
  9459. var y = positions[offset + 1];
  9460. var z = positions[offset + 2];
  9461. minimum.minimizeInPlaceFromFloats(x, y, z);
  9462. maximum.maximizeInPlaceFromFloats(x, y, z);
  9463. }
  9464. if (bias) {
  9465. minimum.x -= minimum.x * bias.x + bias.y;
  9466. minimum.y -= minimum.y * bias.x + bias.y;
  9467. minimum.z -= minimum.z * bias.x + bias.y;
  9468. maximum.x += maximum.x * bias.x + bias.y;
  9469. maximum.y += maximum.y * bias.x + bias.y;
  9470. maximum.z += maximum.z * bias.x + bias.y;
  9471. }
  9472. return {
  9473. minimum: minimum,
  9474. maximum: maximum
  9475. };
  9476. };
  9477. /**
  9478. * Extracts minimum and maximum values from a list of positions
  9479. * @param positions defines the positions to use
  9480. * @param start defines the start index in the positions array
  9481. * @param count defines the number of positions to handle
  9482. * @param bias defines bias value to add to the result
  9483. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9484. * @return minimum and maximum values
  9485. */
  9486. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9487. if (bias === void 0) { bias = null; }
  9488. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9489. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9490. if (!stride) {
  9491. stride = 3;
  9492. }
  9493. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  9494. var x = positions[offset];
  9495. var y = positions[offset + 1];
  9496. var z = positions[offset + 2];
  9497. minimum.minimizeInPlaceFromFloats(x, y, z);
  9498. maximum.maximizeInPlaceFromFloats(x, y, z);
  9499. }
  9500. if (bias) {
  9501. minimum.x -= minimum.x * bias.x + bias.y;
  9502. minimum.y -= minimum.y * bias.x + bias.y;
  9503. minimum.z -= minimum.z * bias.x + bias.y;
  9504. maximum.x += maximum.x * bias.x + bias.y;
  9505. maximum.y += maximum.y * bias.x + bias.y;
  9506. maximum.z += maximum.z * bias.x + bias.y;
  9507. }
  9508. return {
  9509. minimum: minimum,
  9510. maximum: maximum
  9511. };
  9512. };
  9513. /**
  9514. * Returns an array if obj is not an array
  9515. * @param obj defines the object to evaluate as an array
  9516. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9517. * @returns either obj directly if obj is an array or a new array containing obj
  9518. */
  9519. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9520. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9521. return null;
  9522. return Array.isArray(obj) ? obj : [obj];
  9523. };
  9524. /**
  9525. * Gets the pointer prefix to use
  9526. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9527. */
  9528. Tools.GetPointerPrefix = function () {
  9529. var eventPrefix = "pointer";
  9530. // Check if pointer events are supported
  9531. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9532. eventPrefix = "mouse";
  9533. }
  9534. return eventPrefix;
  9535. };
  9536. /**
  9537. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9538. * @param func - the function to be called
  9539. * @param requester - the object that will request the next frame. Falls back to window.
  9540. * @returns frame number
  9541. */
  9542. Tools.QueueNewFrame = function (func, requester) {
  9543. if (!Tools.IsWindowObjectExist()) {
  9544. return setTimeout(func, 16);
  9545. }
  9546. if (!requester) {
  9547. requester = window;
  9548. }
  9549. if (requester.requestAnimationFrame) {
  9550. return requester.requestAnimationFrame(func);
  9551. }
  9552. else if (requester.msRequestAnimationFrame) {
  9553. return requester.msRequestAnimationFrame(func);
  9554. }
  9555. else if (requester.webkitRequestAnimationFrame) {
  9556. return requester.webkitRequestAnimationFrame(func);
  9557. }
  9558. else if (requester.mozRequestAnimationFrame) {
  9559. return requester.mozRequestAnimationFrame(func);
  9560. }
  9561. else if (requester.oRequestAnimationFrame) {
  9562. return requester.oRequestAnimationFrame(func);
  9563. }
  9564. else {
  9565. return window.setTimeout(func, 16);
  9566. }
  9567. };
  9568. /**
  9569. * Ask the browser to promote the current element to fullscreen rendering mode
  9570. * @param element defines the DOM element to promote
  9571. */
  9572. Tools.RequestFullscreen = function (element) {
  9573. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9574. if (!requestFunction)
  9575. return;
  9576. requestFunction.call(element);
  9577. };
  9578. /**
  9579. * Asks the browser to exit fullscreen mode
  9580. */
  9581. Tools.ExitFullscreen = function () {
  9582. if (document.exitFullscreen) {
  9583. document.exitFullscreen();
  9584. }
  9585. else if (document.mozCancelFullScreen) {
  9586. document.mozCancelFullScreen();
  9587. }
  9588. else if (document.webkitCancelFullScreen) {
  9589. document.webkitCancelFullScreen();
  9590. }
  9591. else if (document.msCancelFullScreen) {
  9592. document.msCancelFullScreen();
  9593. }
  9594. };
  9595. /**
  9596. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9597. * @param url define the url we are trying
  9598. * @param element define the dom element where to configure the cors policy
  9599. */
  9600. Tools.SetCorsBehavior = function (url, element) {
  9601. if (url && url.indexOf("data:") === 0) {
  9602. return;
  9603. }
  9604. if (Tools.CorsBehavior) {
  9605. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9606. element.crossOrigin = Tools.CorsBehavior;
  9607. }
  9608. else {
  9609. var result = Tools.CorsBehavior(url);
  9610. if (result) {
  9611. element.crossOrigin = result;
  9612. }
  9613. }
  9614. }
  9615. };
  9616. // External files
  9617. /**
  9618. * Removes unwanted characters from an url
  9619. * @param url defines the url to clean
  9620. * @returns the cleaned url
  9621. */
  9622. Tools.CleanUrl = function (url) {
  9623. url = url.replace(/#/mg, "%23");
  9624. return url;
  9625. };
  9626. /**
  9627. * Loads an image as an HTMLImageElement.
  9628. * @param input url string, ArrayBuffer, or Blob to load
  9629. * @param onLoad callback called when the image successfully loads
  9630. * @param onError callback called when the image fails to load
  9631. * @param database database for caching
  9632. * @returns the HTMLImageElement of the loaded image
  9633. */
  9634. Tools.LoadImage = function (input, onLoad, onError, database) {
  9635. var url;
  9636. var usingObjectURL = false;
  9637. if (input instanceof ArrayBuffer) {
  9638. url = URL.createObjectURL(new Blob([input]));
  9639. usingObjectURL = true;
  9640. }
  9641. else if (input instanceof Blob) {
  9642. url = URL.createObjectURL(input);
  9643. usingObjectURL = true;
  9644. }
  9645. else {
  9646. url = Tools.CleanUrl(input);
  9647. url = Tools.PreprocessUrl(input);
  9648. }
  9649. var img = new Image();
  9650. Tools.SetCorsBehavior(url, img);
  9651. var loadHandler = function () {
  9652. if (usingObjectURL && img.src) {
  9653. URL.revokeObjectURL(img.src);
  9654. }
  9655. img.removeEventListener("load", loadHandler);
  9656. img.removeEventListener("error", errorHandler);
  9657. onLoad(img);
  9658. };
  9659. var errorHandler = function (err) {
  9660. if (usingObjectURL && img.src) {
  9661. URL.revokeObjectURL(img.src);
  9662. }
  9663. img.removeEventListener("load", loadHandler);
  9664. img.removeEventListener("error", errorHandler);
  9665. Tools.Error("Error while trying to load image: " + input);
  9666. if (onError) {
  9667. onError("Error while trying to load image: " + input, err);
  9668. }
  9669. };
  9670. img.addEventListener("load", loadHandler);
  9671. img.addEventListener("error", errorHandler);
  9672. var noIndexedDB = function () {
  9673. img.src = url;
  9674. };
  9675. var loadFromIndexedDB = function () {
  9676. if (database) {
  9677. database.loadImageFromDB(url, img);
  9678. }
  9679. };
  9680. //ANY database to do!
  9681. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9682. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9683. }
  9684. else {
  9685. if (url.indexOf("file:") !== -1) {
  9686. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9687. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9688. try {
  9689. var blobURL;
  9690. try {
  9691. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9692. }
  9693. catch (ex) {
  9694. // Chrome doesn't support oneTimeOnly parameter
  9695. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9696. }
  9697. img.src = blobURL;
  9698. usingObjectURL = true;
  9699. }
  9700. catch (e) {
  9701. img.src = "";
  9702. }
  9703. return img;
  9704. }
  9705. }
  9706. noIndexedDB();
  9707. }
  9708. return img;
  9709. };
  9710. /**
  9711. * Loads a file
  9712. * @param url url string, ArrayBuffer, or Blob to load
  9713. * @param onSuccess callback called when the file successfully loads
  9714. * @param onProgress callback called while file is loading (if the server supports this mode)
  9715. * @param database database for caching
  9716. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9717. * @param onError callback called when the file fails to load
  9718. * @returns a file request object
  9719. */
  9720. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9721. url = Tools.CleanUrl(url);
  9722. url = Tools.PreprocessUrl(url);
  9723. // If file and file input are set
  9724. if (url.indexOf("file:") !== -1) {
  9725. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9726. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9727. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9728. }
  9729. }
  9730. var loadUrl = Tools.BaseUrl + url;
  9731. var aborted = false;
  9732. var fileRequest = {
  9733. onCompleteObservable: new BABYLON.Observable(),
  9734. abort: function () { return aborted = true; },
  9735. };
  9736. var requestFile = function () {
  9737. var request = new XMLHttpRequest();
  9738. var retryHandle = null;
  9739. fileRequest.abort = function () {
  9740. aborted = true;
  9741. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9742. request.abort();
  9743. }
  9744. if (retryHandle !== null) {
  9745. clearTimeout(retryHandle);
  9746. retryHandle = null;
  9747. }
  9748. };
  9749. var retryLoop = function (retryIndex) {
  9750. request.open('GET', loadUrl, true);
  9751. if (useArrayBuffer) {
  9752. request.responseType = "arraybuffer";
  9753. }
  9754. if (onProgress) {
  9755. request.addEventListener("progress", onProgress);
  9756. }
  9757. var onLoadEnd = function () {
  9758. request.removeEventListener("loadend", onLoadEnd);
  9759. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9760. fileRequest.onCompleteObservable.clear();
  9761. };
  9762. request.addEventListener("loadend", onLoadEnd);
  9763. var onReadyStateChange = function () {
  9764. if (aborted) {
  9765. return;
  9766. }
  9767. // In case of undefined state in some browsers.
  9768. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9769. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9770. request.removeEventListener("readystatechange", onReadyStateChange);
  9771. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9772. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9773. return;
  9774. }
  9775. var retryStrategy = Tools.DefaultRetryStrategy;
  9776. if (retryStrategy) {
  9777. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9778. if (waitTime !== -1) {
  9779. // Prevent the request from completing for retry.
  9780. request.removeEventListener("loadend", onLoadEnd);
  9781. request = new XMLHttpRequest();
  9782. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9783. return;
  9784. }
  9785. }
  9786. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9787. if (onError) {
  9788. onError(request, e);
  9789. }
  9790. else {
  9791. throw e;
  9792. }
  9793. }
  9794. };
  9795. request.addEventListener("readystatechange", onReadyStateChange);
  9796. request.send();
  9797. };
  9798. retryLoop(0);
  9799. };
  9800. // Caching all files
  9801. if (database && database.enableSceneOffline) {
  9802. var noIndexedDB_1 = function (request) {
  9803. if (request && request.status > 400) {
  9804. if (onError) {
  9805. onError(request);
  9806. }
  9807. }
  9808. else {
  9809. if (!aborted) {
  9810. requestFile();
  9811. }
  9812. }
  9813. };
  9814. var loadFromIndexedDB = function () {
  9815. // TODO: database needs to support aborting and should return a IFileRequest
  9816. if (aborted) {
  9817. return;
  9818. }
  9819. if (database) {
  9820. database.loadFileFromDB(url, function (data) {
  9821. if (!aborted) {
  9822. onSuccess(data);
  9823. }
  9824. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9825. }, onProgress ? function (event) {
  9826. if (!aborted) {
  9827. onProgress(event);
  9828. }
  9829. } : undefined, noIndexedDB_1, useArrayBuffer);
  9830. }
  9831. };
  9832. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9833. }
  9834. else {
  9835. requestFile();
  9836. }
  9837. return fileRequest;
  9838. };
  9839. /**
  9840. * Load a script (identified by an url). When the url returns, the
  9841. * content of this file is added into a new script element, attached to the DOM (body element)
  9842. * @param scriptUrl defines the url of the script to laod
  9843. * @param onSuccess defines the callback called when the script is loaded
  9844. * @param onError defines the callback to call if an error occurs
  9845. */
  9846. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9847. if (!Tools.IsWindowObjectExist()) {
  9848. return;
  9849. }
  9850. var head = document.getElementsByTagName('head')[0];
  9851. var script = document.createElement('script');
  9852. script.type = 'text/javascript';
  9853. script.src = scriptUrl;
  9854. script.onload = function () {
  9855. if (onSuccess) {
  9856. onSuccess();
  9857. }
  9858. };
  9859. script.onerror = function (e) {
  9860. if (onError) {
  9861. onError("Unable to load script '" + scriptUrl + "'", e);
  9862. }
  9863. };
  9864. head.appendChild(script);
  9865. };
  9866. /**
  9867. * Loads a file from a blob
  9868. * @param fileToLoad defines the blob to use
  9869. * @param callback defines the callback to call when data is loaded
  9870. * @param progressCallback defines the callback to call during loading process
  9871. * @returns a file request object
  9872. */
  9873. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9874. var reader = new FileReader();
  9875. var request = {
  9876. onCompleteObservable: new BABYLON.Observable(),
  9877. abort: function () { return reader.abort(); },
  9878. };
  9879. reader.onloadend = function (e) {
  9880. request.onCompleteObservable.notifyObservers(request);
  9881. };
  9882. reader.onload = function (e) {
  9883. //target doesn't have result from ts 1.3
  9884. callback(e.target['result']);
  9885. };
  9886. reader.onprogress = progressCallback;
  9887. reader.readAsDataURL(fileToLoad);
  9888. return request;
  9889. };
  9890. /**
  9891. * Loads a file
  9892. * @param fileToLoad defines the file to load
  9893. * @param callback defines the callback to call when data is loaded
  9894. * @param progressCallBack defines the callback to call during loading process
  9895. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  9896. * @returns a file request object
  9897. */
  9898. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9899. var reader = new FileReader();
  9900. var request = {
  9901. onCompleteObservable: new BABYLON.Observable(),
  9902. abort: function () { return reader.abort(); },
  9903. };
  9904. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9905. reader.onerror = function (e) {
  9906. Tools.Log("Error while reading file: " + fileToLoad.name);
  9907. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9908. };
  9909. reader.onload = function (e) {
  9910. //target doesn't have result from ts 1.3
  9911. callback(e.target['result']);
  9912. };
  9913. if (progressCallBack) {
  9914. reader.onprogress = progressCallBack;
  9915. }
  9916. if (!useArrayBuffer) {
  9917. // Asynchronous read
  9918. reader.readAsText(fileToLoad);
  9919. }
  9920. else {
  9921. reader.readAsArrayBuffer(fileToLoad);
  9922. }
  9923. return request;
  9924. };
  9925. /**
  9926. * Creates a data url from a given string content
  9927. * @param content defines the content to convert
  9928. * @returns the new data url link
  9929. */
  9930. Tools.FileAsURL = function (content) {
  9931. var fileBlob = new Blob([content]);
  9932. var url = window.URL || window.webkitURL;
  9933. var link = url.createObjectURL(fileBlob);
  9934. return link;
  9935. };
  9936. /**
  9937. * Format the given number to a specific decimal format
  9938. * @param value defines the number to format
  9939. * @param decimals defines the number of decimals to use
  9940. * @returns the formatted string
  9941. */
  9942. Tools.Format = function (value, decimals) {
  9943. if (decimals === void 0) { decimals = 2; }
  9944. return value.toFixed(decimals);
  9945. };
  9946. /**
  9947. * Checks if a given vector is inside a specific range
  9948. * @param v defines the vector to test
  9949. * @param min defines the minimum range
  9950. * @param max defines the maximum range
  9951. */
  9952. Tools.CheckExtends = function (v, min, max) {
  9953. if (v.x < min.x)
  9954. min.x = v.x;
  9955. if (v.y < min.y)
  9956. min.y = v.y;
  9957. if (v.z < min.z)
  9958. min.z = v.z;
  9959. if (v.x > max.x)
  9960. max.x = v.x;
  9961. if (v.y > max.y)
  9962. max.y = v.y;
  9963. if (v.z > max.z)
  9964. max.z = v.z;
  9965. };
  9966. /**
  9967. * Tries to copy an object by duplicating every property
  9968. * @param source defines the source object
  9969. * @param destination defines the target object
  9970. * @param doNotCopyList defines a list of properties to avoid
  9971. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  9972. */
  9973. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9974. for (var prop in source) {
  9975. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9976. continue;
  9977. }
  9978. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9979. continue;
  9980. }
  9981. var sourceValue = source[prop];
  9982. var typeOfSourceValue = typeof sourceValue;
  9983. if (typeOfSourceValue === "function") {
  9984. continue;
  9985. }
  9986. try {
  9987. if (typeOfSourceValue === "object") {
  9988. if (sourceValue instanceof Array) {
  9989. destination[prop] = [];
  9990. if (sourceValue.length > 0) {
  9991. if (typeof sourceValue[0] == "object") {
  9992. for (var index = 0; index < sourceValue.length; index++) {
  9993. var clonedValue = cloneValue(sourceValue[index], destination);
  9994. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9995. destination[prop].push(clonedValue);
  9996. }
  9997. }
  9998. }
  9999. else {
  10000. destination[prop] = sourceValue.slice(0);
  10001. }
  10002. }
  10003. }
  10004. else {
  10005. destination[prop] = cloneValue(sourceValue, destination);
  10006. }
  10007. }
  10008. else {
  10009. destination[prop] = sourceValue;
  10010. }
  10011. }
  10012. catch (e) {
  10013. // Just ignore error (it could be because of a read-only property)
  10014. }
  10015. }
  10016. };
  10017. /**
  10018. * Gets a boolean indicating if the given object has no own property
  10019. * @param obj defines the object to test
  10020. * @returns true if object has no own property
  10021. */
  10022. Tools.IsEmpty = function (obj) {
  10023. for (var i in obj) {
  10024. if (obj.hasOwnProperty(i)) {
  10025. return false;
  10026. }
  10027. }
  10028. return true;
  10029. };
  10030. /**
  10031. * Function used to register events at window level
  10032. * @param events defines the events to register
  10033. */
  10034. Tools.RegisterTopRootEvents = function (events) {
  10035. for (var index = 0; index < events.length; index++) {
  10036. var event = events[index];
  10037. window.addEventListener(event.name, event.handler, false);
  10038. try {
  10039. if (window.parent) {
  10040. window.parent.addEventListener(event.name, event.handler, false);
  10041. }
  10042. }
  10043. catch (e) {
  10044. // Silently fails...
  10045. }
  10046. }
  10047. };
  10048. /**
  10049. * Function used to unregister events from window level
  10050. * @param events defines the events to unregister
  10051. */
  10052. Tools.UnregisterTopRootEvents = function (events) {
  10053. for (var index = 0; index < events.length; index++) {
  10054. var event = events[index];
  10055. window.removeEventListener(event.name, event.handler);
  10056. try {
  10057. if (window.parent) {
  10058. window.parent.removeEventListener(event.name, event.handler);
  10059. }
  10060. }
  10061. catch (e) {
  10062. // Silently fails...
  10063. }
  10064. }
  10065. };
  10066. /**
  10067. * Dumps the current bound framebuffer
  10068. * @param width defines the rendering width
  10069. * @param height defines the rendering height
  10070. * @param engine defines the hosting engine
  10071. * @param successCallback defines the callback triggered once the data are available
  10072. * @param mimeType defines the mime type of the result
  10073. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10074. */
  10075. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10076. if (mimeType === void 0) { mimeType = "image/png"; }
  10077. // Read the contents of the framebuffer
  10078. var numberOfChannelsByLine = width * 4;
  10079. var halfHeight = height / 2;
  10080. //Reading datas from WebGL
  10081. var data = engine.readPixels(0, 0, width, height);
  10082. //To flip image on Y axis.
  10083. for (var i = 0; i < halfHeight; i++) {
  10084. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10085. var currentCell = j + i * numberOfChannelsByLine;
  10086. var targetLine = height - i - 1;
  10087. var targetCell = j + targetLine * numberOfChannelsByLine;
  10088. var temp = data[currentCell];
  10089. data[currentCell] = data[targetCell];
  10090. data[targetCell] = temp;
  10091. }
  10092. }
  10093. // Create a 2D canvas to store the result
  10094. if (!screenshotCanvas) {
  10095. screenshotCanvas = document.createElement('canvas');
  10096. }
  10097. screenshotCanvas.width = width;
  10098. screenshotCanvas.height = height;
  10099. var context = screenshotCanvas.getContext('2d');
  10100. if (context) {
  10101. // Copy the pixels to a 2D canvas
  10102. var imageData = context.createImageData(width, height);
  10103. var castData = (imageData.data);
  10104. castData.set(data);
  10105. context.putImageData(imageData, 0, 0);
  10106. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10107. }
  10108. };
  10109. /**
  10110. * Converts the canvas data to blob.
  10111. * This acts as a polyfill for browsers not supporting the to blob function.
  10112. * @param canvas Defines the canvas to extract the data from
  10113. * @param successCallback Defines the callback triggered once the data are available
  10114. * @param mimeType Defines the mime type of the result
  10115. */
  10116. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10117. if (mimeType === void 0) { mimeType = "image/png"; }
  10118. // We need HTMLCanvasElement.toBlob for HD screenshots
  10119. if (!canvas.toBlob) {
  10120. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10121. canvas.toBlob = function (callback, type, quality) {
  10122. var _this = this;
  10123. setTimeout(function () {
  10124. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10125. for (var i = 0; i < len; i++) {
  10126. arr[i] = binStr.charCodeAt(i);
  10127. }
  10128. callback(new Blob([arr]));
  10129. });
  10130. };
  10131. }
  10132. canvas.toBlob(function (blob) {
  10133. successCallback(blob);
  10134. }, mimeType);
  10135. };
  10136. /**
  10137. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10138. * @param successCallback defines the callback triggered once the data are available
  10139. * @param mimeType defines the mime type of the result
  10140. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10141. */
  10142. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10143. if (mimeType === void 0) { mimeType = "image/png"; }
  10144. if (successCallback) {
  10145. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10146. successCallback(base64Image);
  10147. }
  10148. else {
  10149. this.ToBlob(screenshotCanvas, function (blob) {
  10150. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10151. if (("download" in document.createElement("a"))) {
  10152. if (!fileName) {
  10153. var date = new Date();
  10154. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10155. fileName = "screenshot_" + stringDate + ".png";
  10156. }
  10157. Tools.Download(blob, fileName);
  10158. }
  10159. else {
  10160. var url = URL.createObjectURL(blob);
  10161. var newWindow = window.open("");
  10162. if (!newWindow)
  10163. return;
  10164. var img = newWindow.document.createElement("img");
  10165. img.onload = function () {
  10166. // no longer need to read the blob so it's revoked
  10167. URL.revokeObjectURL(url);
  10168. };
  10169. img.src = url;
  10170. newWindow.document.body.appendChild(img);
  10171. }
  10172. }, mimeType);
  10173. }
  10174. };
  10175. /**
  10176. * Downloads a blob in the browser
  10177. * @param blob defines the blob to download
  10178. * @param fileName defines the name of the downloaded file
  10179. */
  10180. Tools.Download = function (blob, fileName) {
  10181. if (navigator && navigator.msSaveBlob) {
  10182. navigator.msSaveBlob(blob, fileName);
  10183. return;
  10184. }
  10185. var url = window.URL.createObjectURL(blob);
  10186. var a = document.createElement("a");
  10187. document.body.appendChild(a);
  10188. a.style.display = "none";
  10189. a.href = url;
  10190. a.download = fileName;
  10191. a.addEventListener("click", function () {
  10192. if (a.parentElement) {
  10193. a.parentElement.removeChild(a);
  10194. }
  10195. });
  10196. a.click();
  10197. window.URL.revokeObjectURL(url);
  10198. };
  10199. /**
  10200. * Captures a screenshot of the current rendering
  10201. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10202. * @param engine defines the rendering engine
  10203. * @param camera defines the source camera
  10204. * @param size This parameter can be set to a single number or to an object with the
  10205. * following (optional) properties: precision, width, height. If a single number is passed,
  10206. * it will be used for both width and height. If an object is passed, the screenshot size
  10207. * will be derived from the parameters. The precision property is a multiplier allowing
  10208. * rendering at a higher or lower resolution
  10209. * @param successCallback defines the callback receives a single parameter which contains the
  10210. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10211. * src parameter of an <img> to display it
  10212. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10213. * Check your browser for supported MIME types
  10214. */
  10215. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10216. if (mimeType === void 0) { mimeType = "image/png"; }
  10217. var width;
  10218. var height;
  10219. // If a precision value is specified
  10220. if (size.precision) {
  10221. width = Math.round(engine.getRenderWidth() * size.precision);
  10222. height = Math.round(width / engine.getAspectRatio(camera));
  10223. }
  10224. else if (size.width && size.height) {
  10225. width = size.width;
  10226. height = size.height;
  10227. }
  10228. //If passing only width, computing height to keep display canvas ratio.
  10229. else if (size.width && !size.height) {
  10230. width = size.width;
  10231. height = Math.round(width / engine.getAspectRatio(camera));
  10232. }
  10233. //If passing only height, computing width to keep display canvas ratio.
  10234. else if (size.height && !size.width) {
  10235. height = size.height;
  10236. width = Math.round(height * engine.getAspectRatio(camera));
  10237. }
  10238. //Assuming here that "size" parameter is a number
  10239. else if (!isNaN(size)) {
  10240. height = size;
  10241. width = size;
  10242. }
  10243. else {
  10244. Tools.Error("Invalid 'size' parameter !");
  10245. return;
  10246. }
  10247. if (!screenshotCanvas) {
  10248. screenshotCanvas = document.createElement('canvas');
  10249. }
  10250. screenshotCanvas.width = width;
  10251. screenshotCanvas.height = height;
  10252. var renderContext = screenshotCanvas.getContext("2d");
  10253. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10254. var newWidth = width;
  10255. var newHeight = newWidth / ratio;
  10256. if (newHeight > height) {
  10257. newHeight = height;
  10258. newWidth = newHeight * ratio;
  10259. }
  10260. var offsetX = Math.max(0, width - newWidth) / 2;
  10261. var offsetY = Math.max(0, height - newHeight) / 2;
  10262. var renderingCanvas = engine.getRenderingCanvas();
  10263. if (renderContext && renderingCanvas) {
  10264. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10265. }
  10266. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10267. };
  10268. /**
  10269. * Generates an image screenshot from the specified camera.
  10270. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10271. * @param engine The engine to use for rendering
  10272. * @param camera The camera to use for rendering
  10273. * @param size This parameter can be set to a single number or to an object with the
  10274. * following (optional) properties: precision, width, height. If a single number is passed,
  10275. * it will be used for both width and height. If an object is passed, the screenshot size
  10276. * will be derived from the parameters. The precision property is a multiplier allowing
  10277. * rendering at a higher or lower resolution
  10278. * @param successCallback The callback receives a single parameter which contains the
  10279. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10280. * src parameter of an <img> to display it
  10281. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10282. * Check your browser for supported MIME types
  10283. * @param samples Texture samples (default: 1)
  10284. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10285. * @param fileName A name for for the downloaded file.
  10286. */
  10287. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10288. if (mimeType === void 0) { mimeType = "image/png"; }
  10289. if (samples === void 0) { samples = 1; }
  10290. if (antialiasing === void 0) { antialiasing = false; }
  10291. var width;
  10292. var height;
  10293. //If a precision value is specified
  10294. if (size.precision) {
  10295. width = Math.round(engine.getRenderWidth() * size.precision);
  10296. height = Math.round(width / engine.getAspectRatio(camera));
  10297. size = { width: width, height: height };
  10298. }
  10299. else if (size.width && size.height) {
  10300. width = size.width;
  10301. height = size.height;
  10302. }
  10303. //If passing only width, computing height to keep display canvas ratio.
  10304. else if (size.width && !size.height) {
  10305. width = size.width;
  10306. height = Math.round(width / engine.getAspectRatio(camera));
  10307. size = { width: width, height: height };
  10308. }
  10309. //If passing only height, computing width to keep display canvas ratio.
  10310. else if (size.height && !size.width) {
  10311. height = size.height;
  10312. width = Math.round(height * engine.getAspectRatio(camera));
  10313. size = { width: width, height: height };
  10314. }
  10315. //Assuming here that "size" parameter is a number
  10316. else if (!isNaN(size)) {
  10317. height = size;
  10318. width = size;
  10319. }
  10320. else {
  10321. Tools.Error("Invalid 'size' parameter !");
  10322. return;
  10323. }
  10324. var scene = camera.getScene();
  10325. var previousCamera = null;
  10326. if (scene.activeCamera !== camera) {
  10327. previousCamera = scene.activeCamera;
  10328. scene.activeCamera = camera;
  10329. }
  10330. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10331. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10332. texture.renderList = null;
  10333. texture.samples = samples;
  10334. if (antialiasing) {
  10335. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10336. }
  10337. texture.onAfterRenderObservable.add(function () {
  10338. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10339. });
  10340. scene.incrementRenderId();
  10341. scene.resetCachedMaterial();
  10342. texture.render(true);
  10343. texture.dispose();
  10344. if (previousCamera) {
  10345. scene.activeCamera = previousCamera;
  10346. }
  10347. camera.getProjectionMatrix(true); // Force cache refresh;
  10348. };
  10349. /**
  10350. * Validates if xhr data is correct
  10351. * @param xhr defines the request to validate
  10352. * @param dataType defines the expected data type
  10353. * @returns true if data is correct
  10354. */
  10355. Tools.ValidateXHRData = function (xhr, dataType) {
  10356. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10357. if (dataType === void 0) { dataType = 7; }
  10358. try {
  10359. if (dataType & 1) {
  10360. if (xhr.responseText && xhr.responseText.length > 0) {
  10361. return true;
  10362. }
  10363. else if (dataType === 1) {
  10364. return false;
  10365. }
  10366. }
  10367. if (dataType & 2) {
  10368. // Check header width and height since there is no "TGA" magic number
  10369. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10370. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10371. return true;
  10372. }
  10373. else if (dataType === 2) {
  10374. return false;
  10375. }
  10376. }
  10377. if (dataType & 4) {
  10378. // Check for the "DDS" magic number
  10379. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10380. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10381. return true;
  10382. }
  10383. else {
  10384. return false;
  10385. }
  10386. }
  10387. }
  10388. catch (e) {
  10389. // Global protection
  10390. }
  10391. return false;
  10392. };
  10393. /**
  10394. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10395. * Be aware Math.random() could cause collisions, but:
  10396. * "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"
  10397. * @returns a pseudo random id
  10398. */
  10399. Tools.RandomId = function () {
  10400. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10401. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10402. return v.toString(16);
  10403. });
  10404. };
  10405. /**
  10406. * Test if the given uri is a base64 string
  10407. * @param uri The uri to test
  10408. * @return True if the uri is a base64 string or false otherwise
  10409. */
  10410. Tools.IsBase64 = function (uri) {
  10411. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10412. };
  10413. /**
  10414. * Decode the given base64 uri.
  10415. * @param uri The uri to decode
  10416. * @return The decoded base64 data.
  10417. */
  10418. Tools.DecodeBase64 = function (uri) {
  10419. var decodedString = atob(uri.split(",")[1]);
  10420. var bufferLength = decodedString.length;
  10421. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10422. for (var i = 0; i < bufferLength; i++) {
  10423. bufferView[i] = decodedString.charCodeAt(i);
  10424. }
  10425. return bufferView.buffer;
  10426. };
  10427. Tools._AddLogEntry = function (entry) {
  10428. Tools._LogCache = entry + Tools._LogCache;
  10429. if (Tools.OnNewCacheEntry) {
  10430. Tools.OnNewCacheEntry(entry);
  10431. }
  10432. };
  10433. Tools._FormatMessage = function (message) {
  10434. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10435. var date = new Date();
  10436. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10437. };
  10438. Tools._LogDisabled = function (message) {
  10439. // nothing to do
  10440. };
  10441. Tools._LogEnabled = function (message) {
  10442. var formattedMessage = Tools._FormatMessage(message);
  10443. console.log("BJS - " + formattedMessage);
  10444. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10445. Tools._AddLogEntry(entry);
  10446. };
  10447. Tools._WarnDisabled = function (message) {
  10448. // nothing to do
  10449. };
  10450. Tools._WarnEnabled = function (message) {
  10451. var formattedMessage = Tools._FormatMessage(message);
  10452. console.warn("BJS - " + formattedMessage);
  10453. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10454. Tools._AddLogEntry(entry);
  10455. };
  10456. Tools._ErrorDisabled = function (message) {
  10457. // nothing to do
  10458. };
  10459. Tools._ErrorEnabled = function (message) {
  10460. Tools.errorsCount++;
  10461. var formattedMessage = Tools._FormatMessage(message);
  10462. console.error("BJS - " + formattedMessage);
  10463. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10464. Tools._AddLogEntry(entry);
  10465. };
  10466. Object.defineProperty(Tools, "LogCache", {
  10467. /**
  10468. * Gets current log cache (list of logs)
  10469. */
  10470. get: function () {
  10471. return Tools._LogCache;
  10472. },
  10473. enumerable: true,
  10474. configurable: true
  10475. });
  10476. /**
  10477. * Clears the log cache
  10478. */
  10479. Tools.ClearLogCache = function () {
  10480. Tools._LogCache = "";
  10481. Tools.errorsCount = 0;
  10482. };
  10483. Object.defineProperty(Tools, "LogLevels", {
  10484. /**
  10485. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10486. */
  10487. set: function (level) {
  10488. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10489. Tools.Log = Tools._LogEnabled;
  10490. }
  10491. else {
  10492. Tools.Log = Tools._LogDisabled;
  10493. }
  10494. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10495. Tools.Warn = Tools._WarnEnabled;
  10496. }
  10497. else {
  10498. Tools.Warn = Tools._WarnDisabled;
  10499. }
  10500. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10501. Tools.Error = Tools._ErrorEnabled;
  10502. }
  10503. else {
  10504. Tools.Error = Tools._ErrorDisabled;
  10505. }
  10506. },
  10507. enumerable: true,
  10508. configurable: true
  10509. });
  10510. /**
  10511. * Checks if the loaded document was accessed via `file:`-Protocol.
  10512. * @returns boolean
  10513. */
  10514. Tools.IsFileURL = function () {
  10515. return location.protocol === "file:";
  10516. };
  10517. /**
  10518. * Checks if the window object exists
  10519. * @returns true if the window object exists
  10520. */
  10521. Tools.IsWindowObjectExist = function () {
  10522. return (typeof window) !== "undefined";
  10523. };
  10524. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10525. /**
  10526. * Sets the current performance log level
  10527. */
  10528. set: function (level) {
  10529. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10530. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10531. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10532. return;
  10533. }
  10534. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10535. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10536. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10537. return;
  10538. }
  10539. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10540. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10541. },
  10542. enumerable: true,
  10543. configurable: true
  10544. });
  10545. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10546. };
  10547. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10548. };
  10549. Tools._StartUserMark = function (counterName, condition) {
  10550. if (condition === void 0) { condition = true; }
  10551. if (!Tools._performance) {
  10552. if (!Tools.IsWindowObjectExist()) {
  10553. return;
  10554. }
  10555. Tools._performance = window.performance;
  10556. }
  10557. if (!condition || !Tools._performance.mark) {
  10558. return;
  10559. }
  10560. Tools._performance.mark(counterName + "-Begin");
  10561. };
  10562. Tools._EndUserMark = function (counterName, condition) {
  10563. if (condition === void 0) { condition = true; }
  10564. if (!condition || !Tools._performance.mark) {
  10565. return;
  10566. }
  10567. Tools._performance.mark(counterName + "-End");
  10568. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10569. };
  10570. Tools._StartPerformanceConsole = function (counterName, condition) {
  10571. if (condition === void 0) { condition = true; }
  10572. if (!condition) {
  10573. return;
  10574. }
  10575. Tools._StartUserMark(counterName, condition);
  10576. if (console.time) {
  10577. console.time(counterName);
  10578. }
  10579. };
  10580. Tools._EndPerformanceConsole = function (counterName, condition) {
  10581. if (condition === void 0) { condition = true; }
  10582. if (!condition) {
  10583. return;
  10584. }
  10585. Tools._EndUserMark(counterName, condition);
  10586. if (console.time) {
  10587. console.timeEnd(counterName);
  10588. }
  10589. };
  10590. Object.defineProperty(Tools, "Now", {
  10591. /**
  10592. * Gets either window.performance.now() if supported or Date.now() else
  10593. */
  10594. get: function () {
  10595. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10596. return window.performance.now();
  10597. }
  10598. return Date.now();
  10599. },
  10600. enumerable: true,
  10601. configurable: true
  10602. });
  10603. /**
  10604. * This method will return the name of the class used to create the instance of the given object.
  10605. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10606. * @param object the object to get the class name from
  10607. * @param isType defines if the object is actually a type
  10608. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10609. */
  10610. Tools.GetClassName = function (object, isType) {
  10611. if (isType === void 0) { isType = false; }
  10612. var name = null;
  10613. if (!isType && object.getClassName) {
  10614. name = object.getClassName();
  10615. }
  10616. else {
  10617. if (object instanceof Object) {
  10618. var classObj = isType ? object : Object.getPrototypeOf(object);
  10619. name = classObj.constructor["__bjsclassName__"];
  10620. }
  10621. if (!name) {
  10622. name = typeof object;
  10623. }
  10624. }
  10625. return name;
  10626. };
  10627. /**
  10628. * Gets the first element of an array satisfying a given predicate
  10629. * @param array defines the array to browse
  10630. * @param predicate defines the predicate to use
  10631. * @returns null if not found or the element
  10632. */
  10633. Tools.First = function (array, predicate) {
  10634. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10635. var el = array_1[_i];
  10636. if (predicate(el)) {
  10637. return el;
  10638. }
  10639. }
  10640. return null;
  10641. };
  10642. /**
  10643. * This method will return the name of the full name of the class, including its owning module (if any).
  10644. * 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).
  10645. * @param object the object to get the class name from
  10646. * @param isType defines if the object is actually a type
  10647. * @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.
  10648. * @ignorenaming
  10649. */
  10650. Tools.getFullClassName = function (object, isType) {
  10651. if (isType === void 0) { isType = false; }
  10652. var className = null;
  10653. var moduleName = null;
  10654. if (!isType && object.getClassName) {
  10655. className = object.getClassName();
  10656. }
  10657. else {
  10658. if (object instanceof Object) {
  10659. var classObj = isType ? object : Object.getPrototypeOf(object);
  10660. className = classObj.constructor["__bjsclassName__"];
  10661. moduleName = classObj.constructor["__bjsmoduleName__"];
  10662. }
  10663. if (!className) {
  10664. className = typeof object;
  10665. }
  10666. }
  10667. if (!className) {
  10668. return null;
  10669. }
  10670. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10671. };
  10672. /**
  10673. * Returns a promise that resolves after the given amount of time.
  10674. * @param delay Number of milliseconds to delay
  10675. * @returns Promise that resolves after the given amount of time
  10676. */
  10677. Tools.DelayAsync = function (delay) {
  10678. return new Promise(function (resolve) {
  10679. setTimeout(function () {
  10680. resolve();
  10681. }, delay);
  10682. });
  10683. };
  10684. /**
  10685. * Gets the current gradient from an array of IValueGradient
  10686. * @param ratio defines the current ratio to get
  10687. * @param gradients defines the array of IValueGradient
  10688. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10689. */
  10690. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10691. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10692. var currentGradient = gradients[gradientIndex];
  10693. var nextGradient = gradients[gradientIndex + 1];
  10694. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10695. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10696. updateFunc(currentGradient, nextGradient, scale);
  10697. return;
  10698. }
  10699. }
  10700. // Use last index if over
  10701. var lastIndex = gradients.length - 1;
  10702. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10703. };
  10704. /**
  10705. * Gets or sets the base URL to use to load assets
  10706. */
  10707. Tools.BaseUrl = "";
  10708. /**
  10709. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10710. */
  10711. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10712. /**
  10713. * Default behaviour for cors in the application.
  10714. * It can be a string if the expected behavior is identical in the entire app.
  10715. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10716. */
  10717. Tools.CorsBehavior = "anonymous";
  10718. /**
  10719. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10720. * @ignorenaming
  10721. */
  10722. Tools.UseFallbackTexture = true;
  10723. /**
  10724. * Use this object to register external classes like custom textures or material
  10725. * to allow the laoders to instantiate them
  10726. */
  10727. Tools.RegisteredExternalClasses = {};
  10728. /**
  10729. * Texture content used if a texture cannot loaded
  10730. * @ignorenaming
  10731. */
  10732. 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";
  10733. Tools._tmpFloatArray = new Float32Array(1);
  10734. /**
  10735. * Gets or sets a function used to pre-process url before using them to load assets
  10736. */
  10737. Tools.PreprocessUrl = function (url) {
  10738. return url;
  10739. };
  10740. // Logs
  10741. /**
  10742. * No log
  10743. */
  10744. Tools.NoneLogLevel = 0;
  10745. /**
  10746. * Only message logs
  10747. */
  10748. Tools.MessageLogLevel = 1;
  10749. /**
  10750. * Only warning logs
  10751. */
  10752. Tools.WarningLogLevel = 2;
  10753. /**
  10754. * Only error logs
  10755. */
  10756. Tools.ErrorLogLevel = 4;
  10757. /**
  10758. * All logs
  10759. */
  10760. Tools.AllLogLevel = 7;
  10761. Tools._LogCache = "";
  10762. /**
  10763. * Gets a value indicating the number of loading errors
  10764. * @ignorenaming
  10765. */
  10766. Tools.errorsCount = 0;
  10767. /**
  10768. * Log a message to the console
  10769. */
  10770. Tools.Log = Tools._LogEnabled;
  10771. /**
  10772. * Write a warning message to the console
  10773. */
  10774. Tools.Warn = Tools._WarnEnabled;
  10775. /**
  10776. * Write an error message to the console
  10777. */
  10778. Tools.Error = Tools._ErrorEnabled;
  10779. // Performances
  10780. /**
  10781. * No performance log
  10782. */
  10783. Tools.PerformanceNoneLogLevel = 0;
  10784. /**
  10785. * Use user marks to log performance
  10786. */
  10787. Tools.PerformanceUserMarkLogLevel = 1;
  10788. /**
  10789. * Log performance to the console
  10790. */
  10791. Tools.PerformanceConsoleLogLevel = 2;
  10792. /**
  10793. * Starts a performance counter
  10794. */
  10795. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10796. /**
  10797. * Ends a specific performance coutner
  10798. */
  10799. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10800. return Tools;
  10801. }());
  10802. BABYLON.Tools = Tools;
  10803. /**
  10804. * This class is used to track a performance counter which is number based.
  10805. * The user has access to many properties which give statistics of different nature.
  10806. *
  10807. * The implementer can track two kinds of Performance Counter: time and count.
  10808. * 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.
  10809. * 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.
  10810. */
  10811. var PerfCounter = /** @class */ (function () {
  10812. /**
  10813. * Creates a new counter
  10814. */
  10815. function PerfCounter() {
  10816. this._startMonitoringTime = 0;
  10817. this._min = 0;
  10818. this._max = 0;
  10819. this._average = 0;
  10820. this._lastSecAverage = 0;
  10821. this._current = 0;
  10822. this._totalValueCount = 0;
  10823. this._totalAccumulated = 0;
  10824. this._lastSecAccumulated = 0;
  10825. this._lastSecTime = 0;
  10826. this._lastSecValueCount = 0;
  10827. }
  10828. Object.defineProperty(PerfCounter.prototype, "min", {
  10829. /**
  10830. * Returns the smallest value ever
  10831. */
  10832. get: function () {
  10833. return this._min;
  10834. },
  10835. enumerable: true,
  10836. configurable: true
  10837. });
  10838. Object.defineProperty(PerfCounter.prototype, "max", {
  10839. /**
  10840. * Returns the biggest value ever
  10841. */
  10842. get: function () {
  10843. return this._max;
  10844. },
  10845. enumerable: true,
  10846. configurable: true
  10847. });
  10848. Object.defineProperty(PerfCounter.prototype, "average", {
  10849. /**
  10850. * Returns the average value since the performance counter is running
  10851. */
  10852. get: function () {
  10853. return this._average;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10859. /**
  10860. * Returns the average value of the last second the counter was monitored
  10861. */
  10862. get: function () {
  10863. return this._lastSecAverage;
  10864. },
  10865. enumerable: true,
  10866. configurable: true
  10867. });
  10868. Object.defineProperty(PerfCounter.prototype, "current", {
  10869. /**
  10870. * Returns the current value
  10871. */
  10872. get: function () {
  10873. return this._current;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(PerfCounter.prototype, "total", {
  10879. /**
  10880. * Gets the accumulated total
  10881. */
  10882. get: function () {
  10883. return this._totalAccumulated;
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. Object.defineProperty(PerfCounter.prototype, "count", {
  10889. /**
  10890. * Gets the total value count
  10891. */
  10892. get: function () {
  10893. return this._totalValueCount;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. /**
  10899. * Call this method to start monitoring a new frame.
  10900. * 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.
  10901. */
  10902. PerfCounter.prototype.fetchNewFrame = function () {
  10903. this._totalValueCount++;
  10904. this._current = 0;
  10905. this._lastSecValueCount++;
  10906. };
  10907. /**
  10908. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10909. * @param newCount the count value to add to the monitored count
  10910. * @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.
  10911. */
  10912. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10913. if (!PerfCounter.Enabled) {
  10914. return;
  10915. }
  10916. this._current += newCount;
  10917. if (fetchResult) {
  10918. this._fetchResult();
  10919. }
  10920. };
  10921. /**
  10922. * Start monitoring this performance counter
  10923. */
  10924. PerfCounter.prototype.beginMonitoring = function () {
  10925. if (!PerfCounter.Enabled) {
  10926. return;
  10927. }
  10928. this._startMonitoringTime = Tools.Now;
  10929. };
  10930. /**
  10931. * Compute the time lapsed since the previous beginMonitoring() call.
  10932. * @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
  10933. */
  10934. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10935. if (newFrame === void 0) { newFrame = true; }
  10936. if (!PerfCounter.Enabled) {
  10937. return;
  10938. }
  10939. if (newFrame) {
  10940. this.fetchNewFrame();
  10941. }
  10942. var currentTime = Tools.Now;
  10943. this._current = currentTime - this._startMonitoringTime;
  10944. if (newFrame) {
  10945. this._fetchResult();
  10946. }
  10947. };
  10948. PerfCounter.prototype._fetchResult = function () {
  10949. this._totalAccumulated += this._current;
  10950. this._lastSecAccumulated += this._current;
  10951. // Min/Max update
  10952. this._min = Math.min(this._min, this._current);
  10953. this._max = Math.max(this._max, this._current);
  10954. this._average = this._totalAccumulated / this._totalValueCount;
  10955. // Reset last sec?
  10956. var now = Tools.Now;
  10957. if ((now - this._lastSecTime) > 1000) {
  10958. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10959. this._lastSecTime = now;
  10960. this._lastSecAccumulated = 0;
  10961. this._lastSecValueCount = 0;
  10962. }
  10963. };
  10964. /**
  10965. * Gets or sets a global boolean to turn on and off all the counters
  10966. */
  10967. PerfCounter.Enabled = true;
  10968. return PerfCounter;
  10969. }());
  10970. BABYLON.PerfCounter = PerfCounter;
  10971. /**
  10972. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10973. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10974. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10975. * @param name The name of the class, case should be preserved
  10976. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10977. */
  10978. function className(name, module) {
  10979. return function (target) {
  10980. target["__bjsclassName__"] = name;
  10981. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10982. };
  10983. }
  10984. BABYLON.className = className;
  10985. /**
  10986. * An implementation of a loop for asynchronous functions.
  10987. */
  10988. var AsyncLoop = /** @class */ (function () {
  10989. /**
  10990. * Constructor.
  10991. * @param iterations the number of iterations.
  10992. * @param func the function to run each iteration
  10993. * @param successCallback the callback that will be called upon succesful execution
  10994. * @param offset starting offset.
  10995. */
  10996. function AsyncLoop(
  10997. /**
  10998. * Defines the number of iterations for the loop
  10999. */
  11000. iterations, func, successCallback, offset) {
  11001. if (offset === void 0) { offset = 0; }
  11002. this.iterations = iterations;
  11003. this.index = offset - 1;
  11004. this._done = false;
  11005. this._fn = func;
  11006. this._successCallback = successCallback;
  11007. }
  11008. /**
  11009. * Execute the next iteration. Must be called after the last iteration was finished.
  11010. */
  11011. AsyncLoop.prototype.executeNext = function () {
  11012. if (!this._done) {
  11013. if (this.index + 1 < this.iterations) {
  11014. ++this.index;
  11015. this._fn(this);
  11016. }
  11017. else {
  11018. this.breakLoop();
  11019. }
  11020. }
  11021. };
  11022. /**
  11023. * Break the loop and run the success callback.
  11024. */
  11025. AsyncLoop.prototype.breakLoop = function () {
  11026. this._done = true;
  11027. this._successCallback();
  11028. };
  11029. /**
  11030. * Create and run an async loop.
  11031. * @param iterations the number of iterations.
  11032. * @param fn the function to run each iteration
  11033. * @param successCallback the callback that will be called upon succesful execution
  11034. * @param offset starting offset.
  11035. * @returns the created async loop object
  11036. */
  11037. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11038. if (offset === void 0) { offset = 0; }
  11039. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11040. loop.executeNext();
  11041. return loop;
  11042. };
  11043. /**
  11044. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11045. * @param iterations total number of iterations
  11046. * @param syncedIterations number of synchronous iterations in each async iteration.
  11047. * @param fn the function to call each iteration.
  11048. * @param callback a success call back that will be called when iterating stops.
  11049. * @param breakFunction a break condition (optional)
  11050. * @param timeout timeout settings for the setTimeout function. default - 0.
  11051. * @returns the created async loop object
  11052. */
  11053. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11054. if (timeout === void 0) { timeout = 0; }
  11055. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11056. if (breakFunction && breakFunction())
  11057. loop.breakLoop();
  11058. else {
  11059. setTimeout(function () {
  11060. for (var i = 0; i < syncedIterations; ++i) {
  11061. var iteration = (loop.index * syncedIterations) + i;
  11062. if (iteration >= iterations)
  11063. break;
  11064. fn(iteration);
  11065. if (breakFunction && breakFunction()) {
  11066. loop.breakLoop();
  11067. break;
  11068. }
  11069. }
  11070. loop.executeNext();
  11071. }, timeout);
  11072. }
  11073. }, callback);
  11074. };
  11075. return AsyncLoop;
  11076. }());
  11077. BABYLON.AsyncLoop = AsyncLoop;
  11078. })(BABYLON || (BABYLON = {}));
  11079. //# sourceMappingURL=babylon.tools.js.map
  11080. var BABYLON;
  11081. (function (BABYLON) {
  11082. var PromiseStates;
  11083. (function (PromiseStates) {
  11084. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11085. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11086. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11087. })(PromiseStates || (PromiseStates = {}));
  11088. var FulFillmentAgregator = /** @class */ (function () {
  11089. function FulFillmentAgregator() {
  11090. this.count = 0;
  11091. this.target = 0;
  11092. this.results = [];
  11093. }
  11094. return FulFillmentAgregator;
  11095. }());
  11096. var InternalPromise = /** @class */ (function () {
  11097. function InternalPromise(resolver) {
  11098. var _this = this;
  11099. this._state = PromiseStates.Pending;
  11100. this._children = new Array();
  11101. this._rejectWasConsumed = false;
  11102. if (!resolver) {
  11103. return;
  11104. }
  11105. try {
  11106. resolver(function (value) {
  11107. _this._resolve(value);
  11108. }, function (reason) {
  11109. _this._reject(reason);
  11110. });
  11111. }
  11112. catch (e) {
  11113. this._reject(e);
  11114. }
  11115. }
  11116. Object.defineProperty(InternalPromise.prototype, "_result", {
  11117. get: function () {
  11118. return this._resultValue;
  11119. },
  11120. set: function (value) {
  11121. this._resultValue = value;
  11122. if (this._parent && this._parent._result === undefined) {
  11123. this._parent._result = value;
  11124. }
  11125. },
  11126. enumerable: true,
  11127. configurable: true
  11128. });
  11129. InternalPromise.prototype.catch = function (onRejected) {
  11130. return this.then(undefined, onRejected);
  11131. };
  11132. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11133. var _this = this;
  11134. var newPromise = new InternalPromise();
  11135. newPromise._onFulfilled = onFulfilled;
  11136. newPromise._onRejected = onRejected;
  11137. // Composition
  11138. this._children.push(newPromise);
  11139. newPromise._parent = this;
  11140. if (this._state !== PromiseStates.Pending) {
  11141. BABYLON.Tools.SetImmediate(function () {
  11142. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11143. var returnedValue = newPromise._resolve(_this._result);
  11144. if (returnedValue !== undefined && returnedValue !== null) {
  11145. if (returnedValue._state !== undefined) {
  11146. var returnedPromise = returnedValue;
  11147. newPromise._children.push(returnedPromise);
  11148. returnedPromise._parent = newPromise;
  11149. newPromise = returnedPromise;
  11150. }
  11151. else {
  11152. newPromise._result = returnedValue;
  11153. }
  11154. }
  11155. }
  11156. else {
  11157. newPromise._reject(_this._reason);
  11158. }
  11159. });
  11160. }
  11161. return newPromise;
  11162. };
  11163. InternalPromise.prototype._moveChildren = function (children) {
  11164. var _this = this;
  11165. var _a;
  11166. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11167. this._children.forEach(function (child) {
  11168. child._parent = _this;
  11169. });
  11170. if (this._state === PromiseStates.Fulfilled) {
  11171. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11172. var child = _b[_i];
  11173. child._resolve(this._result);
  11174. }
  11175. }
  11176. else if (this._state === PromiseStates.Rejected) {
  11177. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11178. var child = _d[_c];
  11179. child._reject(this._reason);
  11180. }
  11181. }
  11182. };
  11183. InternalPromise.prototype._resolve = function (value) {
  11184. try {
  11185. this._state = PromiseStates.Fulfilled;
  11186. var returnedValue = null;
  11187. if (this._onFulfilled) {
  11188. returnedValue = this._onFulfilled(value);
  11189. }
  11190. if (returnedValue !== undefined && returnedValue !== null) {
  11191. if (returnedValue._state !== undefined) {
  11192. // Transmit children
  11193. var returnedPromise = returnedValue;
  11194. returnedPromise._parent = this;
  11195. returnedPromise._moveChildren(this._children);
  11196. value = returnedPromise._result;
  11197. }
  11198. else {
  11199. value = returnedValue;
  11200. }
  11201. }
  11202. this._result = value;
  11203. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11204. var child = _a[_i];
  11205. child._resolve(value);
  11206. }
  11207. this._children.length = 0;
  11208. delete this._onFulfilled;
  11209. delete this._onRejected;
  11210. }
  11211. catch (e) {
  11212. this._reject(e, true);
  11213. }
  11214. };
  11215. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11216. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11217. this._state = PromiseStates.Rejected;
  11218. this._reason = reason;
  11219. if (this._onRejected && !onLocalThrow) {
  11220. try {
  11221. this._onRejected(reason);
  11222. this._rejectWasConsumed = true;
  11223. }
  11224. catch (e) {
  11225. reason = e;
  11226. }
  11227. }
  11228. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11229. var child = _a[_i];
  11230. if (this._rejectWasConsumed) {
  11231. child._resolve(null);
  11232. }
  11233. else {
  11234. child._reject(reason);
  11235. }
  11236. }
  11237. this._children.length = 0;
  11238. delete this._onFulfilled;
  11239. delete this._onRejected;
  11240. };
  11241. InternalPromise.resolve = function (value) {
  11242. var newPromise = new InternalPromise();
  11243. newPromise._resolve(value);
  11244. return newPromise;
  11245. };
  11246. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11247. promise.then(function (value) {
  11248. agregator.results[index] = value;
  11249. agregator.count++;
  11250. if (agregator.count === agregator.target) {
  11251. agregator.rootPromise._resolve(agregator.results);
  11252. }
  11253. return null;
  11254. }, function (reason) {
  11255. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11256. agregator.rootPromise._reject(reason);
  11257. }
  11258. });
  11259. };
  11260. InternalPromise.all = function (promises) {
  11261. var newPromise = new InternalPromise();
  11262. var agregator = new FulFillmentAgregator();
  11263. agregator.target = promises.length;
  11264. agregator.rootPromise = newPromise;
  11265. if (promises.length) {
  11266. for (var index = 0; index < promises.length; index++) {
  11267. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11268. }
  11269. }
  11270. else {
  11271. newPromise._resolve([]);
  11272. }
  11273. return newPromise;
  11274. };
  11275. InternalPromise.race = function (promises) {
  11276. var newPromise = new InternalPromise();
  11277. if (promises.length) {
  11278. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11279. var promise = promises_1[_i];
  11280. promise.then(function (value) {
  11281. if (newPromise) {
  11282. newPromise._resolve(value);
  11283. newPromise = null;
  11284. }
  11285. return null;
  11286. }, function (reason) {
  11287. if (newPromise) {
  11288. newPromise._reject(reason);
  11289. newPromise = null;
  11290. }
  11291. });
  11292. }
  11293. }
  11294. return newPromise;
  11295. };
  11296. return InternalPromise;
  11297. }());
  11298. /**
  11299. * Helper class that provides a small promise polyfill
  11300. */
  11301. var PromisePolyfill = /** @class */ (function () {
  11302. function PromisePolyfill() {
  11303. }
  11304. /**
  11305. * Static function used to check if the polyfill is required
  11306. * If this is the case then the function will inject the polyfill to window.Promise
  11307. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11308. */
  11309. PromisePolyfill.Apply = function (force) {
  11310. if (force === void 0) { force = false; }
  11311. if (force || typeof Promise === 'undefined') {
  11312. var root = window;
  11313. root.Promise = InternalPromise;
  11314. }
  11315. };
  11316. return PromisePolyfill;
  11317. }());
  11318. BABYLON.PromisePolyfill = PromisePolyfill;
  11319. })(BABYLON || (BABYLON = {}));
  11320. //# sourceMappingURL=babylon.promise.js.map
  11321. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11322. var BABYLON;
  11323. (function (BABYLON) {
  11324. /**
  11325. * Helper class to push actions to a pool of workers.
  11326. */
  11327. var WorkerPool = /** @class */ (function () {
  11328. /**
  11329. * Constructor
  11330. * @param workers Array of workers to use for actions
  11331. */
  11332. function WorkerPool(workers) {
  11333. this._pendingActions = new Array();
  11334. this._workerInfos = workers.map(function (worker) { return ({
  11335. worker: worker,
  11336. active: false
  11337. }); });
  11338. }
  11339. /**
  11340. * Terminates all workers and clears any pending actions.
  11341. */
  11342. WorkerPool.prototype.dispose = function () {
  11343. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11344. var workerInfo = _a[_i];
  11345. workerInfo.worker.terminate();
  11346. }
  11347. delete this._workerInfos;
  11348. delete this._pendingActions;
  11349. };
  11350. /**
  11351. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11352. * pended until a worker has completed its action.
  11353. * @param action The action to perform. Call onComplete when the action is complete.
  11354. */
  11355. WorkerPool.prototype.push = function (action) {
  11356. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11357. var workerInfo = _a[_i];
  11358. if (!workerInfo.active) {
  11359. this._execute(workerInfo, action);
  11360. return;
  11361. }
  11362. }
  11363. this._pendingActions.push(action);
  11364. };
  11365. WorkerPool.prototype._execute = function (workerInfo, action) {
  11366. var _this = this;
  11367. workerInfo.active = true;
  11368. action(workerInfo.worker, function () {
  11369. workerInfo.active = false;
  11370. var nextAction = _this._pendingActions.shift();
  11371. if (nextAction) {
  11372. _this._execute(workerInfo, nextAction);
  11373. }
  11374. });
  11375. };
  11376. return WorkerPool;
  11377. }());
  11378. BABYLON.WorkerPool = WorkerPool;
  11379. })(BABYLON || (BABYLON = {}));
  11380. //# sourceMappingURL=babylon.workerPool.js.map
  11381. var BABYLON;
  11382. (function (BABYLON) {
  11383. /**
  11384. * @hidden
  11385. **/
  11386. var _AlphaState = /** @class */ (function () {
  11387. /**
  11388. * Initializes the state.
  11389. */
  11390. function _AlphaState() {
  11391. this._isAlphaBlendDirty = false;
  11392. this._isBlendFunctionParametersDirty = false;
  11393. this._isBlendEquationParametersDirty = false;
  11394. this._isBlendConstantsDirty = false;
  11395. this._alphaBlend = false;
  11396. this._blendFunctionParameters = new Array(4);
  11397. this._blendEquationParameters = new Array(2);
  11398. this._blendConstants = new Array(4);
  11399. this.reset();
  11400. }
  11401. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11402. get: function () {
  11403. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11404. },
  11405. enumerable: true,
  11406. configurable: true
  11407. });
  11408. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11409. get: function () {
  11410. return this._alphaBlend;
  11411. },
  11412. set: function (value) {
  11413. if (this._alphaBlend === value) {
  11414. return;
  11415. }
  11416. this._alphaBlend = value;
  11417. this._isAlphaBlendDirty = true;
  11418. },
  11419. enumerable: true,
  11420. configurable: true
  11421. });
  11422. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11423. if (this._blendConstants[0] === r &&
  11424. this._blendConstants[1] === g &&
  11425. this._blendConstants[2] === b &&
  11426. this._blendConstants[3] === a) {
  11427. return;
  11428. }
  11429. this._blendConstants[0] = r;
  11430. this._blendConstants[1] = g;
  11431. this._blendConstants[2] = b;
  11432. this._blendConstants[3] = a;
  11433. this._isBlendConstantsDirty = true;
  11434. };
  11435. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11436. if (this._blendFunctionParameters[0] === value0 &&
  11437. this._blendFunctionParameters[1] === value1 &&
  11438. this._blendFunctionParameters[2] === value2 &&
  11439. this._blendFunctionParameters[3] === value3) {
  11440. return;
  11441. }
  11442. this._blendFunctionParameters[0] = value0;
  11443. this._blendFunctionParameters[1] = value1;
  11444. this._blendFunctionParameters[2] = value2;
  11445. this._blendFunctionParameters[3] = value3;
  11446. this._isBlendFunctionParametersDirty = true;
  11447. };
  11448. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11449. if (this._blendEquationParameters[0] === rgb &&
  11450. this._blendEquationParameters[1] === alpha) {
  11451. return;
  11452. }
  11453. this._blendEquationParameters[0] = rgb;
  11454. this._blendEquationParameters[1] = alpha;
  11455. this._isBlendEquationParametersDirty = true;
  11456. };
  11457. _AlphaState.prototype.reset = function () {
  11458. this._alphaBlend = false;
  11459. this._blendFunctionParameters[0] = null;
  11460. this._blendFunctionParameters[1] = null;
  11461. this._blendFunctionParameters[2] = null;
  11462. this._blendFunctionParameters[3] = null;
  11463. this._blendEquationParameters[0] = null;
  11464. this._blendEquationParameters[1] = null;
  11465. this._blendConstants[0] = null;
  11466. this._blendConstants[1] = null;
  11467. this._blendConstants[2] = null;
  11468. this._blendConstants[3] = null;
  11469. this._isAlphaBlendDirty = true;
  11470. this._isBlendFunctionParametersDirty = false;
  11471. this._isBlendEquationParametersDirty = false;
  11472. this._isBlendConstantsDirty = false;
  11473. };
  11474. _AlphaState.prototype.apply = function (gl) {
  11475. if (!this.isDirty) {
  11476. return;
  11477. }
  11478. // Alpha blend
  11479. if (this._isAlphaBlendDirty) {
  11480. if (this._alphaBlend) {
  11481. gl.enable(gl.BLEND);
  11482. }
  11483. else {
  11484. gl.disable(gl.BLEND);
  11485. }
  11486. this._isAlphaBlendDirty = false;
  11487. }
  11488. // Alpha function
  11489. if (this._isBlendFunctionParametersDirty) {
  11490. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11491. this._isBlendFunctionParametersDirty = false;
  11492. }
  11493. // Alpha equation
  11494. if (this._isBlendEquationParametersDirty) {
  11495. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11496. this._isBlendEquationParametersDirty = false;
  11497. }
  11498. // Constants
  11499. if (this._isBlendConstantsDirty) {
  11500. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11501. this._isBlendConstantsDirty = false;
  11502. }
  11503. };
  11504. return _AlphaState;
  11505. }());
  11506. BABYLON._AlphaState = _AlphaState;
  11507. })(BABYLON || (BABYLON = {}));
  11508. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11509. var BABYLON;
  11510. (function (BABYLON) {
  11511. /**
  11512. * @hidden
  11513. **/
  11514. var _DepthCullingState = /** @class */ (function () {
  11515. /**
  11516. * Initializes the state.
  11517. */
  11518. function _DepthCullingState() {
  11519. this._isDepthTestDirty = false;
  11520. this._isDepthMaskDirty = false;
  11521. this._isDepthFuncDirty = false;
  11522. this._isCullFaceDirty = false;
  11523. this._isCullDirty = false;
  11524. this._isZOffsetDirty = false;
  11525. this._isFrontFaceDirty = false;
  11526. this.reset();
  11527. }
  11528. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11529. get: function () {
  11530. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11531. },
  11532. enumerable: true,
  11533. configurable: true
  11534. });
  11535. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11536. get: function () {
  11537. return this._zOffset;
  11538. },
  11539. set: function (value) {
  11540. if (this._zOffset === value) {
  11541. return;
  11542. }
  11543. this._zOffset = value;
  11544. this._isZOffsetDirty = true;
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11550. get: function () {
  11551. return this._cullFace;
  11552. },
  11553. set: function (value) {
  11554. if (this._cullFace === value) {
  11555. return;
  11556. }
  11557. this._cullFace = value;
  11558. this._isCullFaceDirty = true;
  11559. },
  11560. enumerable: true,
  11561. configurable: true
  11562. });
  11563. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11564. get: function () {
  11565. return this._cull;
  11566. },
  11567. set: function (value) {
  11568. if (this._cull === value) {
  11569. return;
  11570. }
  11571. this._cull = value;
  11572. this._isCullDirty = true;
  11573. },
  11574. enumerable: true,
  11575. configurable: true
  11576. });
  11577. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11578. get: function () {
  11579. return this._depthFunc;
  11580. },
  11581. set: function (value) {
  11582. if (this._depthFunc === value) {
  11583. return;
  11584. }
  11585. this._depthFunc = value;
  11586. this._isDepthFuncDirty = true;
  11587. },
  11588. enumerable: true,
  11589. configurable: true
  11590. });
  11591. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11592. get: function () {
  11593. return this._depthMask;
  11594. },
  11595. set: function (value) {
  11596. if (this._depthMask === value) {
  11597. return;
  11598. }
  11599. this._depthMask = value;
  11600. this._isDepthMaskDirty = true;
  11601. },
  11602. enumerable: true,
  11603. configurable: true
  11604. });
  11605. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11606. get: function () {
  11607. return this._depthTest;
  11608. },
  11609. set: function (value) {
  11610. if (this._depthTest === value) {
  11611. return;
  11612. }
  11613. this._depthTest = value;
  11614. this._isDepthTestDirty = true;
  11615. },
  11616. enumerable: true,
  11617. configurable: true
  11618. });
  11619. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11620. get: function () {
  11621. return this._frontFace;
  11622. },
  11623. set: function (value) {
  11624. if (this._frontFace === value) {
  11625. return;
  11626. }
  11627. this._frontFace = value;
  11628. this._isFrontFaceDirty = true;
  11629. },
  11630. enumerable: true,
  11631. configurable: true
  11632. });
  11633. _DepthCullingState.prototype.reset = function () {
  11634. this._depthMask = true;
  11635. this._depthTest = true;
  11636. this._depthFunc = null;
  11637. this._cullFace = null;
  11638. this._cull = null;
  11639. this._zOffset = 0;
  11640. this._frontFace = null;
  11641. this._isDepthTestDirty = true;
  11642. this._isDepthMaskDirty = true;
  11643. this._isDepthFuncDirty = false;
  11644. this._isCullFaceDirty = false;
  11645. this._isCullDirty = false;
  11646. this._isZOffsetDirty = false;
  11647. this._isFrontFaceDirty = false;
  11648. };
  11649. _DepthCullingState.prototype.apply = function (gl) {
  11650. if (!this.isDirty) {
  11651. return;
  11652. }
  11653. // Cull
  11654. if (this._isCullDirty) {
  11655. if (this.cull) {
  11656. gl.enable(gl.CULL_FACE);
  11657. }
  11658. else {
  11659. gl.disable(gl.CULL_FACE);
  11660. }
  11661. this._isCullDirty = false;
  11662. }
  11663. // Cull face
  11664. if (this._isCullFaceDirty) {
  11665. gl.cullFace(this.cullFace);
  11666. this._isCullFaceDirty = false;
  11667. }
  11668. // Depth mask
  11669. if (this._isDepthMaskDirty) {
  11670. gl.depthMask(this.depthMask);
  11671. this._isDepthMaskDirty = false;
  11672. }
  11673. // Depth test
  11674. if (this._isDepthTestDirty) {
  11675. if (this.depthTest) {
  11676. gl.enable(gl.DEPTH_TEST);
  11677. }
  11678. else {
  11679. gl.disable(gl.DEPTH_TEST);
  11680. }
  11681. this._isDepthTestDirty = false;
  11682. }
  11683. // Depth func
  11684. if (this._isDepthFuncDirty) {
  11685. gl.depthFunc(this.depthFunc);
  11686. this._isDepthFuncDirty = false;
  11687. }
  11688. // zOffset
  11689. if (this._isZOffsetDirty) {
  11690. if (this.zOffset) {
  11691. gl.enable(gl.POLYGON_OFFSET_FILL);
  11692. gl.polygonOffset(this.zOffset, 0);
  11693. }
  11694. else {
  11695. gl.disable(gl.POLYGON_OFFSET_FILL);
  11696. }
  11697. this._isZOffsetDirty = false;
  11698. }
  11699. // Front face
  11700. if (this._isFrontFaceDirty) {
  11701. gl.frontFace(this.frontFace);
  11702. this._isFrontFaceDirty = false;
  11703. }
  11704. };
  11705. return _DepthCullingState;
  11706. }());
  11707. BABYLON._DepthCullingState = _DepthCullingState;
  11708. })(BABYLON || (BABYLON = {}));
  11709. //# sourceMappingURL=babylon.depthCullingState.js.map
  11710. var BABYLON;
  11711. (function (BABYLON) {
  11712. /**
  11713. * @hidden
  11714. **/
  11715. var _StencilState = /** @class */ (function () {
  11716. function _StencilState() {
  11717. this._isStencilTestDirty = false;
  11718. this._isStencilMaskDirty = false;
  11719. this._isStencilFuncDirty = false;
  11720. this._isStencilOpDirty = false;
  11721. this.reset();
  11722. }
  11723. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11724. get: function () {
  11725. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11731. get: function () {
  11732. return this._stencilFunc;
  11733. },
  11734. set: function (value) {
  11735. if (this._stencilFunc === value) {
  11736. return;
  11737. }
  11738. this._stencilFunc = value;
  11739. this._isStencilFuncDirty = true;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11745. get: function () {
  11746. return this._stencilFuncRef;
  11747. },
  11748. set: function (value) {
  11749. if (this._stencilFuncRef === value) {
  11750. return;
  11751. }
  11752. this._stencilFuncRef = value;
  11753. this._isStencilFuncDirty = true;
  11754. },
  11755. enumerable: true,
  11756. configurable: true
  11757. });
  11758. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11759. get: function () {
  11760. return this._stencilFuncMask;
  11761. },
  11762. set: function (value) {
  11763. if (this._stencilFuncMask === value) {
  11764. return;
  11765. }
  11766. this._stencilFuncMask = value;
  11767. this._isStencilFuncDirty = true;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11773. get: function () {
  11774. return this._stencilOpStencilFail;
  11775. },
  11776. set: function (value) {
  11777. if (this._stencilOpStencilFail === value) {
  11778. return;
  11779. }
  11780. this._stencilOpStencilFail = value;
  11781. this._isStencilOpDirty = true;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11787. get: function () {
  11788. return this._stencilOpDepthFail;
  11789. },
  11790. set: function (value) {
  11791. if (this._stencilOpDepthFail === value) {
  11792. return;
  11793. }
  11794. this._stencilOpDepthFail = value;
  11795. this._isStencilOpDirty = true;
  11796. },
  11797. enumerable: true,
  11798. configurable: true
  11799. });
  11800. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11801. get: function () {
  11802. return this._stencilOpStencilDepthPass;
  11803. },
  11804. set: function (value) {
  11805. if (this._stencilOpStencilDepthPass === value) {
  11806. return;
  11807. }
  11808. this._stencilOpStencilDepthPass = value;
  11809. this._isStencilOpDirty = true;
  11810. },
  11811. enumerable: true,
  11812. configurable: true
  11813. });
  11814. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11815. get: function () {
  11816. return this._stencilMask;
  11817. },
  11818. set: function (value) {
  11819. if (this._stencilMask === value) {
  11820. return;
  11821. }
  11822. this._stencilMask = value;
  11823. this._isStencilMaskDirty = true;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11829. get: function () {
  11830. return this._stencilTest;
  11831. },
  11832. set: function (value) {
  11833. if (this._stencilTest === value) {
  11834. return;
  11835. }
  11836. this._stencilTest = value;
  11837. this._isStencilTestDirty = true;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. _StencilState.prototype.reset = function () {
  11843. this._stencilTest = false;
  11844. this._stencilMask = 0xFF;
  11845. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11846. this._stencilFuncRef = 1;
  11847. this._stencilFuncMask = 0xFF;
  11848. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11849. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11850. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11851. this._isStencilTestDirty = true;
  11852. this._isStencilMaskDirty = true;
  11853. this._isStencilFuncDirty = true;
  11854. this._isStencilOpDirty = true;
  11855. };
  11856. _StencilState.prototype.apply = function (gl) {
  11857. if (!this.isDirty) {
  11858. return;
  11859. }
  11860. // Stencil test
  11861. if (this._isStencilTestDirty) {
  11862. if (this.stencilTest) {
  11863. gl.enable(gl.STENCIL_TEST);
  11864. }
  11865. else {
  11866. gl.disable(gl.STENCIL_TEST);
  11867. }
  11868. this._isStencilTestDirty = false;
  11869. }
  11870. // Stencil mask
  11871. if (this._isStencilMaskDirty) {
  11872. gl.stencilMask(this.stencilMask);
  11873. this._isStencilMaskDirty = false;
  11874. }
  11875. // Stencil func
  11876. if (this._isStencilFuncDirty) {
  11877. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11878. this._isStencilFuncDirty = false;
  11879. }
  11880. // Stencil op
  11881. if (this._isStencilOpDirty) {
  11882. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11883. this._isStencilOpDirty = false;
  11884. }
  11885. };
  11886. return _StencilState;
  11887. }());
  11888. BABYLON._StencilState = _StencilState;
  11889. })(BABYLON || (BABYLON = {}));
  11890. //# sourceMappingURL=babylon.stencilState.js.map
  11891. var __assign = (this && this.__assign) || function () {
  11892. __assign = Object.assign || function(t) {
  11893. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11894. s = arguments[i];
  11895. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11896. t[p] = s[p];
  11897. }
  11898. return t;
  11899. };
  11900. return __assign.apply(this, arguments);
  11901. };
  11902. var BABYLON;
  11903. (function (BABYLON) {
  11904. /**
  11905. * Keeps track of all the buffer info used in engine.
  11906. */
  11907. var BufferPointer = /** @class */ (function () {
  11908. function BufferPointer() {
  11909. }
  11910. return BufferPointer;
  11911. }());
  11912. /**
  11913. * Interface for attribute information associated with buffer instanciation
  11914. */
  11915. var InstancingAttributeInfo = /** @class */ (function () {
  11916. function InstancingAttributeInfo() {
  11917. }
  11918. return InstancingAttributeInfo;
  11919. }());
  11920. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11921. /**
  11922. * Define options used to create a render target texture
  11923. */
  11924. var RenderTargetCreationOptions = /** @class */ (function () {
  11925. function RenderTargetCreationOptions() {
  11926. }
  11927. return RenderTargetCreationOptions;
  11928. }());
  11929. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11930. /**
  11931. * Define options used to create a depth texture
  11932. */
  11933. var DepthTextureCreationOptions = /** @class */ (function () {
  11934. function DepthTextureCreationOptions() {
  11935. }
  11936. return DepthTextureCreationOptions;
  11937. }());
  11938. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11939. /**
  11940. * Class used to describe the capabilities of the engine relatively to the current browser
  11941. */
  11942. var EngineCapabilities = /** @class */ (function () {
  11943. function EngineCapabilities() {
  11944. }
  11945. return EngineCapabilities;
  11946. }());
  11947. BABYLON.EngineCapabilities = EngineCapabilities;
  11948. /**
  11949. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11950. */
  11951. var Engine = /** @class */ (function () {
  11952. /**
  11953. * Creates a new engine
  11954. * @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
  11955. * @param antialias defines enable antialiasing (default: false)
  11956. * @param options defines further options to be sent to the getContext() function
  11957. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11958. */
  11959. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11960. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11961. var _this = this;
  11962. // Public members
  11963. /**
  11964. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11965. */
  11966. this.forcePOTTextures = false;
  11967. /**
  11968. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11969. */
  11970. this.isFullscreen = false;
  11971. /**
  11972. * Gets a boolean indicating if the pointer is currently locked
  11973. */
  11974. this.isPointerLock = false;
  11975. /**
  11976. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11977. */
  11978. this.cullBackFaces = true;
  11979. /**
  11980. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11981. */
  11982. this.renderEvenInBackground = true;
  11983. /**
  11984. * Gets or sets a boolean indicating that cache can be kept between frames
  11985. */
  11986. this.preventCacheWipeBetweenFrames = false;
  11987. /**
  11988. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11989. **/
  11990. this.enableOfflineSupport = false;
  11991. /**
  11992. * 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)
  11993. **/
  11994. this.disableManifestCheck = false;
  11995. /**
  11996. * Gets the list of created scenes
  11997. */
  11998. this.scenes = new Array();
  11999. /**
  12000. * Gets the list of created postprocesses
  12001. */
  12002. this.postProcesses = new Array();
  12003. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12004. this.validateShaderPrograms = false;
  12005. // Observables
  12006. /**
  12007. * Observable event triggered each time the rendering canvas is resized
  12008. */
  12009. this.onResizeObservable = new BABYLON.Observable();
  12010. /**
  12011. * Observable event triggered each time the canvas loses focus
  12012. */
  12013. this.onCanvasBlurObservable = new BABYLON.Observable();
  12014. /**
  12015. * Observable event triggered each time the canvas gains focus
  12016. */
  12017. this.onCanvasFocusObservable = new BABYLON.Observable();
  12018. /**
  12019. * Observable event triggered each time the canvas receives pointerout event
  12020. */
  12021. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12022. /**
  12023. * Observable event triggered before each texture is initialized
  12024. */
  12025. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12026. //WebVR
  12027. this._vrDisplay = undefined;
  12028. this._vrSupported = false;
  12029. this._vrExclusivePointerMode = false;
  12030. // Uniform buffers list
  12031. /**
  12032. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12033. */
  12034. this.disableUniformBuffers = false;
  12035. /** @hidden */
  12036. this._uniformBuffers = new Array();
  12037. // Observables
  12038. /**
  12039. * Observable raised when the engine begins a new frame
  12040. */
  12041. this.onBeginFrameObservable = new BABYLON.Observable();
  12042. /**
  12043. * Observable raised when the engine ends the current frame
  12044. */
  12045. this.onEndFrameObservable = new BABYLON.Observable();
  12046. /**
  12047. * Observable raised when the engine is about to compile a shader
  12048. */
  12049. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12050. /**
  12051. * Observable raised when the engine has jsut compiled a shader
  12052. */
  12053. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12054. this._windowIsBackground = false;
  12055. this._webGLVersion = 1.0;
  12056. /** @hidden */
  12057. this._badOS = false;
  12058. /** @hidden */
  12059. this._badDesktopOS = false;
  12060. /**
  12061. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12062. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12063. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12064. */
  12065. this.disableTextureBindingOptimization = false;
  12066. /**
  12067. * Observable signaled when VR display mode changes
  12068. */
  12069. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12070. /**
  12071. * Observable signaled when VR request present is complete
  12072. */
  12073. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12074. /**
  12075. * Observable signaled when VR request present starts
  12076. */
  12077. this.onVRRequestPresentStart = new BABYLON.Observable();
  12078. this._colorWrite = true;
  12079. /** @hidden */
  12080. this._drawCalls = new BABYLON.PerfCounter();
  12081. /** @hidden */
  12082. this._textureCollisions = new BABYLON.PerfCounter();
  12083. this._renderingQueueLaunched = false;
  12084. this._activeRenderLoops = new Array();
  12085. // Deterministic lockstepMaxSteps
  12086. this._deterministicLockstep = false;
  12087. this._lockstepMaxSteps = 4;
  12088. // Lost context
  12089. /**
  12090. * Observable signaled when a context lost event is raised
  12091. */
  12092. this.onContextLostObservable = new BABYLON.Observable();
  12093. /**
  12094. * Observable signaled when a context restored event is raised
  12095. */
  12096. this.onContextRestoredObservable = new BABYLON.Observable();
  12097. this._contextWasLost = false;
  12098. this._doNotHandleContextLost = false;
  12099. // FPS
  12100. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12101. this._fps = 60;
  12102. this._deltaTime = 0;
  12103. /**
  12104. * Turn this value on if you want to pause FPS computation when in background
  12105. */
  12106. this.disablePerformanceMonitorInBackground = false;
  12107. // States
  12108. /** @hidden */
  12109. this._depthCullingState = new BABYLON._DepthCullingState();
  12110. /** @hidden */
  12111. this._stencilState = new BABYLON._StencilState();
  12112. /** @hidden */
  12113. this._alphaState = new BABYLON._AlphaState();
  12114. /** @hidden */
  12115. this._alphaMode = Engine.ALPHA_DISABLE;
  12116. // Cache
  12117. this._internalTexturesCache = new Array();
  12118. /** @hidden */
  12119. this._activeChannel = 0;
  12120. this._currentTextureChannel = -1;
  12121. /** @hidden */
  12122. this._boundTexturesCache = {};
  12123. this._compiledEffects = {};
  12124. this._vertexAttribArraysEnabled = [];
  12125. this._uintIndicesCurrentlySet = false;
  12126. this._currentBoundBuffer = new Array();
  12127. /** @hidden */
  12128. this._currentFramebuffer = null;
  12129. this._currentBufferPointers = new Array();
  12130. this._currentInstanceLocations = new Array();
  12131. this._currentInstanceBuffers = new Array();
  12132. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12133. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12134. this._vaoRecordInProgress = false;
  12135. this._mustWipeVertexAttributes = false;
  12136. this._nextFreeTextureSlots = new Array();
  12137. this._maxSimultaneousTextures = 0;
  12138. this._activeRequests = new Array();
  12139. // Hardware supported Compressed Textures
  12140. this._texturesSupported = new Array();
  12141. /**
  12142. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12143. */
  12144. this.premultipliedAlpha = true;
  12145. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12146. this._onVRFullScreenTriggered = function () {
  12147. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12148. //get the old size before we change
  12149. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12150. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12151. //get the width and height, change the render size
  12152. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12153. _this.setHardwareScalingLevel(1);
  12154. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12155. }
  12156. else {
  12157. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12158. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12159. }
  12160. };
  12161. this._unpackFlipYCached = null;
  12162. /**
  12163. * In case you are sharing the context with other applications, it might
  12164. * be interested to not cache the unpack flip y state to ensure a consistent
  12165. * value would be set.
  12166. */
  12167. this.enableUnpackFlipYCached = true;
  12168. this._boundUniforms = {};
  12169. // Register promises
  12170. BABYLON.PromisePolyfill.Apply();
  12171. var canvas = null;
  12172. Engine.Instances.push(this);
  12173. if (!canvasOrContext) {
  12174. return;
  12175. }
  12176. options = options || {};
  12177. if (canvasOrContext.getContext) {
  12178. canvas = canvasOrContext;
  12179. this._renderingCanvas = canvas;
  12180. if (antialias != null) {
  12181. options.antialias = antialias;
  12182. }
  12183. if (options.deterministicLockstep === undefined) {
  12184. options.deterministicLockstep = false;
  12185. }
  12186. if (options.lockstepMaxSteps === undefined) {
  12187. options.lockstepMaxSteps = 4;
  12188. }
  12189. if (options.preserveDrawingBuffer === undefined) {
  12190. options.preserveDrawingBuffer = false;
  12191. }
  12192. if (options.audioEngine === undefined) {
  12193. options.audioEngine = true;
  12194. }
  12195. if (options.stencil === undefined) {
  12196. options.stencil = true;
  12197. }
  12198. if (options.premultipliedAlpha === false) {
  12199. this.premultipliedAlpha = false;
  12200. }
  12201. this._deterministicLockstep = options.deterministicLockstep;
  12202. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12203. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12204. // Exceptions
  12205. if (navigator && navigator.userAgent) {
  12206. var ua = navigator.userAgent;
  12207. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12208. var exception = _a[_i];
  12209. var key = exception.key;
  12210. var targets = exception.targets;
  12211. if (ua.indexOf(key) > -1) {
  12212. if (exception.capture && exception.captureConstraint) {
  12213. var capture = exception.capture;
  12214. var constraint = exception.captureConstraint;
  12215. var regex = new RegExp(capture);
  12216. var matches = regex.exec(ua);
  12217. if (matches && matches.length > 0) {
  12218. var capturedValue = parseInt(matches[matches.length - 1]);
  12219. if (capturedValue >= constraint) {
  12220. continue;
  12221. }
  12222. }
  12223. }
  12224. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12225. var target = targets_1[_b];
  12226. switch (target) {
  12227. case "uniformBuffer":
  12228. this.disableUniformBuffers = true;
  12229. break;
  12230. case "textureBindingOptimization":
  12231. this.disableTextureBindingOptimization = true;
  12232. break;
  12233. }
  12234. }
  12235. }
  12236. }
  12237. }
  12238. // GL
  12239. if (!options.disableWebGL2Support) {
  12240. try {
  12241. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12242. if (this._gl) {
  12243. this._webGLVersion = 2.0;
  12244. }
  12245. }
  12246. catch (e) {
  12247. // Do nothing
  12248. }
  12249. }
  12250. if (!this._gl) {
  12251. if (!canvas) {
  12252. throw new Error("The provided canvas is null or undefined.");
  12253. }
  12254. try {
  12255. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12256. }
  12257. catch (e) {
  12258. throw new Error("WebGL not supported");
  12259. }
  12260. }
  12261. if (!this._gl) {
  12262. throw new Error("WebGL not supported");
  12263. }
  12264. this._onCanvasFocus = function () {
  12265. _this.onCanvasFocusObservable.notifyObservers(_this);
  12266. };
  12267. this._onCanvasBlur = function () {
  12268. _this.onCanvasBlurObservable.notifyObservers(_this);
  12269. };
  12270. canvas.addEventListener("focus", this._onCanvasFocus);
  12271. canvas.addEventListener("blur", this._onCanvasBlur);
  12272. this._onBlur = function () {
  12273. if (_this.disablePerformanceMonitorInBackground) {
  12274. _this._performanceMonitor.disable();
  12275. }
  12276. _this._windowIsBackground = true;
  12277. };
  12278. this._onFocus = function () {
  12279. if (_this.disablePerformanceMonitorInBackground) {
  12280. _this._performanceMonitor.enable();
  12281. }
  12282. _this._windowIsBackground = false;
  12283. };
  12284. this._onCanvasPointerOut = function (ev) {
  12285. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12286. };
  12287. window.addEventListener("blur", this._onBlur);
  12288. window.addEventListener("focus", this._onFocus);
  12289. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12290. // Context lost
  12291. if (!this._doNotHandleContextLost) {
  12292. this._onContextLost = function (evt) {
  12293. evt.preventDefault();
  12294. _this._contextWasLost = true;
  12295. BABYLON.Tools.Warn("WebGL context lost.");
  12296. _this.onContextLostObservable.notifyObservers(_this);
  12297. };
  12298. this._onContextRestored = function (evt) {
  12299. // Adding a timeout to avoid race condition at browser level
  12300. setTimeout(function () {
  12301. // Rebuild gl context
  12302. _this._initGLContext();
  12303. // Rebuild effects
  12304. _this._rebuildEffects();
  12305. // Rebuild textures
  12306. _this._rebuildInternalTextures();
  12307. // Rebuild buffers
  12308. _this._rebuildBuffers();
  12309. // Cache
  12310. _this.wipeCaches(true);
  12311. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12312. _this.onContextRestoredObservable.notifyObservers(_this);
  12313. _this._contextWasLost = false;
  12314. }, 0);
  12315. };
  12316. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12317. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12318. }
  12319. }
  12320. else {
  12321. this._gl = canvasOrContext;
  12322. this._renderingCanvas = this._gl.canvas;
  12323. if (this._gl.renderbufferStorageMultisample) {
  12324. this._webGLVersion = 2.0;
  12325. }
  12326. options.stencil = this._gl.getContextAttributes().stencil;
  12327. }
  12328. // Viewport
  12329. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12330. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12331. this.resize();
  12332. this._isStencilEnable = options.stencil ? true : false;
  12333. this._initGLContext();
  12334. if (canvas) {
  12335. // Fullscreen
  12336. this._onFullscreenChange = function () {
  12337. if (document.fullscreen !== undefined) {
  12338. _this.isFullscreen = document.fullscreen;
  12339. }
  12340. else if (document.mozFullScreen !== undefined) {
  12341. _this.isFullscreen = document.mozFullScreen;
  12342. }
  12343. else if (document.webkitIsFullScreen !== undefined) {
  12344. _this.isFullscreen = document.webkitIsFullScreen;
  12345. }
  12346. else if (document.msIsFullScreen !== undefined) {
  12347. _this.isFullscreen = document.msIsFullScreen;
  12348. }
  12349. // Pointer lock
  12350. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12351. canvas.requestPointerLock = canvas.requestPointerLock ||
  12352. canvas.msRequestPointerLock ||
  12353. canvas.mozRequestPointerLock ||
  12354. canvas.webkitRequestPointerLock;
  12355. if (canvas.requestPointerLock) {
  12356. canvas.requestPointerLock();
  12357. }
  12358. }
  12359. };
  12360. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12361. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12362. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12363. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12364. // Pointer lock
  12365. this._onPointerLockChange = function () {
  12366. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12367. document.webkitPointerLockElement === canvas ||
  12368. document.msPointerLockElement === canvas ||
  12369. document.pointerLockElement === canvas);
  12370. };
  12371. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12372. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12373. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12374. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12375. this._onVRDisplayPointerRestricted = function () {
  12376. if (canvas) {
  12377. canvas.requestPointerLock();
  12378. }
  12379. };
  12380. this._onVRDisplayPointerUnrestricted = function () {
  12381. document.exitPointerLock();
  12382. };
  12383. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12384. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12385. }
  12386. // Create Audio Engine if needed.
  12387. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12388. Engine.audioEngine = Engine.AudioEngineFactory(this);
  12389. }
  12390. // Prepare buffer pointers
  12391. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12392. this._currentBufferPointers[i] = new BufferPointer();
  12393. }
  12394. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12395. // Load WebVR Devices
  12396. if (options.autoEnableWebVR) {
  12397. this.initWebVR();
  12398. }
  12399. // Detect if we are running on a faulty buggy OS.
  12400. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12401. // Detect if we are running on a faulty buggy desktop OS.
  12402. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12403. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12404. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12405. }
  12406. Object.defineProperty(Engine, "LastCreatedEngine", {
  12407. /**
  12408. * Gets the latest created engine
  12409. */
  12410. get: function () {
  12411. if (Engine.Instances.length === 0) {
  12412. return null;
  12413. }
  12414. return Engine.Instances[Engine.Instances.length - 1];
  12415. },
  12416. enumerable: true,
  12417. configurable: true
  12418. });
  12419. Object.defineProperty(Engine, "LastCreatedScene", {
  12420. /**
  12421. * Gets the latest created scene
  12422. */
  12423. get: function () {
  12424. var lastCreatedEngine = Engine.LastCreatedEngine;
  12425. if (!lastCreatedEngine) {
  12426. return null;
  12427. }
  12428. if (lastCreatedEngine.scenes.length === 0) {
  12429. return null;
  12430. }
  12431. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12432. },
  12433. enumerable: true,
  12434. configurable: true
  12435. });
  12436. /**
  12437. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12438. * @param flag defines which part of the materials must be marked as dirty
  12439. * @param predicate defines a predicate used to filter which materials should be affected
  12440. */
  12441. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12442. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12443. var engine = Engine.Instances[engineIndex];
  12444. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12445. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12446. }
  12447. }
  12448. };
  12449. Object.defineProperty(Engine, "Version", {
  12450. /**
  12451. * Returns the current version of the framework
  12452. */
  12453. get: function () {
  12454. return "3.3.0-rc.2";
  12455. },
  12456. enumerable: true,
  12457. configurable: true
  12458. });
  12459. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12460. /**
  12461. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12462. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12463. */
  12464. get: function () {
  12465. return this._vrExclusivePointerMode;
  12466. },
  12467. enumerable: true,
  12468. configurable: true
  12469. });
  12470. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12471. /**
  12472. * Gets a boolean indicating that the engine supports uniform buffers
  12473. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12474. */
  12475. get: function () {
  12476. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12477. },
  12478. enumerable: true,
  12479. configurable: true
  12480. });
  12481. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12482. /**
  12483. * Gets a boolean indicating that only power of 2 textures are supported
  12484. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12485. */
  12486. get: function () {
  12487. return this._webGLVersion < 2 || this.forcePOTTextures;
  12488. },
  12489. enumerable: true,
  12490. configurable: true
  12491. });
  12492. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12493. /**
  12494. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12495. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12496. */
  12497. get: function () {
  12498. return this._doNotHandleContextLost;
  12499. },
  12500. set: function (value) {
  12501. this._doNotHandleContextLost = value;
  12502. },
  12503. enumerable: true,
  12504. configurable: true
  12505. });
  12506. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12507. /**
  12508. * Gets the performance monitor attached to this engine
  12509. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12510. */
  12511. get: function () {
  12512. return this._performanceMonitor;
  12513. },
  12514. enumerable: true,
  12515. configurable: true
  12516. });
  12517. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12518. /**
  12519. * Gets the list of texture formats supported
  12520. */
  12521. get: function () {
  12522. return this._texturesSupported;
  12523. },
  12524. enumerable: true,
  12525. configurable: true
  12526. });
  12527. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12528. /**
  12529. * Gets the list of texture formats in use
  12530. */
  12531. get: function () {
  12532. return this._textureFormatInUse;
  12533. },
  12534. enumerable: true,
  12535. configurable: true
  12536. });
  12537. Object.defineProperty(Engine.prototype, "currentViewport", {
  12538. /**
  12539. * Gets the current viewport
  12540. */
  12541. get: function () {
  12542. return this._cachedViewport;
  12543. },
  12544. enumerable: true,
  12545. configurable: true
  12546. });
  12547. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12548. /**
  12549. * Gets the default empty texture
  12550. */
  12551. get: function () {
  12552. if (!this._emptyTexture) {
  12553. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12554. }
  12555. return this._emptyTexture;
  12556. },
  12557. enumerable: true,
  12558. configurable: true
  12559. });
  12560. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12561. /**
  12562. * Gets the default empty 3D texture
  12563. */
  12564. get: function () {
  12565. if (!this._emptyTexture3D) {
  12566. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12567. }
  12568. return this._emptyTexture3D;
  12569. },
  12570. enumerable: true,
  12571. configurable: true
  12572. });
  12573. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12574. /**
  12575. * Gets the default empty cube texture
  12576. */
  12577. get: function () {
  12578. if (!this._emptyCubeTexture) {
  12579. var faceData = new Uint8Array(4);
  12580. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12581. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12582. }
  12583. return this._emptyCubeTexture;
  12584. },
  12585. enumerable: true,
  12586. configurable: true
  12587. });
  12588. Engine.prototype._rebuildInternalTextures = function () {
  12589. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12590. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12591. var internalTexture = currentState_1[_i];
  12592. internalTexture._rebuild();
  12593. }
  12594. };
  12595. Engine.prototype._rebuildEffects = function () {
  12596. for (var key in this._compiledEffects) {
  12597. var effect = this._compiledEffects[key];
  12598. effect._prepareEffect();
  12599. }
  12600. BABYLON.Effect.ResetCache();
  12601. };
  12602. Engine.prototype._rebuildBuffers = function () {
  12603. // Index / Vertex
  12604. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12605. var scene = _a[_i];
  12606. scene.resetCachedMaterial();
  12607. scene._rebuildGeometries();
  12608. scene._rebuildTextures();
  12609. }
  12610. // Uniforms
  12611. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12612. var uniformBuffer = _c[_b];
  12613. uniformBuffer._rebuild();
  12614. }
  12615. };
  12616. Engine.prototype._initGLContext = function () {
  12617. // Caps
  12618. this._caps = new EngineCapabilities();
  12619. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12620. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12621. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12622. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12623. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12624. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12625. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12626. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12627. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12628. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12629. // Infos
  12630. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12631. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12632. if (rendererInfo != null) {
  12633. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12634. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12635. }
  12636. if (!this._glVendor) {
  12637. this._glVendor = "Unknown vendor";
  12638. }
  12639. if (!this._glRenderer) {
  12640. this._glRenderer = "Unknown renderer";
  12641. }
  12642. // Constants
  12643. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12644. if (this._gl.RGBA16F !== 0x881A) {
  12645. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12646. }
  12647. if (this._gl.RGBA32F !== 0x8814) {
  12648. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12649. }
  12650. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12651. this._gl.DEPTH24_STENCIL8 = 35056;
  12652. }
  12653. // Extensions
  12654. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12655. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12656. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12657. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12658. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12659. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12660. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12661. 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');
  12662. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12663. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12664. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12665. this._caps.highPrecisionShaderSupported = true;
  12666. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12667. if (this._caps.timerQuery) {
  12668. if (this._webGLVersion === 1) {
  12669. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12670. }
  12671. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12672. }
  12673. // Checks if some of the format renders first to allow the use of webgl inspector.
  12674. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12675. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12676. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12677. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12678. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12679. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12680. if (this._webGLVersion > 1) {
  12681. this._gl.HALF_FLOAT_OES = 0x140B;
  12682. }
  12683. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12684. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12685. // Draw buffers
  12686. if (this._webGLVersion > 1) {
  12687. this._caps.drawBuffersExtension = true;
  12688. }
  12689. else {
  12690. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12691. if (drawBuffersExtension !== null) {
  12692. this._caps.drawBuffersExtension = true;
  12693. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12694. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12695. for (var i = 0; i < 16; i++) {
  12696. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12697. }
  12698. }
  12699. else {
  12700. this._caps.drawBuffersExtension = false;
  12701. }
  12702. }
  12703. // Depth Texture
  12704. if (this._webGLVersion > 1) {
  12705. this._caps.depthTextureExtension = true;
  12706. }
  12707. else {
  12708. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12709. if (depthTextureExtension != null) {
  12710. this._caps.depthTextureExtension = true;
  12711. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12712. }
  12713. }
  12714. // Vertex array object
  12715. if (this._webGLVersion > 1) {
  12716. this._caps.vertexArrayObject = true;
  12717. }
  12718. else {
  12719. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12720. if (vertexArrayObjectExtension != null) {
  12721. this._caps.vertexArrayObject = true;
  12722. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12723. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12724. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12725. }
  12726. else {
  12727. this._caps.vertexArrayObject = false;
  12728. }
  12729. }
  12730. // Instances count
  12731. if (this._webGLVersion > 1) {
  12732. this._caps.instancedArrays = true;
  12733. }
  12734. else {
  12735. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12736. if (instanceExtension != null) {
  12737. this._caps.instancedArrays = true;
  12738. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12739. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12740. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12741. }
  12742. else {
  12743. this._caps.instancedArrays = false;
  12744. }
  12745. }
  12746. // Intelligently add supported compressed formats in order to check for.
  12747. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12748. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12749. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12750. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12751. if (this._caps.astc)
  12752. this.texturesSupported.push('-astc.ktx');
  12753. if (this._caps.s3tc)
  12754. this.texturesSupported.push('-dxt.ktx');
  12755. if (this._caps.pvrtc)
  12756. this.texturesSupported.push('-pvrtc.ktx');
  12757. if (this._caps.etc2)
  12758. this.texturesSupported.push('-etc2.ktx');
  12759. if (this._caps.etc1)
  12760. this.texturesSupported.push('-etc1.ktx');
  12761. if (this._gl.getShaderPrecisionFormat) {
  12762. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12763. if (highp) {
  12764. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12765. }
  12766. }
  12767. // Depth buffer
  12768. this.setDepthBuffer(true);
  12769. this.setDepthFunctionToLessOrEqual();
  12770. this.setDepthWrite(true);
  12771. // Texture maps
  12772. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12773. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12774. this._nextFreeTextureSlots.push(slot);
  12775. }
  12776. };
  12777. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12778. /**
  12779. * Gets version of the current webGL context
  12780. */
  12781. get: function () {
  12782. return this._webGLVersion;
  12783. },
  12784. enumerable: true,
  12785. configurable: true
  12786. });
  12787. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12788. /**
  12789. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12790. */
  12791. get: function () {
  12792. return this._isStencilEnable;
  12793. },
  12794. enumerable: true,
  12795. configurable: true
  12796. });
  12797. Engine.prototype._prepareWorkingCanvas = function () {
  12798. if (this._workingCanvas) {
  12799. return;
  12800. }
  12801. this._workingCanvas = document.createElement("canvas");
  12802. var context = this._workingCanvas.getContext("2d");
  12803. if (context) {
  12804. this._workingContext = context;
  12805. }
  12806. };
  12807. /**
  12808. * Reset the texture cache to empty state
  12809. */
  12810. Engine.prototype.resetTextureCache = function () {
  12811. for (var key in this._boundTexturesCache) {
  12812. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12813. continue;
  12814. }
  12815. var boundTexture = this._boundTexturesCache[key];
  12816. if (boundTexture) {
  12817. this._removeDesignatedSlot(boundTexture);
  12818. }
  12819. this._boundTexturesCache[key] = null;
  12820. }
  12821. if (!this.disableTextureBindingOptimization) {
  12822. this._nextFreeTextureSlots = [];
  12823. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12824. this._nextFreeTextureSlots.push(slot);
  12825. }
  12826. }
  12827. this._currentTextureChannel = -1;
  12828. };
  12829. /**
  12830. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12831. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12832. * @returns true if engine is in deterministic lock step mode
  12833. */
  12834. Engine.prototype.isDeterministicLockStep = function () {
  12835. return this._deterministicLockstep;
  12836. };
  12837. /**
  12838. * Gets the max steps when engine is running in deterministic lock step
  12839. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12840. * @returns the max steps
  12841. */
  12842. Engine.prototype.getLockstepMaxSteps = function () {
  12843. return this._lockstepMaxSteps;
  12844. };
  12845. /**
  12846. * Gets an object containing information about the current webGL context
  12847. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12848. */
  12849. Engine.prototype.getGlInfo = function () {
  12850. return {
  12851. vendor: this._glVendor,
  12852. renderer: this._glRenderer,
  12853. version: this._glVersion
  12854. };
  12855. };
  12856. /**
  12857. * Gets current aspect ratio
  12858. * @param camera defines the camera to use to get the aspect ratio
  12859. * @param useScreen defines if screen size must be used (or the current render target if any)
  12860. * @returns a number defining the aspect ratio
  12861. */
  12862. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12863. if (useScreen === void 0) { useScreen = false; }
  12864. var viewport = camera.viewport;
  12865. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12866. };
  12867. /**
  12868. * Gets current screen aspect ratio
  12869. * @returns a number defining the aspect ratio
  12870. */
  12871. Engine.prototype.getScreenAspectRatio = function () {
  12872. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12873. };
  12874. /**
  12875. * Gets the current render width
  12876. * @param useScreen defines if screen size must be used (or the current render target if any)
  12877. * @returns a number defining the current render width
  12878. */
  12879. Engine.prototype.getRenderWidth = function (useScreen) {
  12880. if (useScreen === void 0) { useScreen = false; }
  12881. if (!useScreen && this._currentRenderTarget) {
  12882. return this._currentRenderTarget.width;
  12883. }
  12884. return this._gl.drawingBufferWidth;
  12885. };
  12886. /**
  12887. * Gets the current render height
  12888. * @param useScreen defines if screen size must be used (or the current render target if any)
  12889. * @returns a number defining the current render height
  12890. */
  12891. Engine.prototype.getRenderHeight = function (useScreen) {
  12892. if (useScreen === void 0) { useScreen = false; }
  12893. if (!useScreen && this._currentRenderTarget) {
  12894. return this._currentRenderTarget.height;
  12895. }
  12896. return this._gl.drawingBufferHeight;
  12897. };
  12898. /**
  12899. * Gets the HTML canvas attached with the current webGL context
  12900. * @returns a HTML canvas
  12901. */
  12902. Engine.prototype.getRenderingCanvas = function () {
  12903. return this._renderingCanvas;
  12904. };
  12905. /**
  12906. * Gets the client rect of the HTML canvas attached with the current webGL context
  12907. * @returns a client rectanglee
  12908. */
  12909. Engine.prototype.getRenderingCanvasClientRect = function () {
  12910. if (!this._renderingCanvas) {
  12911. return null;
  12912. }
  12913. return this._renderingCanvas.getBoundingClientRect();
  12914. };
  12915. /**
  12916. * Defines the hardware scaling level.
  12917. * By default the hardware scaling level is computed from the window device ratio.
  12918. * 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.
  12919. * @param level defines the level to use
  12920. */
  12921. Engine.prototype.setHardwareScalingLevel = function (level) {
  12922. this._hardwareScalingLevel = level;
  12923. this.resize();
  12924. };
  12925. /**
  12926. * Gets the current hardware scaling level.
  12927. * By default the hardware scaling level is computed from the window device ratio.
  12928. * 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.
  12929. * @returns a number indicating the current hardware scaling level
  12930. */
  12931. Engine.prototype.getHardwareScalingLevel = function () {
  12932. return this._hardwareScalingLevel;
  12933. };
  12934. /**
  12935. * Gets the list of loaded textures
  12936. * @returns an array containing all loaded textures
  12937. */
  12938. Engine.prototype.getLoadedTexturesCache = function () {
  12939. return this._internalTexturesCache;
  12940. };
  12941. /**
  12942. * Gets the object containing all engine capabilities
  12943. * @returns the EngineCapabilities object
  12944. */
  12945. Engine.prototype.getCaps = function () {
  12946. return this._caps;
  12947. };
  12948. Object.defineProperty(Engine.prototype, "drawCalls", {
  12949. /** @hidden */
  12950. get: function () {
  12951. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12952. return 0;
  12953. },
  12954. enumerable: true,
  12955. configurable: true
  12956. });
  12957. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12958. /** @hidden */
  12959. get: function () {
  12960. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12961. return null;
  12962. },
  12963. enumerable: true,
  12964. configurable: true
  12965. });
  12966. /**
  12967. * Gets the current depth function
  12968. * @returns a number defining the depth function
  12969. */
  12970. Engine.prototype.getDepthFunction = function () {
  12971. return this._depthCullingState.depthFunc;
  12972. };
  12973. /**
  12974. * Sets the current depth function
  12975. * @param depthFunc defines the function to use
  12976. */
  12977. Engine.prototype.setDepthFunction = function (depthFunc) {
  12978. this._depthCullingState.depthFunc = depthFunc;
  12979. };
  12980. /**
  12981. * Sets the current depth function to GREATER
  12982. */
  12983. Engine.prototype.setDepthFunctionToGreater = function () {
  12984. this._depthCullingState.depthFunc = this._gl.GREATER;
  12985. };
  12986. /**
  12987. * Sets the current depth function to GEQUAL
  12988. */
  12989. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12990. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12991. };
  12992. /**
  12993. * Sets the current depth function to LESS
  12994. */
  12995. Engine.prototype.setDepthFunctionToLess = function () {
  12996. this._depthCullingState.depthFunc = this._gl.LESS;
  12997. };
  12998. /**
  12999. * Sets the current depth function to LEQUAL
  13000. */
  13001. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13002. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13003. };
  13004. /**
  13005. * Gets a boolean indicating if stencil buffer is enabled
  13006. * @returns the current stencil buffer state
  13007. */
  13008. Engine.prototype.getStencilBuffer = function () {
  13009. return this._stencilState.stencilTest;
  13010. };
  13011. /**
  13012. * Enable or disable the stencil buffer
  13013. * @param enable defines if the stencil buffer must be enabled or disabled
  13014. */
  13015. Engine.prototype.setStencilBuffer = function (enable) {
  13016. this._stencilState.stencilTest = enable;
  13017. };
  13018. /**
  13019. * Gets the current stencil mask
  13020. * @returns a number defining the new stencil mask to use
  13021. */
  13022. Engine.prototype.getStencilMask = function () {
  13023. return this._stencilState.stencilMask;
  13024. };
  13025. /**
  13026. * Sets the current stencil mask
  13027. * @param mask defines the new stencil mask to use
  13028. */
  13029. Engine.prototype.setStencilMask = function (mask) {
  13030. this._stencilState.stencilMask = mask;
  13031. };
  13032. /**
  13033. * Gets the current stencil function
  13034. * @returns a number defining the stencil function to use
  13035. */
  13036. Engine.prototype.getStencilFunction = function () {
  13037. return this._stencilState.stencilFunc;
  13038. };
  13039. /**
  13040. * Gets the current stencil reference value
  13041. * @returns a number defining the stencil reference value to use
  13042. */
  13043. Engine.prototype.getStencilFunctionReference = function () {
  13044. return this._stencilState.stencilFuncRef;
  13045. };
  13046. /**
  13047. * Gets the current stencil mask
  13048. * @returns a number defining the stencil mask to use
  13049. */
  13050. Engine.prototype.getStencilFunctionMask = function () {
  13051. return this._stencilState.stencilFuncMask;
  13052. };
  13053. /**
  13054. * Sets the current stencil function
  13055. * @param stencilFunc defines the new stencil function to use
  13056. */
  13057. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13058. this._stencilState.stencilFunc = stencilFunc;
  13059. };
  13060. /**
  13061. * Sets the current stencil reference
  13062. * @param reference defines the new stencil reference to use
  13063. */
  13064. Engine.prototype.setStencilFunctionReference = function (reference) {
  13065. this._stencilState.stencilFuncRef = reference;
  13066. };
  13067. /**
  13068. * Sets the current stencil mask
  13069. * @param mask defines the new stencil mask to use
  13070. */
  13071. Engine.prototype.setStencilFunctionMask = function (mask) {
  13072. this._stencilState.stencilFuncMask = mask;
  13073. };
  13074. /**
  13075. * Gets the current stencil operation when stencil fails
  13076. * @returns a number defining stencil operation to use when stencil fails
  13077. */
  13078. Engine.prototype.getStencilOperationFail = function () {
  13079. return this._stencilState.stencilOpStencilFail;
  13080. };
  13081. /**
  13082. * Gets the current stencil operation when depth fails
  13083. * @returns a number defining stencil operation to use when depth fails
  13084. */
  13085. Engine.prototype.getStencilOperationDepthFail = function () {
  13086. return this._stencilState.stencilOpDepthFail;
  13087. };
  13088. /**
  13089. * Gets the current stencil operation when stencil passes
  13090. * @returns a number defining stencil operation to use when stencil passes
  13091. */
  13092. Engine.prototype.getStencilOperationPass = function () {
  13093. return this._stencilState.stencilOpStencilDepthPass;
  13094. };
  13095. /**
  13096. * Sets the stencil operation to use when stencil fails
  13097. * @param operation defines the stencil operation to use when stencil fails
  13098. */
  13099. Engine.prototype.setStencilOperationFail = function (operation) {
  13100. this._stencilState.stencilOpStencilFail = operation;
  13101. };
  13102. /**
  13103. * Sets the stencil operation to use when depth fails
  13104. * @param operation defines the stencil operation to use when depth fails
  13105. */
  13106. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13107. this._stencilState.stencilOpDepthFail = operation;
  13108. };
  13109. /**
  13110. * Sets the stencil operation to use when stencil passes
  13111. * @param operation defines the stencil operation to use when stencil passes
  13112. */
  13113. Engine.prototype.setStencilOperationPass = function (operation) {
  13114. this._stencilState.stencilOpStencilDepthPass = operation;
  13115. };
  13116. /**
  13117. * Sets a boolean indicating if the dithering state is enabled or disabled
  13118. * @param value defines the dithering state
  13119. */
  13120. Engine.prototype.setDitheringState = function (value) {
  13121. if (value) {
  13122. this._gl.enable(this._gl.DITHER);
  13123. }
  13124. else {
  13125. this._gl.disable(this._gl.DITHER);
  13126. }
  13127. };
  13128. /**
  13129. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13130. * @param value defines the rasterizer state
  13131. */
  13132. Engine.prototype.setRasterizerState = function (value) {
  13133. if (value) {
  13134. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13135. }
  13136. else {
  13137. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13138. }
  13139. };
  13140. /**
  13141. * stop executing a render loop function and remove it from the execution array
  13142. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13143. */
  13144. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13145. if (!renderFunction) {
  13146. this._activeRenderLoops = [];
  13147. return;
  13148. }
  13149. var index = this._activeRenderLoops.indexOf(renderFunction);
  13150. if (index >= 0) {
  13151. this._activeRenderLoops.splice(index, 1);
  13152. }
  13153. };
  13154. /** @hidden */
  13155. Engine.prototype._renderLoop = function () {
  13156. if (!this._contextWasLost) {
  13157. var shouldRender = true;
  13158. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13159. shouldRender = false;
  13160. }
  13161. if (shouldRender) {
  13162. // Start new frame
  13163. this.beginFrame();
  13164. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13165. var renderFunction = this._activeRenderLoops[index];
  13166. renderFunction();
  13167. }
  13168. // Present
  13169. this.endFrame();
  13170. }
  13171. }
  13172. if (this._activeRenderLoops.length > 0) {
  13173. // Register new frame
  13174. var requester = null;
  13175. if (this._vrDisplay && this._vrDisplay.isPresenting)
  13176. requester = this._vrDisplay;
  13177. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13178. }
  13179. else {
  13180. this._renderingQueueLaunched = false;
  13181. }
  13182. };
  13183. /**
  13184. * Register and execute a render loop. The engine can have more than one render function
  13185. * @param renderFunction defines the function to continuously execute
  13186. */
  13187. Engine.prototype.runRenderLoop = function (renderFunction) {
  13188. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13189. return;
  13190. }
  13191. this._activeRenderLoops.push(renderFunction);
  13192. if (!this._renderingQueueLaunched) {
  13193. this._renderingQueueLaunched = true;
  13194. this._bindedRenderFunction = this._renderLoop.bind(this);
  13195. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13196. }
  13197. };
  13198. /**
  13199. * Toggle full screen mode
  13200. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13201. */
  13202. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13203. if (this.isFullscreen) {
  13204. BABYLON.Tools.ExitFullscreen();
  13205. }
  13206. else {
  13207. this._pointerLockRequested = requestPointerLock;
  13208. if (this._renderingCanvas) {
  13209. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13210. }
  13211. }
  13212. };
  13213. /**
  13214. * Clear the current render buffer or the current render target (if any is set up)
  13215. * @param color defines the color to use
  13216. * @param backBuffer defines if the back buffer must be cleared
  13217. * @param depth defines if the depth buffer must be cleared
  13218. * @param stencil defines if the stencil buffer must be cleared
  13219. */
  13220. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13221. if (stencil === void 0) { stencil = false; }
  13222. this.applyStates();
  13223. var mode = 0;
  13224. if (backBuffer && color) {
  13225. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13226. mode |= this._gl.COLOR_BUFFER_BIT;
  13227. }
  13228. if (depth) {
  13229. this._gl.clearDepth(1.0);
  13230. mode |= this._gl.DEPTH_BUFFER_BIT;
  13231. }
  13232. if (stencil) {
  13233. this._gl.clearStencil(0);
  13234. mode |= this._gl.STENCIL_BUFFER_BIT;
  13235. }
  13236. this._gl.clear(mode);
  13237. };
  13238. /**
  13239. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13240. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13241. * @param y defines the y-coordinate of the corner of the clear rectangle
  13242. * @param width defines the width of the clear rectangle
  13243. * @param height defines the height of the clear rectangle
  13244. * @param clearColor defines the clear color
  13245. */
  13246. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13247. var gl = this._gl;
  13248. // Save state
  13249. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13250. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13251. // Change state
  13252. gl.enable(gl.SCISSOR_TEST);
  13253. gl.scissor(x, y, width, height);
  13254. // Clear
  13255. this.clear(clearColor, true, true, true);
  13256. // Restore state
  13257. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13258. if (curScissor === true) {
  13259. gl.enable(gl.SCISSOR_TEST);
  13260. }
  13261. else {
  13262. gl.disable(gl.SCISSOR_TEST);
  13263. }
  13264. };
  13265. /** @hidden */
  13266. Engine.prototype._viewport = function (x, y, width, height) {
  13267. if (x !== this._viewportCached.x ||
  13268. y !== this._viewportCached.y ||
  13269. width !== this._viewportCached.z ||
  13270. height !== this._viewportCached.w) {
  13271. this._viewportCached.x = x;
  13272. this._viewportCached.y = y;
  13273. this._viewportCached.z = width;
  13274. this._viewportCached.w = height;
  13275. this._gl.viewport(x, y, width, height);
  13276. }
  13277. };
  13278. /**
  13279. * Set the WebGL's viewport
  13280. * @param viewport defines the viewport element to be used
  13281. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13282. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13283. */
  13284. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13285. var width = requiredWidth || this.getRenderWidth();
  13286. var height = requiredHeight || this.getRenderHeight();
  13287. var x = viewport.x || 0;
  13288. var y = viewport.y || 0;
  13289. this._cachedViewport = viewport;
  13290. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13291. };
  13292. /**
  13293. * Directly set the WebGL Viewport
  13294. * @param x defines the x coordinate of the viewport (in screen space)
  13295. * @param y defines the y coordinate of the viewport (in screen space)
  13296. * @param width defines the width of the viewport (in screen space)
  13297. * @param height defines the height of the viewport (in screen space)
  13298. * @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
  13299. */
  13300. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13301. var currentViewport = this._cachedViewport;
  13302. this._cachedViewport = null;
  13303. this._viewport(x, y, width, height);
  13304. return currentViewport;
  13305. };
  13306. /**
  13307. * Begin a new frame
  13308. */
  13309. Engine.prototype.beginFrame = function () {
  13310. this.onBeginFrameObservable.notifyObservers(this);
  13311. this._measureFps();
  13312. };
  13313. /**
  13314. * Enf the current frame
  13315. */
  13316. Engine.prototype.endFrame = function () {
  13317. // Force a flush in case we are using a bad OS.
  13318. if (this._badOS) {
  13319. this.flushFramebuffer();
  13320. }
  13321. // Submit frame to the vr device, if enabled
  13322. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13323. // TODO: We should only submit the frame if we read frameData successfully.
  13324. this._vrDisplay.submitFrame();
  13325. }
  13326. this.onEndFrameObservable.notifyObservers(this);
  13327. };
  13328. /**
  13329. * Resize the view according to the canvas' size
  13330. */
  13331. Engine.prototype.resize = function () {
  13332. // We're not resizing the size of the canvas while in VR mode & presenting
  13333. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13334. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13335. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13336. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13337. }
  13338. };
  13339. /**
  13340. * Force a specific size of the canvas
  13341. * @param width defines the new canvas' width
  13342. * @param height defines the new canvas' height
  13343. */
  13344. Engine.prototype.setSize = function (width, height) {
  13345. if (!this._renderingCanvas) {
  13346. return;
  13347. }
  13348. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13349. return;
  13350. }
  13351. this._renderingCanvas.width = width;
  13352. this._renderingCanvas.height = height;
  13353. for (var index = 0; index < this.scenes.length; index++) {
  13354. var scene = this.scenes[index];
  13355. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13356. var cam = scene.cameras[camIndex];
  13357. cam._currentRenderId = 0;
  13358. }
  13359. }
  13360. if (this.onResizeObservable.hasObservers) {
  13361. this.onResizeObservable.notifyObservers(this);
  13362. }
  13363. };
  13364. // WebVR functions
  13365. /**
  13366. * Gets a boolean indicating if a webVR device was detected
  13367. * @returns true if a webVR device was detected
  13368. */
  13369. Engine.prototype.isVRDevicePresent = function () {
  13370. return !!this._vrDisplay;
  13371. };
  13372. /**
  13373. * Gets the current webVR device
  13374. * @returns the current webVR device (or null)
  13375. */
  13376. Engine.prototype.getVRDevice = function () {
  13377. return this._vrDisplay;
  13378. };
  13379. /**
  13380. * Initializes a webVR display and starts listening to display change events
  13381. * The onVRDisplayChangedObservable will be notified upon these changes
  13382. * @returns The onVRDisplayChangedObservable
  13383. */
  13384. Engine.prototype.initWebVR = function () {
  13385. this.initWebVRAsync();
  13386. return this.onVRDisplayChangedObservable;
  13387. };
  13388. /**
  13389. * Initializes a webVR display and starts listening to display change events
  13390. * The onVRDisplayChangedObservable will be notified upon these changes
  13391. * @returns A promise containing a VRDisplay and if vr is supported
  13392. */
  13393. Engine.prototype.initWebVRAsync = function () {
  13394. var _this = this;
  13395. var notifyObservers = function () {
  13396. var eventArgs = {
  13397. vrDisplay: _this._vrDisplay,
  13398. vrSupported: _this._vrSupported
  13399. };
  13400. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13401. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13402. };
  13403. if (!this._onVrDisplayConnect) {
  13404. this._onVrDisplayConnect = function (event) {
  13405. _this._vrDisplay = event.display;
  13406. notifyObservers();
  13407. };
  13408. this._onVrDisplayDisconnect = function () {
  13409. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13410. _this._vrDisplay = undefined;
  13411. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13412. notifyObservers();
  13413. };
  13414. this._onVrDisplayPresentChange = function () {
  13415. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13416. };
  13417. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13418. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13419. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13420. }
  13421. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13422. this._webVRInitPromise.then(notifyObservers);
  13423. return this._webVRInitPromise;
  13424. };
  13425. /**
  13426. * Call this function to switch to webVR mode
  13427. * Will do nothing if webVR is not supported or if there is no webVR device
  13428. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13429. */
  13430. Engine.prototype.enableVR = function () {
  13431. var _this = this;
  13432. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13433. var onResolved = function () {
  13434. _this.onVRRequestPresentComplete.notifyObservers(true);
  13435. _this._onVRFullScreenTriggered();
  13436. };
  13437. var onRejected = function () {
  13438. _this.onVRRequestPresentComplete.notifyObservers(false);
  13439. };
  13440. this.onVRRequestPresentStart.notifyObservers(this);
  13441. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13442. }
  13443. };
  13444. /**
  13445. * Call this function to leave webVR mode
  13446. * Will do nothing if webVR is not supported or if there is no webVR device
  13447. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13448. */
  13449. Engine.prototype.disableVR = function () {
  13450. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13451. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13452. }
  13453. };
  13454. Engine.prototype._getVRDisplaysAsync = function () {
  13455. var _this = this;
  13456. return new Promise(function (res, rej) {
  13457. if (navigator.getVRDisplays) {
  13458. navigator.getVRDisplays().then(function (devices) {
  13459. _this._vrSupported = true;
  13460. // note that devices may actually be an empty array. This is fine;
  13461. // we expect this._vrDisplay to be undefined in this case.
  13462. _this._vrDisplay = devices[0];
  13463. res({
  13464. vrDisplay: _this._vrDisplay,
  13465. vrSupported: _this._vrSupported
  13466. });
  13467. });
  13468. }
  13469. else {
  13470. _this._vrDisplay = undefined;
  13471. _this._vrSupported = false;
  13472. res({
  13473. vrDisplay: _this._vrDisplay,
  13474. vrSupported: _this._vrSupported
  13475. });
  13476. }
  13477. });
  13478. };
  13479. /**
  13480. * Binds the frame buffer to the specified texture.
  13481. * @param texture The texture to render to or null for the default canvas
  13482. * @param faceIndex The face of the texture to render to in case of cube texture
  13483. * @param requiredWidth The width of the target to render to
  13484. * @param requiredHeight The height of the target to render to
  13485. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13486. * @param depthStencilTexture The depth stencil texture to use to render
  13487. * @param lodLevel defines le lod level to bind to the frame buffer
  13488. */
  13489. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13490. if (lodLevel === void 0) { lodLevel = 0; }
  13491. if (this._currentRenderTarget) {
  13492. this.unBindFramebuffer(this._currentRenderTarget);
  13493. }
  13494. this._currentRenderTarget = texture;
  13495. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13496. var gl = this._gl;
  13497. if (texture.isCube) {
  13498. if (faceIndex === undefined) {
  13499. faceIndex = 0;
  13500. }
  13501. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13502. if (depthStencilTexture) {
  13503. if (depthStencilTexture._generateStencilBuffer) {
  13504. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13505. }
  13506. else {
  13507. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13508. }
  13509. }
  13510. }
  13511. if (this._cachedViewport && !forceFullscreenViewport) {
  13512. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13513. }
  13514. else {
  13515. if (!requiredWidth) {
  13516. requiredWidth = texture.width;
  13517. if (lodLevel) {
  13518. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13519. }
  13520. }
  13521. if (!requiredHeight) {
  13522. requiredHeight = texture.height;
  13523. if (lodLevel) {
  13524. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13525. }
  13526. }
  13527. this._viewport(0, 0, requiredWidth, requiredHeight);
  13528. }
  13529. this.wipeCaches();
  13530. };
  13531. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13532. if (this._currentFramebuffer !== framebuffer) {
  13533. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13534. this._currentFramebuffer = framebuffer;
  13535. }
  13536. };
  13537. /**
  13538. * Unbind the current render target texture from the webGL context
  13539. * @param texture defines the render target texture to unbind
  13540. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13541. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13542. */
  13543. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13544. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13545. this._currentRenderTarget = null;
  13546. // If MSAA, we need to bitblt back to main texture
  13547. var gl = this._gl;
  13548. if (texture._MSAAFramebuffer) {
  13549. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13550. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13551. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13552. }
  13553. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13554. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13555. gl.generateMipmap(gl.TEXTURE_2D);
  13556. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13557. }
  13558. if (onBeforeUnbind) {
  13559. if (texture._MSAAFramebuffer) {
  13560. // Bind the correct framebuffer
  13561. this.bindUnboundFramebuffer(texture._framebuffer);
  13562. }
  13563. onBeforeUnbind();
  13564. }
  13565. this.bindUnboundFramebuffer(null);
  13566. };
  13567. /**
  13568. * Unbind a list of render target textures from the webGL context
  13569. * This is used only when drawBuffer extension or webGL2 are active
  13570. * @param textures defines the render target textures to unbind
  13571. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13572. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13573. */
  13574. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13575. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13576. this._currentRenderTarget = null;
  13577. // If MSAA, we need to bitblt back to main texture
  13578. var gl = this._gl;
  13579. if (textures[0]._MSAAFramebuffer) {
  13580. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13581. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13582. var attachments = textures[0]._attachments;
  13583. if (!attachments) {
  13584. attachments = new Array(textures.length);
  13585. textures[0]._attachments = attachments;
  13586. }
  13587. for (var i = 0; i < textures.length; i++) {
  13588. var texture = textures[i];
  13589. for (var j = 0; j < attachments.length; j++) {
  13590. attachments[j] = gl.NONE;
  13591. }
  13592. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13593. gl.readBuffer(attachments[i]);
  13594. gl.drawBuffers(attachments);
  13595. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13596. }
  13597. for (var i = 0; i < attachments.length; i++) {
  13598. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13599. }
  13600. gl.drawBuffers(attachments);
  13601. }
  13602. for (var i = 0; i < textures.length; i++) {
  13603. var texture = textures[i];
  13604. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13605. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13606. gl.generateMipmap(gl.TEXTURE_2D);
  13607. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13608. }
  13609. }
  13610. if (onBeforeUnbind) {
  13611. if (textures[0]._MSAAFramebuffer) {
  13612. // Bind the correct framebuffer
  13613. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13614. }
  13615. onBeforeUnbind();
  13616. }
  13617. this.bindUnboundFramebuffer(null);
  13618. };
  13619. /**
  13620. * Force the mipmap generation for the given render target texture
  13621. * @param texture defines the render target texture to use
  13622. */
  13623. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13624. if (texture.generateMipMaps) {
  13625. var gl = this._gl;
  13626. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13627. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13628. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13629. }
  13630. };
  13631. /**
  13632. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13633. */
  13634. Engine.prototype.flushFramebuffer = function () {
  13635. this._gl.flush();
  13636. };
  13637. /**
  13638. * Unbind the current render target and bind the default framebuffer
  13639. */
  13640. Engine.prototype.restoreDefaultFramebuffer = function () {
  13641. if (this._currentRenderTarget) {
  13642. this.unBindFramebuffer(this._currentRenderTarget);
  13643. }
  13644. else {
  13645. this.bindUnboundFramebuffer(null);
  13646. }
  13647. if (this._cachedViewport) {
  13648. this.setViewport(this._cachedViewport);
  13649. }
  13650. this.wipeCaches();
  13651. };
  13652. // UBOs
  13653. /**
  13654. * Create an uniform buffer
  13655. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13656. * @param elements defines the content of the uniform buffer
  13657. * @returns the webGL uniform buffer
  13658. */
  13659. Engine.prototype.createUniformBuffer = function (elements) {
  13660. var ubo = this._gl.createBuffer();
  13661. if (!ubo) {
  13662. throw new Error("Unable to create uniform buffer");
  13663. }
  13664. this.bindUniformBuffer(ubo);
  13665. if (elements instanceof Float32Array) {
  13666. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13667. }
  13668. else {
  13669. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13670. }
  13671. this.bindUniformBuffer(null);
  13672. ubo.references = 1;
  13673. return ubo;
  13674. };
  13675. /**
  13676. * Create a dynamic uniform buffer
  13677. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13678. * @param elements defines the content of the uniform buffer
  13679. * @returns the webGL uniform buffer
  13680. */
  13681. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13682. var ubo = this._gl.createBuffer();
  13683. if (!ubo) {
  13684. throw new Error("Unable to create dynamic uniform buffer");
  13685. }
  13686. this.bindUniformBuffer(ubo);
  13687. if (elements instanceof Float32Array) {
  13688. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13689. }
  13690. else {
  13691. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13692. }
  13693. this.bindUniformBuffer(null);
  13694. ubo.references = 1;
  13695. return ubo;
  13696. };
  13697. /**
  13698. * Update an existing uniform buffer
  13699. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13700. * @param uniformBuffer defines the target uniform buffer
  13701. * @param elements defines the content to update
  13702. * @param offset defines the offset in the uniform buffer where update should start
  13703. * @param count defines the size of the data to update
  13704. */
  13705. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13706. this.bindUniformBuffer(uniformBuffer);
  13707. if (offset === undefined) {
  13708. offset = 0;
  13709. }
  13710. if (count === undefined) {
  13711. if (elements instanceof Float32Array) {
  13712. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13713. }
  13714. else {
  13715. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13716. }
  13717. }
  13718. else {
  13719. if (elements instanceof Float32Array) {
  13720. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13721. }
  13722. else {
  13723. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13724. }
  13725. }
  13726. this.bindUniformBuffer(null);
  13727. };
  13728. // VBOs
  13729. Engine.prototype._resetVertexBufferBinding = function () {
  13730. this.bindArrayBuffer(null);
  13731. this._cachedVertexBuffers = null;
  13732. };
  13733. /**
  13734. * Creates a vertex buffer
  13735. * @param data the data for the vertex buffer
  13736. * @returns the new WebGL static buffer
  13737. */
  13738. Engine.prototype.createVertexBuffer = function (data) {
  13739. var vbo = this._gl.createBuffer();
  13740. if (!vbo) {
  13741. throw new Error("Unable to create vertex buffer");
  13742. }
  13743. this.bindArrayBuffer(vbo);
  13744. if (data instanceof Array) {
  13745. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13746. }
  13747. else {
  13748. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13749. }
  13750. this._resetVertexBufferBinding();
  13751. vbo.references = 1;
  13752. return vbo;
  13753. };
  13754. /**
  13755. * Creates a dynamic vertex buffer
  13756. * @param data the data for the dynamic vertex buffer
  13757. * @returns the new WebGL dynamic buffer
  13758. */
  13759. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13760. var vbo = this._gl.createBuffer();
  13761. if (!vbo) {
  13762. throw new Error("Unable to create dynamic vertex buffer");
  13763. }
  13764. this.bindArrayBuffer(vbo);
  13765. if (data instanceof Array) {
  13766. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13767. }
  13768. else {
  13769. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13770. }
  13771. this._resetVertexBufferBinding();
  13772. vbo.references = 1;
  13773. return vbo;
  13774. };
  13775. /**
  13776. * Update a dynamic index buffer
  13777. * @param indexBuffer defines the target index buffer
  13778. * @param indices defines the data to update
  13779. * @param offset defines the offset in the target index buffer where update should start
  13780. */
  13781. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13782. if (offset === void 0) { offset = 0; }
  13783. // Force cache update
  13784. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13785. this.bindIndexBuffer(indexBuffer);
  13786. var arrayBuffer;
  13787. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13788. arrayBuffer = indices;
  13789. }
  13790. else {
  13791. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13792. }
  13793. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13794. this._resetIndexBufferBinding();
  13795. };
  13796. /**
  13797. * Updates a dynamic vertex buffer.
  13798. * @param vertexBuffer the vertex buffer to update
  13799. * @param data the data used to update the vertex buffer
  13800. * @param byteOffset the byte offset of the data
  13801. * @param byteLength the byte length of the data
  13802. */
  13803. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13804. this.bindArrayBuffer(vertexBuffer);
  13805. if (byteOffset === undefined) {
  13806. byteOffset = 0;
  13807. }
  13808. if (byteLength === undefined) {
  13809. if (data instanceof Array) {
  13810. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13811. }
  13812. else {
  13813. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13814. }
  13815. }
  13816. else {
  13817. if (data instanceof Array) {
  13818. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13819. }
  13820. else {
  13821. if (data instanceof ArrayBuffer) {
  13822. data = new Uint8Array(data, byteOffset, byteLength);
  13823. }
  13824. else {
  13825. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13826. }
  13827. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13828. }
  13829. }
  13830. this._resetVertexBufferBinding();
  13831. };
  13832. Engine.prototype._resetIndexBufferBinding = function () {
  13833. this.bindIndexBuffer(null);
  13834. this._cachedIndexBuffer = null;
  13835. };
  13836. /**
  13837. * Creates a new index buffer
  13838. * @param indices defines the content of the index buffer
  13839. * @param updatable defines if the index buffer must be updatable
  13840. * @returns a new webGL buffer
  13841. */
  13842. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13843. var vbo = this._gl.createBuffer();
  13844. if (!vbo) {
  13845. throw new Error("Unable to create index buffer");
  13846. }
  13847. this.bindIndexBuffer(vbo);
  13848. // Check for 32 bits indices
  13849. var arrayBuffer;
  13850. var need32Bits = false;
  13851. if (indices instanceof Uint16Array) {
  13852. arrayBuffer = indices;
  13853. }
  13854. else {
  13855. //check 32 bit support
  13856. if (this._caps.uintIndices) {
  13857. if (indices instanceof Uint32Array) {
  13858. arrayBuffer = indices;
  13859. need32Bits = true;
  13860. }
  13861. else {
  13862. //number[] or Int32Array, check if 32 bit is necessary
  13863. for (var index = 0; index < indices.length; index++) {
  13864. if (indices[index] > 65535) {
  13865. need32Bits = true;
  13866. break;
  13867. }
  13868. }
  13869. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13870. }
  13871. }
  13872. else {
  13873. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13874. arrayBuffer = new Uint16Array(indices);
  13875. }
  13876. }
  13877. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13878. this._resetIndexBufferBinding();
  13879. vbo.references = 1;
  13880. vbo.is32Bits = need32Bits;
  13881. return vbo;
  13882. };
  13883. /**
  13884. * Bind a webGL buffer to the webGL context
  13885. * @param buffer defines the buffer to bind
  13886. */
  13887. Engine.prototype.bindArrayBuffer = function (buffer) {
  13888. if (!this._vaoRecordInProgress) {
  13889. this._unbindVertexArrayObject();
  13890. }
  13891. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13892. };
  13893. /**
  13894. * Bind an uniform buffer to the current webGL context
  13895. * @param buffer defines the buffer to bind
  13896. */
  13897. Engine.prototype.bindUniformBuffer = function (buffer) {
  13898. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13899. };
  13900. /**
  13901. * Bind a buffer to the current webGL context at a given location
  13902. * @param buffer defines the buffer to bind
  13903. * @param location defines the index where to bind the buffer
  13904. */
  13905. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13906. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13907. };
  13908. /**
  13909. * Bind a specific block at a given index in a specific shader program
  13910. * @param shaderProgram defines the shader program
  13911. * @param blockName defines the block name
  13912. * @param index defines the index where to bind the block
  13913. */
  13914. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13915. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13916. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13917. };
  13918. ;
  13919. Engine.prototype.bindIndexBuffer = function (buffer) {
  13920. if (!this._vaoRecordInProgress) {
  13921. this._unbindVertexArrayObject();
  13922. }
  13923. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13924. };
  13925. Engine.prototype.bindBuffer = function (buffer, target) {
  13926. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13927. this._gl.bindBuffer(target, buffer);
  13928. this._currentBoundBuffer[target] = buffer;
  13929. }
  13930. };
  13931. /**
  13932. * update the bound buffer with the given data
  13933. * @param data defines the data to update
  13934. */
  13935. Engine.prototype.updateArrayBuffer = function (data) {
  13936. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13937. };
  13938. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13939. var pointer = this._currentBufferPointers[indx];
  13940. var changed = false;
  13941. if (!pointer.active) {
  13942. changed = true;
  13943. pointer.active = true;
  13944. pointer.index = indx;
  13945. pointer.size = size;
  13946. pointer.type = type;
  13947. pointer.normalized = normalized;
  13948. pointer.stride = stride;
  13949. pointer.offset = offset;
  13950. pointer.buffer = buffer;
  13951. }
  13952. else {
  13953. if (pointer.buffer !== buffer) {
  13954. pointer.buffer = buffer;
  13955. changed = true;
  13956. }
  13957. if (pointer.size !== size) {
  13958. pointer.size = size;
  13959. changed = true;
  13960. }
  13961. if (pointer.type !== type) {
  13962. pointer.type = type;
  13963. changed = true;
  13964. }
  13965. if (pointer.normalized !== normalized) {
  13966. pointer.normalized = normalized;
  13967. changed = true;
  13968. }
  13969. if (pointer.stride !== stride) {
  13970. pointer.stride = stride;
  13971. changed = true;
  13972. }
  13973. if (pointer.offset !== offset) {
  13974. pointer.offset = offset;
  13975. changed = true;
  13976. }
  13977. }
  13978. if (changed || this._vaoRecordInProgress) {
  13979. this.bindArrayBuffer(buffer);
  13980. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13981. }
  13982. };
  13983. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13984. if (indexBuffer == null) {
  13985. return;
  13986. }
  13987. if (this._cachedIndexBuffer !== indexBuffer) {
  13988. this._cachedIndexBuffer = indexBuffer;
  13989. this.bindIndexBuffer(indexBuffer);
  13990. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13991. }
  13992. };
  13993. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13994. var attributes = effect.getAttributesNames();
  13995. if (!this._vaoRecordInProgress) {
  13996. this._unbindVertexArrayObject();
  13997. }
  13998. this.unbindAllAttributes();
  13999. for (var index = 0; index < attributes.length; index++) {
  14000. var order = effect.getAttributeLocation(index);
  14001. if (order >= 0) {
  14002. var vertexBuffer = vertexBuffers[attributes[index]];
  14003. if (!vertexBuffer) {
  14004. continue;
  14005. }
  14006. this._gl.enableVertexAttribArray(order);
  14007. if (!this._vaoRecordInProgress) {
  14008. this._vertexAttribArraysEnabled[order] = true;
  14009. }
  14010. var buffer = vertexBuffer.getBuffer();
  14011. if (buffer) {
  14012. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14013. if (vertexBuffer.getIsInstanced()) {
  14014. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14015. if (!this._vaoRecordInProgress) {
  14016. this._currentInstanceLocations.push(order);
  14017. this._currentInstanceBuffers.push(buffer);
  14018. }
  14019. }
  14020. }
  14021. }
  14022. }
  14023. };
  14024. /**
  14025. * Records a vertex array object
  14026. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14027. * @param vertexBuffers defines the list of vertex buffers to store
  14028. * @param indexBuffer defines the index buffer to store
  14029. * @param effect defines the effect to store
  14030. * @returns the new vertex array object
  14031. */
  14032. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14033. var vao = this._gl.createVertexArray();
  14034. this._vaoRecordInProgress = true;
  14035. this._gl.bindVertexArray(vao);
  14036. this._mustWipeVertexAttributes = true;
  14037. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14038. this.bindIndexBuffer(indexBuffer);
  14039. this._vaoRecordInProgress = false;
  14040. this._gl.bindVertexArray(null);
  14041. return vao;
  14042. };
  14043. /**
  14044. * Bind a specific vertex array object
  14045. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14046. * @param vertexArrayObject defines the vertex array object to bind
  14047. * @param indexBuffer defines the index buffer to bind
  14048. */
  14049. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14050. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14051. this._cachedVertexArrayObject = vertexArrayObject;
  14052. this._gl.bindVertexArray(vertexArrayObject);
  14053. this._cachedVertexBuffers = null;
  14054. this._cachedIndexBuffer = null;
  14055. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14056. this._mustWipeVertexAttributes = true;
  14057. }
  14058. };
  14059. /**
  14060. * Bind webGl buffers directly to the webGL context
  14061. * @param vertexBuffer defines the vertex buffer to bind
  14062. * @param indexBuffer defines the index buffer to bind
  14063. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14064. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14065. * @param effect defines the effect associated with the vertex buffer
  14066. */
  14067. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14068. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14069. this._cachedVertexBuffers = vertexBuffer;
  14070. this._cachedEffectForVertexBuffers = effect;
  14071. var attributesCount = effect.getAttributesCount();
  14072. this._unbindVertexArrayObject();
  14073. this.unbindAllAttributes();
  14074. var offset = 0;
  14075. for (var index = 0; index < attributesCount; index++) {
  14076. if (index < vertexDeclaration.length) {
  14077. var order = effect.getAttributeLocation(index);
  14078. if (order >= 0) {
  14079. this._gl.enableVertexAttribArray(order);
  14080. this._vertexAttribArraysEnabled[order] = true;
  14081. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14082. }
  14083. offset += vertexDeclaration[index] * 4;
  14084. }
  14085. }
  14086. }
  14087. this._bindIndexBufferWithCache(indexBuffer);
  14088. };
  14089. Engine.prototype._unbindVertexArrayObject = function () {
  14090. if (!this._cachedVertexArrayObject) {
  14091. return;
  14092. }
  14093. this._cachedVertexArrayObject = null;
  14094. this._gl.bindVertexArray(null);
  14095. };
  14096. /**
  14097. * Bind a list of vertex buffers to the webGL context
  14098. * @param vertexBuffers defines the list of vertex buffers to bind
  14099. * @param indexBuffer defines the index buffer to bind
  14100. * @param effect defines the effect associated with the vertex buffers
  14101. */
  14102. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14103. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14104. this._cachedVertexBuffers = vertexBuffers;
  14105. this._cachedEffectForVertexBuffers = effect;
  14106. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14107. }
  14108. this._bindIndexBufferWithCache(indexBuffer);
  14109. };
  14110. /**
  14111. * Unbind all instance attributes
  14112. */
  14113. Engine.prototype.unbindInstanceAttributes = function () {
  14114. var boundBuffer;
  14115. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14116. var instancesBuffer = this._currentInstanceBuffers[i];
  14117. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14118. boundBuffer = instancesBuffer;
  14119. this.bindArrayBuffer(instancesBuffer);
  14120. }
  14121. var offsetLocation = this._currentInstanceLocations[i];
  14122. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14123. }
  14124. this._currentInstanceBuffers.length = 0;
  14125. this._currentInstanceLocations.length = 0;
  14126. };
  14127. /**
  14128. * Release and free the memory of a vertex array object
  14129. * @param vao defines the vertex array object to delete
  14130. */
  14131. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14132. this._gl.deleteVertexArray(vao);
  14133. };
  14134. /** @hidden */
  14135. Engine.prototype._releaseBuffer = function (buffer) {
  14136. buffer.references--;
  14137. if (buffer.references === 0) {
  14138. this._gl.deleteBuffer(buffer);
  14139. return true;
  14140. }
  14141. return false;
  14142. };
  14143. /**
  14144. * Creates a webGL buffer to use with instanciation
  14145. * @param capacity defines the size of the buffer
  14146. * @returns the webGL buffer
  14147. */
  14148. Engine.prototype.createInstancesBuffer = function (capacity) {
  14149. var buffer = this._gl.createBuffer();
  14150. if (!buffer) {
  14151. throw new Error("Unable to create instance buffer");
  14152. }
  14153. buffer.capacity = capacity;
  14154. this.bindArrayBuffer(buffer);
  14155. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14156. return buffer;
  14157. };
  14158. /**
  14159. * Delete a webGL buffer used with instanciation
  14160. * @param buffer defines the webGL buffer to delete
  14161. */
  14162. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14163. this._gl.deleteBuffer(buffer);
  14164. };
  14165. /**
  14166. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14167. * @param instancesBuffer defines the webGL buffer to update and bind
  14168. * @param data defines the data to store in the buffer
  14169. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14170. */
  14171. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14172. this.bindArrayBuffer(instancesBuffer);
  14173. if (data) {
  14174. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14175. }
  14176. if (offsetLocations[0].index !== undefined) {
  14177. var stride = 0;
  14178. for (var i = 0; i < offsetLocations.length; i++) {
  14179. var ai = offsetLocations[i];
  14180. stride += ai.attributeSize * 4;
  14181. }
  14182. for (var i = 0; i < offsetLocations.length; i++) {
  14183. var ai = offsetLocations[i];
  14184. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14185. this._gl.enableVertexAttribArray(ai.index);
  14186. this._vertexAttribArraysEnabled[ai.index] = true;
  14187. }
  14188. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14189. this._gl.vertexAttribDivisor(ai.index, 1);
  14190. this._currentInstanceLocations.push(ai.index);
  14191. this._currentInstanceBuffers.push(instancesBuffer);
  14192. }
  14193. }
  14194. else {
  14195. for (var index = 0; index < 4; index++) {
  14196. var offsetLocation = offsetLocations[index];
  14197. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14198. this._gl.enableVertexAttribArray(offsetLocation);
  14199. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14200. }
  14201. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14202. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14203. this._currentInstanceLocations.push(offsetLocation);
  14204. this._currentInstanceBuffers.push(instancesBuffer);
  14205. }
  14206. }
  14207. };
  14208. /**
  14209. * Apply all cached states (depth, culling, stencil and alpha)
  14210. */
  14211. Engine.prototype.applyStates = function () {
  14212. this._depthCullingState.apply(this._gl);
  14213. this._stencilState.apply(this._gl);
  14214. this._alphaState.apply(this._gl);
  14215. };
  14216. /**
  14217. * Send a draw order
  14218. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14219. * @param indexStart defines the starting index
  14220. * @param indexCount defines the number of index to draw
  14221. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14222. */
  14223. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14224. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14225. };
  14226. /**
  14227. * Draw a list of points
  14228. * @param verticesStart defines the index of first vertex to draw
  14229. * @param verticesCount defines the count of vertices to draw
  14230. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14231. */
  14232. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14233. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14234. };
  14235. /**
  14236. * Draw a list of unindexed primitives
  14237. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14238. * @param verticesStart defines the index of first vertex to draw
  14239. * @param verticesCount defines the count of vertices to draw
  14240. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14241. */
  14242. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14243. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14244. };
  14245. /**
  14246. * Draw a list of indexed primitives
  14247. * @param fillMode defines the primitive to use
  14248. * @param indexStart defines the starting index
  14249. * @param indexCount defines the number of index to draw
  14250. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14251. */
  14252. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14253. // Apply states
  14254. this.applyStates();
  14255. this._drawCalls.addCount(1, false);
  14256. // Render
  14257. var drawMode = this._drawMode(fillMode);
  14258. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14259. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14260. if (instancesCount) {
  14261. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14262. }
  14263. else {
  14264. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14265. }
  14266. };
  14267. /**
  14268. * Draw a list of unindexed primitives
  14269. * @param fillMode defines the primitive to use
  14270. * @param verticesStart defines the index of first vertex to draw
  14271. * @param verticesCount defines the count of vertices to draw
  14272. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14273. */
  14274. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14275. // Apply states
  14276. this.applyStates();
  14277. this._drawCalls.addCount(1, false);
  14278. var drawMode = this._drawMode(fillMode);
  14279. if (instancesCount) {
  14280. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14281. }
  14282. else {
  14283. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14284. }
  14285. };
  14286. Engine.prototype._drawMode = function (fillMode) {
  14287. switch (fillMode) {
  14288. // Triangle views
  14289. case BABYLON.Material.TriangleFillMode:
  14290. return this._gl.TRIANGLES;
  14291. case BABYLON.Material.PointFillMode:
  14292. return this._gl.POINTS;
  14293. case BABYLON.Material.WireFrameFillMode:
  14294. return this._gl.LINES;
  14295. // Draw modes
  14296. case BABYLON.Material.PointListDrawMode:
  14297. return this._gl.POINTS;
  14298. case BABYLON.Material.LineListDrawMode:
  14299. return this._gl.LINES;
  14300. case BABYLON.Material.LineLoopDrawMode:
  14301. return this._gl.LINE_LOOP;
  14302. case BABYLON.Material.LineStripDrawMode:
  14303. return this._gl.LINE_STRIP;
  14304. case BABYLON.Material.TriangleStripDrawMode:
  14305. return this._gl.TRIANGLE_STRIP;
  14306. case BABYLON.Material.TriangleFanDrawMode:
  14307. return this._gl.TRIANGLE_FAN;
  14308. default:
  14309. return this._gl.TRIANGLES;
  14310. }
  14311. };
  14312. // Shaders
  14313. /** @hidden */
  14314. Engine.prototype._releaseEffect = function (effect) {
  14315. if (this._compiledEffects[effect._key]) {
  14316. delete this._compiledEffects[effect._key];
  14317. this._deleteProgram(effect.getProgram());
  14318. }
  14319. };
  14320. /** @hidden */
  14321. Engine.prototype._deleteProgram = function (program) {
  14322. if (program) {
  14323. program.__SPECTOR_rebuildProgram = null;
  14324. if (program.transformFeedback) {
  14325. this.deleteTransformFeedback(program.transformFeedback);
  14326. program.transformFeedback = null;
  14327. }
  14328. this._gl.deleteProgram(program);
  14329. }
  14330. };
  14331. /**
  14332. * Create a new effect (used to store vertex/fragment shaders)
  14333. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14334. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14335. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14336. * @param samplers defines an array of string used to represent textures
  14337. * @param defines defines the string containing the defines to use to compile the shaders
  14338. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14339. * @param onCompiled defines a function to call when the effect creation is successful
  14340. * @param onError defines a function to call when the effect creation has failed
  14341. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14342. * @returns the new Effect
  14343. */
  14344. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14345. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14346. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14347. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14348. if (this._compiledEffects[name]) {
  14349. var compiledEffect = this._compiledEffects[name];
  14350. if (onCompiled && compiledEffect.isReady()) {
  14351. onCompiled(compiledEffect);
  14352. }
  14353. return compiledEffect;
  14354. }
  14355. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14356. effect._key = name;
  14357. this._compiledEffects[name] = effect;
  14358. return effect;
  14359. };
  14360. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14361. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14362. };
  14363. ;
  14364. Engine.prototype._compileRawShader = function (source, type) {
  14365. var gl = this._gl;
  14366. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14367. gl.shaderSource(shader, source);
  14368. gl.compileShader(shader);
  14369. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14370. var log = gl.getShaderInfoLog(shader);
  14371. if (log) {
  14372. throw new Error(log);
  14373. }
  14374. }
  14375. if (!shader) {
  14376. throw new Error("Something went wrong while compile the shader.");
  14377. }
  14378. return shader;
  14379. };
  14380. ;
  14381. /**
  14382. * Directly creates a webGL program
  14383. * @param vertexCode defines the vertex shader code to use
  14384. * @param fragmentCode defines the fragment shader code to use
  14385. * @param context defines the webGL context to use (if not set, the current one will be used)
  14386. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14387. * @returns the new webGL program
  14388. */
  14389. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14390. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14391. context = context || this._gl;
  14392. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14393. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14394. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14395. };
  14396. /**
  14397. * Creates a webGL program
  14398. * @param vertexCode defines the vertex shader code to use
  14399. * @param fragmentCode defines the fragment shader code to use
  14400. * @param defines defines the string containing the defines to use to compile the shaders
  14401. * @param context defines the webGL context to use (if not set, the current one will be used)
  14402. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14403. * @returns the new webGL program
  14404. */
  14405. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14406. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14407. context = context || this._gl;
  14408. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14409. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14410. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14411. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14412. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14413. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14414. return program;
  14415. };
  14416. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14417. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14418. var shaderProgram = context.createProgram();
  14419. if (!shaderProgram) {
  14420. throw new Error("Unable to create program");
  14421. }
  14422. context.attachShader(shaderProgram, vertexShader);
  14423. context.attachShader(shaderProgram, fragmentShader);
  14424. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14425. var transformFeedback = this.createTransformFeedback();
  14426. this.bindTransformFeedback(transformFeedback);
  14427. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14428. shaderProgram.transformFeedback = transformFeedback;
  14429. }
  14430. context.linkProgram(shaderProgram);
  14431. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14432. this.bindTransformFeedback(null);
  14433. }
  14434. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14435. if (!linked) {
  14436. var error = context.getProgramInfoLog(shaderProgram);
  14437. if (error) {
  14438. throw new Error(error);
  14439. }
  14440. }
  14441. if (this.validateShaderPrograms) {
  14442. context.validateProgram(shaderProgram);
  14443. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14444. if (!validated) {
  14445. var error = context.getProgramInfoLog(shaderProgram);
  14446. if (error) {
  14447. throw new Error(error);
  14448. }
  14449. }
  14450. }
  14451. context.deleteShader(vertexShader);
  14452. context.deleteShader(fragmentShader);
  14453. return shaderProgram;
  14454. };
  14455. /**
  14456. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14457. * @param shaderProgram defines the webGL program to use
  14458. * @param uniformsNames defines the list of uniform names
  14459. * @returns an array of webGL uniform locations
  14460. */
  14461. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14462. var results = new Array();
  14463. for (var index = 0; index < uniformsNames.length; index++) {
  14464. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14465. }
  14466. return results;
  14467. };
  14468. /**
  14469. * Gets the lsit of active attributes for a given webGL program
  14470. * @param shaderProgram defines the webGL program to use
  14471. * @param attributesNames defines the list of attribute names to get
  14472. * @returns an array of indices indicating the offset of each attribute
  14473. */
  14474. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14475. var results = [];
  14476. for (var index = 0; index < attributesNames.length; index++) {
  14477. try {
  14478. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14479. }
  14480. catch (e) {
  14481. results.push(-1);
  14482. }
  14483. }
  14484. return results;
  14485. };
  14486. /**
  14487. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14488. * @param effect defines the effect to activate
  14489. */
  14490. Engine.prototype.enableEffect = function (effect) {
  14491. if (!effect || effect === this._currentEffect) {
  14492. return;
  14493. }
  14494. // Use program
  14495. this.bindSamplers(effect);
  14496. this._currentEffect = effect;
  14497. if (effect.onBind) {
  14498. effect.onBind(effect);
  14499. }
  14500. if (effect._onBindObservable) {
  14501. effect._onBindObservable.notifyObservers(effect);
  14502. }
  14503. };
  14504. /**
  14505. * Set the value of an uniform to an array of int32
  14506. * @param uniform defines the webGL uniform location where to store the value
  14507. * @param array defines the array of int32 to store
  14508. */
  14509. Engine.prototype.setIntArray = function (uniform, array) {
  14510. if (!uniform)
  14511. return;
  14512. this._gl.uniform1iv(uniform, array);
  14513. };
  14514. /**
  14515. * Set the value of an uniform to an array of int32 (stored as vec2)
  14516. * @param uniform defines the webGL uniform location where to store the value
  14517. * @param array defines the array of int32 to store
  14518. */
  14519. Engine.prototype.setIntArray2 = function (uniform, array) {
  14520. if (!uniform || array.length % 2 !== 0)
  14521. return;
  14522. this._gl.uniform2iv(uniform, array);
  14523. };
  14524. /**
  14525. * Set the value of an uniform to an array of int32 (stored as vec3)
  14526. * @param uniform defines the webGL uniform location where to store the value
  14527. * @param array defines the array of int32 to store
  14528. */
  14529. Engine.prototype.setIntArray3 = function (uniform, array) {
  14530. if (!uniform || array.length % 3 !== 0)
  14531. return;
  14532. this._gl.uniform3iv(uniform, array);
  14533. };
  14534. /**
  14535. * Set the value of an uniform to an array of int32 (stored as vec4)
  14536. * @param uniform defines the webGL uniform location where to store the value
  14537. * @param array defines the array of int32 to store
  14538. */
  14539. Engine.prototype.setIntArray4 = function (uniform, array) {
  14540. if (!uniform || array.length % 4 !== 0)
  14541. return;
  14542. this._gl.uniform4iv(uniform, array);
  14543. };
  14544. /**
  14545. * Set the value of an uniform to an array of float32
  14546. * @param uniform defines the webGL uniform location where to store the value
  14547. * @param array defines the array of float32 to store
  14548. */
  14549. Engine.prototype.setFloatArray = function (uniform, array) {
  14550. if (!uniform)
  14551. return;
  14552. this._gl.uniform1fv(uniform, array);
  14553. };
  14554. /**
  14555. * Set the value of an uniform to an array of float32 (stored as vec2)
  14556. * @param uniform defines the webGL uniform location where to store the value
  14557. * @param array defines the array of float32 to store
  14558. */
  14559. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14560. if (!uniform || array.length % 2 !== 0)
  14561. return;
  14562. this._gl.uniform2fv(uniform, array);
  14563. };
  14564. /**
  14565. * Set the value of an uniform to an array of float32 (stored as vec3)
  14566. * @param uniform defines the webGL uniform location where to store the value
  14567. * @param array defines the array of float32 to store
  14568. */
  14569. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14570. if (!uniform || array.length % 3 !== 0)
  14571. return;
  14572. this._gl.uniform3fv(uniform, array);
  14573. };
  14574. /**
  14575. * Set the value of an uniform to an array of float32 (stored as vec4)
  14576. * @param uniform defines the webGL uniform location where to store the value
  14577. * @param array defines the array of float32 to store
  14578. */
  14579. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14580. if (!uniform || array.length % 4 !== 0)
  14581. return;
  14582. this._gl.uniform4fv(uniform, array);
  14583. };
  14584. /**
  14585. * Set the value of an uniform to an array of number
  14586. * @param uniform defines the webGL uniform location where to store the value
  14587. * @param array defines the array of number to store
  14588. */
  14589. Engine.prototype.setArray = function (uniform, array) {
  14590. if (!uniform)
  14591. return;
  14592. this._gl.uniform1fv(uniform, array);
  14593. };
  14594. /**
  14595. * Set the value of an uniform to an array of number (stored as vec2)
  14596. * @param uniform defines the webGL uniform location where to store the value
  14597. * @param array defines the array of number to store
  14598. */
  14599. Engine.prototype.setArray2 = function (uniform, array) {
  14600. if (!uniform || array.length % 2 !== 0)
  14601. return;
  14602. this._gl.uniform2fv(uniform, array);
  14603. };
  14604. /**
  14605. * Set the value of an uniform to an array of number (stored as vec3)
  14606. * @param uniform defines the webGL uniform location where to store the value
  14607. * @param array defines the array of number to store
  14608. */
  14609. Engine.prototype.setArray3 = function (uniform, array) {
  14610. if (!uniform || array.length % 3 !== 0)
  14611. return;
  14612. this._gl.uniform3fv(uniform, array);
  14613. };
  14614. /**
  14615. * Set the value of an uniform to an array of number (stored as vec4)
  14616. * @param uniform defines the webGL uniform location where to store the value
  14617. * @param array defines the array of number to store
  14618. */
  14619. Engine.prototype.setArray4 = function (uniform, array) {
  14620. if (!uniform || array.length % 4 !== 0)
  14621. return;
  14622. this._gl.uniform4fv(uniform, array);
  14623. };
  14624. /**
  14625. * Set the value of an uniform to an array of float32 (stored as matrices)
  14626. * @param uniform defines the webGL uniform location where to store the value
  14627. * @param matrices defines the array of float32 to store
  14628. */
  14629. Engine.prototype.setMatrices = function (uniform, matrices) {
  14630. if (!uniform)
  14631. return;
  14632. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14633. };
  14634. /**
  14635. * Set the value of an uniform to a matrix
  14636. * @param uniform defines the webGL uniform location where to store the value
  14637. * @param matrix defines the matrix to store
  14638. */
  14639. Engine.prototype.setMatrix = function (uniform, matrix) {
  14640. if (!uniform)
  14641. return;
  14642. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14643. };
  14644. /**
  14645. * Set the value of an uniform to a matrix (3x3)
  14646. * @param uniform defines the webGL uniform location where to store the value
  14647. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14648. */
  14649. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14650. if (!uniform)
  14651. return;
  14652. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14653. };
  14654. /**
  14655. * Set the value of an uniform to a matrix (2x2)
  14656. * @param uniform defines the webGL uniform location where to store the value
  14657. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14658. */
  14659. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14660. if (!uniform)
  14661. return;
  14662. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14663. };
  14664. /**
  14665. * Set the value of an uniform to a number (int)
  14666. * @param uniform defines the webGL uniform location where to store the value
  14667. * @param value defines the int number to store
  14668. */
  14669. Engine.prototype.setInt = function (uniform, value) {
  14670. if (!uniform)
  14671. return;
  14672. this._gl.uniform1i(uniform, value);
  14673. };
  14674. /**
  14675. * Set the value of an uniform to a number (float)
  14676. * @param uniform defines the webGL uniform location where to store the value
  14677. * @param value defines the float number to store
  14678. */
  14679. Engine.prototype.setFloat = function (uniform, value) {
  14680. if (!uniform)
  14681. return;
  14682. this._gl.uniform1f(uniform, value);
  14683. };
  14684. /**
  14685. * Set the value of an uniform to a vec2
  14686. * @param uniform defines the webGL uniform location where to store the value
  14687. * @param x defines the 1st component of the value
  14688. * @param y defines the 2nd component of the value
  14689. */
  14690. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14691. if (!uniform)
  14692. return;
  14693. this._gl.uniform2f(uniform, x, y);
  14694. };
  14695. /**
  14696. * Set the value of an uniform to a vec3
  14697. * @param uniform defines the webGL uniform location where to store the value
  14698. * @param x defines the 1st component of the value
  14699. * @param y defines the 2nd component of the value
  14700. * @param z defines the 3rd component of the value
  14701. */
  14702. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14703. if (!uniform)
  14704. return;
  14705. this._gl.uniform3f(uniform, x, y, z);
  14706. };
  14707. /**
  14708. * Set the value of an uniform to a boolean
  14709. * @param uniform defines the webGL uniform location where to store the value
  14710. * @param bool defines the boolean to store
  14711. */
  14712. Engine.prototype.setBool = function (uniform, bool) {
  14713. if (!uniform)
  14714. return;
  14715. this._gl.uniform1i(uniform, bool);
  14716. };
  14717. /**
  14718. * Set the value of an uniform to a vec4
  14719. * @param uniform defines the webGL uniform location where to store the value
  14720. * @param x defines the 1st component of the value
  14721. * @param y defines the 2nd component of the value
  14722. * @param z defines the 3rd component of the value
  14723. * @param w defines the 4th component of the value
  14724. */
  14725. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14726. if (!uniform)
  14727. return;
  14728. this._gl.uniform4f(uniform, x, y, z, w);
  14729. };
  14730. /**
  14731. * Set the value of an uniform to a Color3
  14732. * @param uniform defines the webGL uniform location where to store the value
  14733. * @param color3 defines the color to store
  14734. */
  14735. Engine.prototype.setColor3 = function (uniform, color3) {
  14736. if (!uniform)
  14737. return;
  14738. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14739. };
  14740. /**
  14741. * Set the value of an uniform to a Color3 and an alpha value
  14742. * @param uniform defines the webGL uniform location where to store the value
  14743. * @param color3 defines the color to store
  14744. * @param alpha defines the alpha component to store
  14745. */
  14746. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14747. if (!uniform)
  14748. return;
  14749. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14750. };
  14751. /**
  14752. * Sets a Color4 on a uniform variable
  14753. * @param uniform defines the uniform location
  14754. * @param color4 defines the value to be set
  14755. */
  14756. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14757. if (!uniform)
  14758. return;
  14759. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14760. };
  14761. // States
  14762. /**
  14763. * Set various states to the webGL context
  14764. * @param culling defines backface culling state
  14765. * @param zOffset defines the value to apply to zOffset (0 by default)
  14766. * @param force defines if states must be applied even if cache is up to date
  14767. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14768. */
  14769. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14770. if (zOffset === void 0) { zOffset = 0; }
  14771. if (reverseSide === void 0) { reverseSide = false; }
  14772. // Culling
  14773. if (this._depthCullingState.cull !== culling || force) {
  14774. this._depthCullingState.cull = culling;
  14775. }
  14776. // Cull face
  14777. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14778. if (this._depthCullingState.cullFace !== cullFace || force) {
  14779. this._depthCullingState.cullFace = cullFace;
  14780. }
  14781. // Z offset
  14782. this.setZOffset(zOffset);
  14783. // Front face
  14784. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14785. if (this._depthCullingState.frontFace !== frontFace || force) {
  14786. this._depthCullingState.frontFace = frontFace;
  14787. }
  14788. };
  14789. /**
  14790. * Set the z offset to apply to current rendering
  14791. * @param value defines the offset to apply
  14792. */
  14793. Engine.prototype.setZOffset = function (value) {
  14794. this._depthCullingState.zOffset = value;
  14795. };
  14796. /**
  14797. * Gets the current value of the zOffset
  14798. * @returns the current zOffset state
  14799. */
  14800. Engine.prototype.getZOffset = function () {
  14801. return this._depthCullingState.zOffset;
  14802. };
  14803. /**
  14804. * Enable or disable depth buffering
  14805. * @param enable defines the state to set
  14806. */
  14807. Engine.prototype.setDepthBuffer = function (enable) {
  14808. this._depthCullingState.depthTest = enable;
  14809. };
  14810. /**
  14811. * Gets a boolean indicating if depth writing is enabled
  14812. * @returns the current depth writing state
  14813. */
  14814. Engine.prototype.getDepthWrite = function () {
  14815. return this._depthCullingState.depthMask;
  14816. };
  14817. /**
  14818. * Enable or disable depth writing
  14819. * @param enable defines the state to set
  14820. */
  14821. Engine.prototype.setDepthWrite = function (enable) {
  14822. this._depthCullingState.depthMask = enable;
  14823. };
  14824. /**
  14825. * Enable or disable color writing
  14826. * @param enable defines the state to set
  14827. */
  14828. Engine.prototype.setColorWrite = function (enable) {
  14829. this._gl.colorMask(enable, enable, enable, enable);
  14830. this._colorWrite = enable;
  14831. };
  14832. /**
  14833. * Gets a boolean indicating if color writing is enabled
  14834. * @returns the current color writing state
  14835. */
  14836. Engine.prototype.getColorWrite = function () {
  14837. return this._colorWrite;
  14838. };
  14839. /**
  14840. * Sets alpha constants used by some alpha blending modes
  14841. * @param r defines the red component
  14842. * @param g defines the green component
  14843. * @param b defines the blue component
  14844. * @param a defines the alpha component
  14845. */
  14846. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14847. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14848. };
  14849. /**
  14850. * Sets the current alpha mode
  14851. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14852. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14853. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14854. */
  14855. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14856. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14857. if (this._alphaMode === mode) {
  14858. return;
  14859. }
  14860. switch (mode) {
  14861. case Engine.ALPHA_DISABLE:
  14862. this._alphaState.alphaBlend = false;
  14863. break;
  14864. case Engine.ALPHA_PREMULTIPLIED:
  14865. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14866. this._alphaState.alphaBlend = true;
  14867. break;
  14868. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14869. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14870. this._alphaState.alphaBlend = true;
  14871. break;
  14872. case Engine.ALPHA_COMBINE:
  14873. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14874. this._alphaState.alphaBlend = true;
  14875. break;
  14876. case Engine.ALPHA_ONEONE:
  14877. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14878. this._alphaState.alphaBlend = true;
  14879. break;
  14880. case Engine.ALPHA_ADD:
  14881. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14882. this._alphaState.alphaBlend = true;
  14883. break;
  14884. case Engine.ALPHA_SUBTRACT:
  14885. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14886. this._alphaState.alphaBlend = true;
  14887. break;
  14888. case Engine.ALPHA_MULTIPLY:
  14889. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14890. this._alphaState.alphaBlend = true;
  14891. break;
  14892. case Engine.ALPHA_MAXIMIZED:
  14893. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14894. this._alphaState.alphaBlend = true;
  14895. break;
  14896. case Engine.ALPHA_INTERPOLATE:
  14897. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14898. this._alphaState.alphaBlend = true;
  14899. break;
  14900. case Engine.ALPHA_SCREENMODE:
  14901. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14902. this._alphaState.alphaBlend = true;
  14903. break;
  14904. }
  14905. if (!noDepthWriteChange) {
  14906. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14907. }
  14908. this._alphaMode = mode;
  14909. };
  14910. /**
  14911. * Gets the current alpha mode
  14912. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14913. * @returns the current alpha mode
  14914. */
  14915. Engine.prototype.getAlphaMode = function () {
  14916. return this._alphaMode;
  14917. };
  14918. // Textures
  14919. /**
  14920. * Clears the list of texture accessible through engine.
  14921. * This can help preventing texture load conflict due to name collision.
  14922. */
  14923. Engine.prototype.clearInternalTexturesCache = function () {
  14924. this._internalTexturesCache = [];
  14925. };
  14926. /**
  14927. * Force the entire cache to be cleared
  14928. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14929. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14930. */
  14931. Engine.prototype.wipeCaches = function (bruteForce) {
  14932. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14933. return;
  14934. }
  14935. this._currentEffect = null;
  14936. this._viewportCached.x = 0;
  14937. this._viewportCached.y = 0;
  14938. this._viewportCached.z = 0;
  14939. this._viewportCached.w = 0;
  14940. if (bruteForce) {
  14941. this.resetTextureCache();
  14942. this._currentProgram = null;
  14943. this._stencilState.reset();
  14944. this._depthCullingState.reset();
  14945. this.setDepthFunctionToLessOrEqual();
  14946. this._alphaState.reset();
  14947. this._unpackFlipYCached = null;
  14948. }
  14949. this._resetVertexBufferBinding();
  14950. this._cachedIndexBuffer = null;
  14951. this._cachedEffectForVertexBuffers = null;
  14952. this._unbindVertexArrayObject();
  14953. this.bindIndexBuffer(null);
  14954. };
  14955. /**
  14956. * Set the compressed texture format to use, based on the formats you have, and the formats
  14957. * supported by the hardware / browser.
  14958. *
  14959. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14960. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14961. * to API arguments needed to compressed textures. This puts the burden on the container
  14962. * generator to house the arcane code for determining these for current & future formats.
  14963. *
  14964. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14965. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14966. *
  14967. * Note: The result of this call is not taken into account when a texture is base64.
  14968. *
  14969. * @param formatsAvailable defines the list of those format families you have created
  14970. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14971. *
  14972. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14973. * @returns The extension selected.
  14974. */
  14975. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14976. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14977. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14978. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14979. return this._textureFormatInUse = this._texturesSupported[i];
  14980. }
  14981. }
  14982. }
  14983. // actively set format to nothing, to allow this to be called more than once
  14984. // and possibly fail the 2nd time
  14985. this._textureFormatInUse = null;
  14986. return null;
  14987. };
  14988. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14989. var gl = this._gl;
  14990. var magFilter = gl.NEAREST;
  14991. var minFilter = gl.NEAREST;
  14992. switch (samplingMode) {
  14993. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14994. magFilter = gl.LINEAR;
  14995. if (generateMipMaps) {
  14996. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14997. }
  14998. else {
  14999. minFilter = gl.LINEAR;
  15000. }
  15001. break;
  15002. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15003. magFilter = gl.LINEAR;
  15004. if (generateMipMaps) {
  15005. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15006. }
  15007. else {
  15008. minFilter = gl.LINEAR;
  15009. }
  15010. break;
  15011. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15012. magFilter = gl.NEAREST;
  15013. if (generateMipMaps) {
  15014. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15015. }
  15016. else {
  15017. minFilter = gl.NEAREST;
  15018. }
  15019. break;
  15020. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15021. magFilter = gl.NEAREST;
  15022. if (generateMipMaps) {
  15023. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15024. }
  15025. else {
  15026. minFilter = gl.NEAREST;
  15027. }
  15028. break;
  15029. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15030. magFilter = gl.NEAREST;
  15031. if (generateMipMaps) {
  15032. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15033. }
  15034. else {
  15035. minFilter = gl.LINEAR;
  15036. }
  15037. break;
  15038. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15039. magFilter = gl.NEAREST;
  15040. if (generateMipMaps) {
  15041. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15042. }
  15043. else {
  15044. minFilter = gl.LINEAR;
  15045. }
  15046. break;
  15047. case Engine.TEXTURE_NEAREST_LINEAR:
  15048. magFilter = gl.NEAREST;
  15049. minFilter = gl.LINEAR;
  15050. break;
  15051. case Engine.TEXTURE_NEAREST_NEAREST:
  15052. magFilter = gl.NEAREST;
  15053. minFilter = gl.NEAREST;
  15054. break;
  15055. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15056. magFilter = gl.LINEAR;
  15057. if (generateMipMaps) {
  15058. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15059. }
  15060. else {
  15061. minFilter = gl.NEAREST;
  15062. }
  15063. break;
  15064. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15065. magFilter = gl.LINEAR;
  15066. if (generateMipMaps) {
  15067. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15068. }
  15069. else {
  15070. minFilter = gl.NEAREST;
  15071. }
  15072. break;
  15073. case Engine.TEXTURE_LINEAR_LINEAR:
  15074. magFilter = gl.LINEAR;
  15075. minFilter = gl.LINEAR;
  15076. break;
  15077. case Engine.TEXTURE_LINEAR_NEAREST:
  15078. magFilter = gl.LINEAR;
  15079. minFilter = gl.NEAREST;
  15080. break;
  15081. }
  15082. return {
  15083. min: minFilter,
  15084. mag: magFilter
  15085. };
  15086. };
  15087. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15088. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15089. var img;
  15090. var onload = function () {
  15091. loadedImages[index] = img;
  15092. loadedImages._internalCount++;
  15093. if (scene) {
  15094. scene._removePendingData(img);
  15095. }
  15096. if (loadedImages._internalCount === 6) {
  15097. onfinish(loadedImages);
  15098. }
  15099. };
  15100. var onerror = function (message, exception) {
  15101. if (scene) {
  15102. scene._removePendingData(img);
  15103. }
  15104. if (onErrorCallBack) {
  15105. onErrorCallBack(message, exception);
  15106. }
  15107. };
  15108. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15109. if (scene) {
  15110. scene._addPendingData(img);
  15111. }
  15112. };
  15113. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15114. if (onError === void 0) { onError = null; }
  15115. var loadedImages = [];
  15116. loadedImages._internalCount = 0;
  15117. for (var index = 0; index < 6; index++) {
  15118. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15119. }
  15120. };
  15121. ;
  15122. /** @hidden */
  15123. Engine.prototype._createTexture = function () {
  15124. var texture = this._gl.createTexture();
  15125. if (!texture) {
  15126. throw new Error("Unable to create texture");
  15127. }
  15128. return texture;
  15129. };
  15130. /**
  15131. * Usually called from BABYLON.Texture.ts.
  15132. * Passed information to create a WebGLTexture
  15133. * @param urlArg defines a value which contains one of the following:
  15134. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15135. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15136. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15137. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15138. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15139. * @param scene needed for loading to the correct scene
  15140. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15141. * @param onLoad optional callback to be called upon successful completion
  15142. * @param onError optional callback to be called upon failure
  15143. * @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
  15144. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15145. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15146. * @param forcedExtension defines the extension to use to pick the right loader
  15147. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15148. */
  15149. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15150. var _this = this;
  15151. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15152. if (onLoad === void 0) { onLoad = null; }
  15153. if (onError === void 0) { onError = null; }
  15154. if (buffer === void 0) { buffer = null; }
  15155. if (fallback === void 0) { fallback = null; }
  15156. if (format === void 0) { format = null; }
  15157. if (forcedExtension === void 0) { forcedExtension = null; }
  15158. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15159. var fromData = url.substr(0, 5) === "data:";
  15160. var fromBlob = url.substr(0, 5) === "blob:";
  15161. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15162. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15163. // establish the file extension, if possible
  15164. var lastDot = url.lastIndexOf('.');
  15165. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15166. var loader = null;
  15167. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15168. var availableLoader = _a[_i];
  15169. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15170. loader = availableLoader;
  15171. break;
  15172. }
  15173. }
  15174. if (loader) {
  15175. url = loader.transformUrl(url, this._textureFormatInUse);
  15176. }
  15177. if (scene) {
  15178. scene._addPendingData(texture);
  15179. }
  15180. texture.url = url;
  15181. texture.generateMipMaps = !noMipmap;
  15182. texture.samplingMode = samplingMode;
  15183. texture.invertY = invertY;
  15184. if (!this._doNotHandleContextLost) {
  15185. // Keep a link to the buffer only if we plan to handle context lost
  15186. texture._buffer = buffer;
  15187. }
  15188. var onLoadObserver = null;
  15189. if (onLoad && !fallback) {
  15190. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15191. }
  15192. if (!fallback)
  15193. this._internalTexturesCache.push(texture);
  15194. var onInternalError = function (message, exception) {
  15195. if (scene) {
  15196. scene._removePendingData(texture);
  15197. }
  15198. var customFallback = false;
  15199. if (loader) {
  15200. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15201. if (fallbackUrl) {
  15202. // Add Back
  15203. customFallback = true;
  15204. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15205. }
  15206. }
  15207. if (!customFallback) {
  15208. if (onLoadObserver) {
  15209. texture.onLoadedObservable.remove(onLoadObserver);
  15210. }
  15211. if (BABYLON.Tools.UseFallbackTexture) {
  15212. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15213. }
  15214. }
  15215. if (onError) {
  15216. onError(message || "Unknown error", exception);
  15217. }
  15218. };
  15219. // processing for non-image formats
  15220. if (loader) {
  15221. var callback = function (data) {
  15222. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15223. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15224. done();
  15225. return false;
  15226. }, samplingMode);
  15227. });
  15228. };
  15229. if (!buffer) {
  15230. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15231. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15232. });
  15233. }
  15234. else {
  15235. callback(buffer);
  15236. }
  15237. }
  15238. else {
  15239. var onload = function (img) {
  15240. if (fromBlob && !_this._doNotHandleContextLost) {
  15241. // We need to store the image if we need to rebuild the texture
  15242. // in case of a webgl context lost
  15243. texture._buffer = img;
  15244. }
  15245. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15246. var gl = _this._gl;
  15247. var isPot = (img.width === potWidth && img.height === potHeight);
  15248. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15249. if (isPot) {
  15250. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15251. return false;
  15252. }
  15253. var maxTextureSize = _this._caps.maxTextureSize;
  15254. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15255. _this._prepareWorkingCanvas();
  15256. if (!_this._workingCanvas || !_this._workingContext) {
  15257. return false;
  15258. }
  15259. _this._workingCanvas.width = potWidth;
  15260. _this._workingCanvas.height = potHeight;
  15261. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15262. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15263. texture.width = potWidth;
  15264. texture.height = potHeight;
  15265. return false;
  15266. }
  15267. else {
  15268. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15269. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15270. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15271. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15274. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15275. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15276. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15277. _this._releaseTexture(source_1);
  15278. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15279. continuationCallback();
  15280. });
  15281. }
  15282. return true;
  15283. }, samplingMode);
  15284. };
  15285. if (!fromData || isBase64) {
  15286. if (buffer instanceof HTMLImageElement) {
  15287. onload(buffer);
  15288. }
  15289. else {
  15290. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15291. }
  15292. }
  15293. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15294. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15295. }
  15296. else {
  15297. onload(buffer);
  15298. }
  15299. }
  15300. return texture;
  15301. };
  15302. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15303. var _this = this;
  15304. var rtt = this.createRenderTargetTexture({
  15305. width: destination.width,
  15306. height: destination.height,
  15307. }, {
  15308. generateMipMaps: false,
  15309. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15310. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15311. generateDepthBuffer: false,
  15312. generateStencilBuffer: false
  15313. });
  15314. if (!this._rescalePostProcess) {
  15315. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15316. }
  15317. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15318. _this._rescalePostProcess.onApply = function (effect) {
  15319. effect._bindTexture("textureSampler", source);
  15320. };
  15321. var hostingScene = scene;
  15322. if (!hostingScene) {
  15323. hostingScene = _this.scenes[_this.scenes.length - 1];
  15324. }
  15325. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15326. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15327. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15328. _this.unBindFramebuffer(rtt);
  15329. _this._releaseTexture(rtt);
  15330. if (onComplete) {
  15331. onComplete();
  15332. }
  15333. });
  15334. };
  15335. /**
  15336. * Update a raw texture
  15337. * @param texture defines the texture to update
  15338. * @param data defines the data to store in the texture
  15339. * @param format defines the format of the data
  15340. * @param invertY defines if data must be stored with Y axis inverted
  15341. * @param compression defines the compression used (null by default)
  15342. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15343. */
  15344. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15345. if (compression === void 0) { compression = null; }
  15346. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15347. if (!texture) {
  15348. return;
  15349. }
  15350. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15351. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15352. // babylon's internalFormat but gl's texImage2D format
  15353. var internalFormat = this._getInternalFormat(format);
  15354. var textureType = this._getWebGLTextureType(type);
  15355. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15356. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15357. if (!this._doNotHandleContextLost) {
  15358. texture._bufferView = data;
  15359. texture.format = format;
  15360. texture.type = type;
  15361. texture.invertY = invertY;
  15362. texture._compression = compression;
  15363. }
  15364. if (texture.width % 4 !== 0) {
  15365. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15366. }
  15367. if (compression && data) {
  15368. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15369. }
  15370. else {
  15371. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15372. }
  15373. if (texture.generateMipMaps) {
  15374. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15375. }
  15376. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15377. // this.resetTextureCache();
  15378. texture.isReady = true;
  15379. };
  15380. /**
  15381. * Creates a raw texture
  15382. * @param data defines the data to store in the texture
  15383. * @param width defines the width of the texture
  15384. * @param height defines the height of the texture
  15385. * @param format defines the format of the data
  15386. * @param generateMipMaps defines if the engine should generate the mip levels
  15387. * @param invertY defines if data must be stored with Y axis inverted
  15388. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15389. * @param compression defines the compression used (null by default)
  15390. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15391. * @returns the raw texture inside an InternalTexture
  15392. */
  15393. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15394. if (compression === void 0) { compression = null; }
  15395. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15396. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15397. texture.baseWidth = width;
  15398. texture.baseHeight = height;
  15399. texture.width = width;
  15400. texture.height = height;
  15401. texture.format = format;
  15402. texture.generateMipMaps = generateMipMaps;
  15403. texture.samplingMode = samplingMode;
  15404. texture.invertY = invertY;
  15405. texture._compression = compression;
  15406. texture.type = type;
  15407. if (!this._doNotHandleContextLost) {
  15408. texture._bufferView = data;
  15409. }
  15410. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15411. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15412. // Filters
  15413. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15414. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15415. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15416. if (generateMipMaps) {
  15417. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15418. }
  15419. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15420. this._internalTexturesCache.push(texture);
  15421. return texture;
  15422. };
  15423. /** @hidden */
  15424. Engine.prototype._unpackFlipY = function (value) {
  15425. if (this._unpackFlipYCached !== value) {
  15426. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15427. if (this.enableUnpackFlipYCached) {
  15428. this._unpackFlipYCached = value;
  15429. }
  15430. }
  15431. };
  15432. /** @hidden */
  15433. Engine.prototype._getUnpackAlignement = function () {
  15434. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15435. };
  15436. /**
  15437. * Creates a dynamic texture
  15438. * @param width defines the width of the texture
  15439. * @param height defines the height of the texture
  15440. * @param generateMipMaps defines if the engine should generate the mip levels
  15441. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15442. * @returns the dynamic texture inside an InternalTexture
  15443. */
  15444. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15445. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15446. texture.baseWidth = width;
  15447. texture.baseHeight = height;
  15448. if (generateMipMaps) {
  15449. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15450. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15451. }
  15452. // this.resetTextureCache();
  15453. texture.width = width;
  15454. texture.height = height;
  15455. texture.isReady = false;
  15456. texture.generateMipMaps = generateMipMaps;
  15457. texture.samplingMode = samplingMode;
  15458. this.updateTextureSamplingMode(samplingMode, texture);
  15459. this._internalTexturesCache.push(texture);
  15460. return texture;
  15461. };
  15462. /**
  15463. * Update the sampling mode of a given texture
  15464. * @param samplingMode defines the required sampling mode
  15465. * @param texture defines the texture to update
  15466. */
  15467. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15468. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15469. if (texture.isCube) {
  15470. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15471. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15472. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15473. }
  15474. else if (texture.is3D) {
  15475. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15476. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15477. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15478. }
  15479. else {
  15480. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15481. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15482. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15483. }
  15484. texture.samplingMode = samplingMode;
  15485. };
  15486. /**
  15487. * Update the content of a dynamic texture
  15488. * @param texture defines the texture to update
  15489. * @param canvas defines the canvas containing the source
  15490. * @param invertY defines if data must be stored with Y axis inverted
  15491. * @param premulAlpha defines if alpha is stored as premultiplied
  15492. * @param format defines the format of the data
  15493. */
  15494. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15495. if (premulAlpha === void 0) { premulAlpha = false; }
  15496. if (!texture) {
  15497. return;
  15498. }
  15499. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15500. this._unpackFlipY(invertY);
  15501. if (premulAlpha) {
  15502. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15503. }
  15504. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15505. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15506. if (texture.generateMipMaps) {
  15507. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15508. }
  15509. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15510. if (premulAlpha) {
  15511. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15512. }
  15513. texture.isReady = true;
  15514. };
  15515. /**
  15516. * Update a video texture
  15517. * @param texture defines the texture to update
  15518. * @param video defines the video element to use
  15519. * @param invertY defines if data must be stored with Y axis inverted
  15520. */
  15521. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15522. if (!texture || texture._isDisabled) {
  15523. return;
  15524. }
  15525. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15526. this._unpackFlipY(!invertY); // Video are upside down by default
  15527. try {
  15528. // Testing video texture support
  15529. if (this._videoTextureSupported === undefined) {
  15530. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15531. if (this._gl.getError() !== 0) {
  15532. this._videoTextureSupported = false;
  15533. }
  15534. else {
  15535. this._videoTextureSupported = true;
  15536. }
  15537. }
  15538. // Copy video through the current working canvas if video texture is not supported
  15539. if (!this._videoTextureSupported) {
  15540. if (!texture._workingCanvas) {
  15541. texture._workingCanvas = document.createElement("canvas");
  15542. var context = texture._workingCanvas.getContext("2d");
  15543. if (!context) {
  15544. throw new Error("Unable to get 2d context");
  15545. }
  15546. texture._workingContext = context;
  15547. texture._workingCanvas.width = texture.width;
  15548. texture._workingCanvas.height = texture.height;
  15549. }
  15550. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15551. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15552. }
  15553. else {
  15554. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15555. }
  15556. if (texture.generateMipMaps) {
  15557. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15558. }
  15559. if (!wasPreviouslyBound) {
  15560. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15561. }
  15562. // this.resetTextureCache();
  15563. texture.isReady = true;
  15564. }
  15565. catch (ex) {
  15566. // Something unexpected
  15567. // Let's disable the texture
  15568. texture._isDisabled = true;
  15569. }
  15570. };
  15571. /**
  15572. * Updates a depth texture Comparison Mode and Function.
  15573. * If the comparison Function is equal to 0, the mode will be set to none.
  15574. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15575. * @param texture The texture to set the comparison function for
  15576. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15577. */
  15578. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15579. if (this.webGLVersion === 1) {
  15580. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15581. return;
  15582. }
  15583. var gl = this._gl;
  15584. if (texture.isCube) {
  15585. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15586. if (comparisonFunction === 0) {
  15587. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15589. }
  15590. else {
  15591. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15592. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15593. }
  15594. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15595. }
  15596. else {
  15597. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15598. if (comparisonFunction === 0) {
  15599. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15600. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15601. }
  15602. else {
  15603. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15604. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15605. }
  15606. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15607. }
  15608. texture._comparisonFunction = comparisonFunction;
  15609. };
  15610. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15611. var width = size.width || size;
  15612. var height = size.height || size;
  15613. internalTexture.baseWidth = width;
  15614. internalTexture.baseHeight = height;
  15615. internalTexture.width = width;
  15616. internalTexture.height = height;
  15617. internalTexture.isReady = true;
  15618. internalTexture.samples = 1;
  15619. internalTexture.generateMipMaps = false;
  15620. internalTexture._generateDepthBuffer = true;
  15621. internalTexture._generateStencilBuffer = generateStencil;
  15622. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15623. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15624. internalTexture._comparisonFunction = comparisonFunction;
  15625. var gl = this._gl;
  15626. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15627. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15628. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15629. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15630. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15631. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15632. if (comparisonFunction === 0) {
  15633. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15634. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15635. }
  15636. else {
  15637. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15638. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15639. }
  15640. };
  15641. /**
  15642. * Creates a depth stencil texture.
  15643. * This is only available in WebGL 2 or with the depth texture extension available.
  15644. * @param size The size of face edge in the texture.
  15645. * @param options The options defining the texture.
  15646. * @returns The texture
  15647. */
  15648. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15649. if (options.isCube) {
  15650. var width = size.width || size;
  15651. return this._createDepthStencilCubeTexture(width, options);
  15652. }
  15653. else {
  15654. return this._createDepthStencilTexture(size, options);
  15655. }
  15656. };
  15657. /**
  15658. * Creates a depth stencil texture.
  15659. * This is only available in WebGL 2 or with the depth texture extension available.
  15660. * @param size The size of face edge in the texture.
  15661. * @param options The options defining the texture.
  15662. * @returns The texture
  15663. */
  15664. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15665. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15666. if (!this._caps.depthTextureExtension) {
  15667. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15668. return internalTexture;
  15669. }
  15670. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15671. var gl = this._gl;
  15672. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15673. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15674. if (this.webGLVersion > 1) {
  15675. if (internalOptions.generateStencil) {
  15676. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15677. }
  15678. else {
  15679. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15680. }
  15681. }
  15682. else {
  15683. if (internalOptions.generateStencil) {
  15684. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15685. }
  15686. else {
  15687. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15688. }
  15689. }
  15690. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15691. return internalTexture;
  15692. };
  15693. /**
  15694. * Creates a depth stencil cube texture.
  15695. * This is only available in WebGL 2.
  15696. * @param size The size of face edge in the cube texture.
  15697. * @param options The options defining the cube texture.
  15698. * @returns The cube texture
  15699. */
  15700. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15701. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15702. internalTexture.isCube = true;
  15703. if (this.webGLVersion === 1) {
  15704. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15705. return internalTexture;
  15706. }
  15707. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15708. var gl = this._gl;
  15709. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15710. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15711. // Create the depth/stencil buffer
  15712. for (var face = 0; face < 6; face++) {
  15713. if (internalOptions.generateStencil) {
  15714. 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);
  15715. }
  15716. else {
  15717. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15718. }
  15719. }
  15720. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15721. return internalTexture;
  15722. };
  15723. /**
  15724. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15725. * @param renderTarget The render target to set the frame buffer for
  15726. */
  15727. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15728. // Create the framebuffer
  15729. var internalTexture = renderTarget.getInternalTexture();
  15730. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15731. return;
  15732. }
  15733. var gl = this._gl;
  15734. var depthStencilTexture = renderTarget.depthStencilTexture;
  15735. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15736. if (depthStencilTexture.isCube) {
  15737. if (depthStencilTexture._generateStencilBuffer) {
  15738. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15739. }
  15740. else {
  15741. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15742. }
  15743. }
  15744. else {
  15745. if (depthStencilTexture._generateStencilBuffer) {
  15746. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15747. }
  15748. else {
  15749. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15750. }
  15751. }
  15752. this.bindUnboundFramebuffer(null);
  15753. };
  15754. /**
  15755. * Creates a new render target texture
  15756. * @param size defines the size of the texture
  15757. * @param options defines the options used to create the texture
  15758. * @returns a new render target texture stored in an InternalTexture
  15759. */
  15760. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15761. var fullOptions = new RenderTargetCreationOptions();
  15762. if (options !== undefined && typeof options === "object") {
  15763. fullOptions.generateMipMaps = options.generateMipMaps;
  15764. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15765. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15766. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15767. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15768. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15769. }
  15770. else {
  15771. fullOptions.generateMipMaps = options;
  15772. fullOptions.generateDepthBuffer = true;
  15773. fullOptions.generateStencilBuffer = false;
  15774. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15775. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15776. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15777. }
  15778. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15779. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15780. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15781. }
  15782. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15783. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15784. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15785. }
  15786. var gl = this._gl;
  15787. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15788. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15789. var width = size.width || size;
  15790. var height = size.height || size;
  15791. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15792. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15793. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15794. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15795. }
  15796. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15797. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15798. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15800. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15801. // Create the framebuffer
  15802. var currentFrameBuffer = this._currentFramebuffer;
  15803. var framebuffer = gl.createFramebuffer();
  15804. this.bindUnboundFramebuffer(framebuffer);
  15805. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15806. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15807. if (fullOptions.generateMipMaps) {
  15808. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15809. }
  15810. // Unbind
  15811. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15812. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15813. this.bindUnboundFramebuffer(currentFrameBuffer);
  15814. texture._framebuffer = framebuffer;
  15815. texture.baseWidth = width;
  15816. texture.baseHeight = height;
  15817. texture.width = width;
  15818. texture.height = height;
  15819. texture.isReady = true;
  15820. texture.samples = 1;
  15821. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15822. texture.samplingMode = fullOptions.samplingMode;
  15823. texture.type = fullOptions.type;
  15824. texture.format = fullOptions.format;
  15825. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15826. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15827. // this.resetTextureCache();
  15828. this._internalTexturesCache.push(texture);
  15829. return texture;
  15830. };
  15831. /**
  15832. * Create a multi render target texture
  15833. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15834. * @param size defines the size of the texture
  15835. * @param options defines the creation options
  15836. * @returns the cube texture as an InternalTexture
  15837. */
  15838. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15839. var generateMipMaps = false;
  15840. var generateDepthBuffer = true;
  15841. var generateStencilBuffer = false;
  15842. var generateDepthTexture = false;
  15843. var textureCount = 1;
  15844. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15845. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15846. var types = new Array();
  15847. var samplingModes = new Array();
  15848. if (options !== undefined) {
  15849. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15850. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15851. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15852. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15853. textureCount = options.textureCount || 1;
  15854. if (options.types) {
  15855. types = options.types;
  15856. }
  15857. if (options.samplingModes) {
  15858. samplingModes = options.samplingModes;
  15859. }
  15860. }
  15861. var gl = this._gl;
  15862. // Create the framebuffer
  15863. var framebuffer = gl.createFramebuffer();
  15864. this.bindUnboundFramebuffer(framebuffer);
  15865. var width = size.width || size;
  15866. var height = size.height || size;
  15867. var textures = [];
  15868. var attachments = [];
  15869. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15870. for (var i = 0; i < textureCount; i++) {
  15871. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15872. var type = types[i] || defaultType;
  15873. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15874. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15875. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15876. }
  15877. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15878. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15879. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15880. }
  15881. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15882. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15883. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15884. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15885. }
  15886. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15887. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15888. textures.push(texture);
  15889. attachments.push(attachment);
  15890. gl.activeTexture(gl["TEXTURE" + i]);
  15891. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15896. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15897. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15898. if (generateMipMaps) {
  15899. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15900. }
  15901. // Unbind
  15902. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15903. texture._framebuffer = framebuffer;
  15904. texture._depthStencilBuffer = depthStencilBuffer;
  15905. texture.baseWidth = width;
  15906. texture.baseHeight = height;
  15907. texture.width = width;
  15908. texture.height = height;
  15909. texture.isReady = true;
  15910. texture.samples = 1;
  15911. texture.generateMipMaps = generateMipMaps;
  15912. texture.samplingMode = samplingMode;
  15913. texture.type = type;
  15914. texture._generateDepthBuffer = generateDepthBuffer;
  15915. texture._generateStencilBuffer = generateStencilBuffer;
  15916. texture._attachments = attachments;
  15917. this._internalTexturesCache.push(texture);
  15918. }
  15919. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15920. // Depth texture
  15921. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15922. gl.activeTexture(gl.TEXTURE0);
  15923. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15924. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15925. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15926. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15927. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15928. 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);
  15929. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15930. depthTexture._framebuffer = framebuffer;
  15931. depthTexture.baseWidth = width;
  15932. depthTexture.baseHeight = height;
  15933. depthTexture.width = width;
  15934. depthTexture.height = height;
  15935. depthTexture.isReady = true;
  15936. depthTexture.samples = 1;
  15937. depthTexture.generateMipMaps = generateMipMaps;
  15938. depthTexture.samplingMode = gl.NEAREST;
  15939. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15940. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15941. textures.push(depthTexture);
  15942. this._internalTexturesCache.push(depthTexture);
  15943. }
  15944. gl.drawBuffers(attachments);
  15945. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15946. this.bindUnboundFramebuffer(null);
  15947. this.resetTextureCache();
  15948. return textures;
  15949. };
  15950. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15951. if (samples === void 0) { samples = 1; }
  15952. var depthStencilBuffer = null;
  15953. var gl = this._gl;
  15954. // Create the depth/stencil buffer
  15955. if (generateStencilBuffer) {
  15956. depthStencilBuffer = gl.createRenderbuffer();
  15957. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15958. if (samples > 1) {
  15959. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15960. }
  15961. else {
  15962. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15963. }
  15964. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15965. }
  15966. else if (generateDepthBuffer) {
  15967. depthStencilBuffer = gl.createRenderbuffer();
  15968. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15969. if (samples > 1) {
  15970. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15971. }
  15972. else {
  15973. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15974. }
  15975. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15976. }
  15977. return depthStencilBuffer;
  15978. };
  15979. /**
  15980. * Updates the sample count of a render target texture
  15981. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15982. * @param texture defines the texture to update
  15983. * @param samples defines the sample count to set
  15984. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15985. */
  15986. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15987. if (this.webGLVersion < 2 || !texture) {
  15988. return 1;
  15989. }
  15990. if (texture.samples === samples) {
  15991. return samples;
  15992. }
  15993. var gl = this._gl;
  15994. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15995. // Dispose previous render buffers
  15996. if (texture._depthStencilBuffer) {
  15997. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15998. texture._depthStencilBuffer = null;
  15999. }
  16000. if (texture._MSAAFramebuffer) {
  16001. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16002. texture._MSAAFramebuffer = null;
  16003. }
  16004. if (texture._MSAARenderBuffer) {
  16005. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16006. texture._MSAARenderBuffer = null;
  16007. }
  16008. if (samples > 1) {
  16009. var framebuffer = gl.createFramebuffer();
  16010. if (!framebuffer) {
  16011. throw new Error("Unable to create multi sampled framebuffer");
  16012. }
  16013. texture._MSAAFramebuffer = framebuffer;
  16014. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16015. var colorRenderbuffer = gl.createRenderbuffer();
  16016. if (!colorRenderbuffer) {
  16017. throw new Error("Unable to create multi sampled framebuffer");
  16018. }
  16019. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16020. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16021. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16022. texture._MSAARenderBuffer = colorRenderbuffer;
  16023. }
  16024. else {
  16025. this.bindUnboundFramebuffer(texture._framebuffer);
  16026. }
  16027. texture.samples = samples;
  16028. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16029. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16030. this.bindUnboundFramebuffer(null);
  16031. return samples;
  16032. };
  16033. /**
  16034. * Update the sample count for a given multiple render target texture
  16035. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16036. * @param textures defines the textures to update
  16037. * @param samples defines the sample count to set
  16038. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16039. */
  16040. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16041. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16042. return 1;
  16043. }
  16044. if (textures[0].samples === samples) {
  16045. return samples;
  16046. }
  16047. var gl = this._gl;
  16048. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16049. // Dispose previous render buffers
  16050. if (textures[0]._depthStencilBuffer) {
  16051. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16052. textures[0]._depthStencilBuffer = null;
  16053. }
  16054. if (textures[0]._MSAAFramebuffer) {
  16055. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16056. textures[0]._MSAAFramebuffer = null;
  16057. }
  16058. for (var i = 0; i < textures.length; i++) {
  16059. if (textures[i]._MSAARenderBuffer) {
  16060. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16061. textures[i]._MSAARenderBuffer = null;
  16062. }
  16063. }
  16064. if (samples > 1) {
  16065. var framebuffer = gl.createFramebuffer();
  16066. if (!framebuffer) {
  16067. throw new Error("Unable to create multi sampled framebuffer");
  16068. }
  16069. this.bindUnboundFramebuffer(framebuffer);
  16070. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16071. var attachments = [];
  16072. for (var i = 0; i < textures.length; i++) {
  16073. var texture = textures[i];
  16074. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16075. var colorRenderbuffer = gl.createRenderbuffer();
  16076. if (!colorRenderbuffer) {
  16077. throw new Error("Unable to create multi sampled framebuffer");
  16078. }
  16079. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16080. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16081. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16082. texture._MSAAFramebuffer = framebuffer;
  16083. texture._MSAARenderBuffer = colorRenderbuffer;
  16084. texture.samples = samples;
  16085. texture._depthStencilBuffer = depthStencilBuffer;
  16086. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16087. attachments.push(attachment);
  16088. }
  16089. gl.drawBuffers(attachments);
  16090. }
  16091. else {
  16092. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16093. }
  16094. this.bindUnboundFramebuffer(null);
  16095. return samples;
  16096. };
  16097. /** @hidden */
  16098. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16099. if (faceIndex === void 0) { faceIndex = 0; }
  16100. if (lod === void 0) { lod = 0; }
  16101. var gl = this._gl;
  16102. var target = gl.TEXTURE_2D;
  16103. if (texture.isCube) {
  16104. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16105. }
  16106. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16107. };
  16108. /** @hidden */
  16109. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16110. if (faceIndex === void 0) { faceIndex = 0; }
  16111. if (lod === void 0) { lod = 0; }
  16112. var gl = this._gl;
  16113. var textureType = this._getWebGLTextureType(texture.type);
  16114. var format = this._getInternalFormat(texture.format);
  16115. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16116. this._unpackFlipY(texture.invertY);
  16117. var target = gl.TEXTURE_2D;
  16118. if (texture.isCube) {
  16119. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16120. }
  16121. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16122. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16123. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16124. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16125. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16126. };
  16127. /** @hidden */
  16128. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16129. if (faceIndex === void 0) { faceIndex = 0; }
  16130. if (lod === void 0) { lod = 0; }
  16131. var gl = this._gl;
  16132. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16133. this._bindTextureDirectly(bindTarget, texture, true);
  16134. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16135. this._bindTextureDirectly(bindTarget, null, true);
  16136. };
  16137. /** @hidden */
  16138. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16139. if (faceIndex === void 0) { faceIndex = 0; }
  16140. if (lod === void 0) { lod = 0; }
  16141. var gl = this._gl;
  16142. var textureType = this._getWebGLTextureType(texture.type);
  16143. var format = this._getInternalFormat(texture.format);
  16144. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16145. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16146. this._bindTextureDirectly(bindTarget, texture, true);
  16147. this._unpackFlipY(texture.invertY);
  16148. var target = gl.TEXTURE_2D;
  16149. if (texture.isCube) {
  16150. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16151. }
  16152. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16153. this._bindTextureDirectly(bindTarget, null, true);
  16154. };
  16155. /**
  16156. * Creates a new render target cube texture
  16157. * @param size defines the size of the texture
  16158. * @param options defines the options used to create the texture
  16159. * @returns a new render target cube texture stored in an InternalTexture
  16160. */
  16161. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16162. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16163. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16164. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16165. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16166. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16167. }
  16168. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16169. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16170. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16171. }
  16172. var gl = this._gl;
  16173. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16174. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16175. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16176. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16177. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16178. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16179. }
  16180. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16181. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16182. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16183. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16184. for (var face = 0; face < 6; face++) {
  16185. 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);
  16186. }
  16187. // Create the framebuffer
  16188. var framebuffer = gl.createFramebuffer();
  16189. this.bindUnboundFramebuffer(framebuffer);
  16190. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16191. // MipMaps
  16192. if (fullOptions.generateMipMaps) {
  16193. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16194. }
  16195. // Unbind
  16196. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16197. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16198. this.bindUnboundFramebuffer(null);
  16199. texture._framebuffer = framebuffer;
  16200. texture.width = size;
  16201. texture.height = size;
  16202. texture.isReady = true;
  16203. texture.isCube = true;
  16204. texture.samples = 1;
  16205. texture.generateMipMaps = fullOptions.generateMipMaps;
  16206. texture.samplingMode = fullOptions.samplingMode;
  16207. texture.type = fullOptions.type;
  16208. texture.format = fullOptions.format;
  16209. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16210. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16211. this._internalTexturesCache.push(texture);
  16212. return texture;
  16213. };
  16214. /**
  16215. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16216. * @param rootUrl defines the url where the file to load is located
  16217. * @param scene defines the current scene
  16218. * @param lodScale defines scale to apply to the mip map selection
  16219. * @param lodOffset defines offset to apply to the mip map selection
  16220. * @param onLoad defines an optional callback raised when the texture is loaded
  16221. * @param onError defines an optional callback raised if there is an issue to load the texture
  16222. * @param format defines the format of the data
  16223. * @param forcedExtension defines the extension to use to pick the right loader
  16224. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16225. * @returns the cube texture as an InternalTexture
  16226. */
  16227. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16228. var _this = this;
  16229. if (onLoad === void 0) { onLoad = null; }
  16230. if (onError === void 0) { onError = null; }
  16231. if (forcedExtension === void 0) { forcedExtension = null; }
  16232. if (createPolynomials === void 0) { createPolynomials = true; }
  16233. var callback = function (loadData) {
  16234. if (!loadData) {
  16235. if (onLoad) {
  16236. onLoad(null);
  16237. }
  16238. return;
  16239. }
  16240. var texture = loadData.texture;
  16241. if (!createPolynomials) {
  16242. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16243. }
  16244. else if (loadData.info.sphericalPolynomial) {
  16245. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16246. }
  16247. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16248. if (_this._caps.textureLOD) {
  16249. // Do not add extra process if texture lod is supported.
  16250. if (onLoad) {
  16251. onLoad(texture);
  16252. }
  16253. return;
  16254. }
  16255. var mipSlices = 3;
  16256. var gl = _this._gl;
  16257. var width = loadData.width;
  16258. if (!width) {
  16259. return;
  16260. }
  16261. var textures = [];
  16262. for (var i = 0; i < mipSlices; i++) {
  16263. //compute LOD from even spacing in smoothness (matching shader calculation)
  16264. var smoothness = i / (mipSlices - 1);
  16265. var roughness = 1 - smoothness;
  16266. var minLODIndex = lodOffset; // roughness = 0
  16267. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16268. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16269. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16270. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16271. glTextureFromLod.type = texture.type;
  16272. glTextureFromLod.format = texture.format;
  16273. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16274. glTextureFromLod.height = glTextureFromLod.width;
  16275. glTextureFromLod.isCube = true;
  16276. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16277. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16278. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16279. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16280. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16281. if (loadData.isDDS) {
  16282. var info = loadData.info;
  16283. var data = loadData.data;
  16284. _this._unpackFlipY(info.isCompressed);
  16285. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16286. }
  16287. else {
  16288. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16289. }
  16290. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16291. // Wrap in a base texture for easy binding.
  16292. var lodTexture = new BABYLON.BaseTexture(scene);
  16293. lodTexture.isCube = true;
  16294. lodTexture._texture = glTextureFromLod;
  16295. glTextureFromLod.isReady = true;
  16296. textures.push(lodTexture);
  16297. }
  16298. texture._lodTextureHigh = textures[2];
  16299. texture._lodTextureMid = textures[1];
  16300. texture._lodTextureLow = textures[0];
  16301. if (onLoad) {
  16302. onLoad(texture);
  16303. }
  16304. };
  16305. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16306. };
  16307. /**
  16308. * Creates a cube texture
  16309. * @param rootUrl defines the url where the files to load is located
  16310. * @param scene defines the current scene
  16311. * @param files defines the list of files to load (1 per face)
  16312. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16313. * @param onLoad defines an optional callback raised when the texture is loaded
  16314. * @param onError defines an optional callback raised if there is an issue to load the texture
  16315. * @param format defines the format of the data
  16316. * @param forcedExtension defines the extension to use to pick the right loader
  16317. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16318. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16319. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16320. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16321. * @returns the cube texture as an InternalTexture
  16322. */
  16323. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16324. var _this = this;
  16325. if (onLoad === void 0) { onLoad = null; }
  16326. if (onError === void 0) { onError = null; }
  16327. if (forcedExtension === void 0) { forcedExtension = null; }
  16328. if (createPolynomials === void 0) { createPolynomials = false; }
  16329. if (lodScale === void 0) { lodScale = 0; }
  16330. if (lodOffset === void 0) { lodOffset = 0; }
  16331. if (fallback === void 0) { fallback = null; }
  16332. var gl = this._gl;
  16333. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16334. texture.isCube = true;
  16335. texture.url = rootUrl;
  16336. texture.generateMipMaps = !noMipmap;
  16337. texture._lodGenerationScale = lodScale;
  16338. texture._lodGenerationOffset = lodOffset;
  16339. if (!this._doNotHandleContextLost) {
  16340. texture._extension = forcedExtension;
  16341. texture._files = files;
  16342. }
  16343. var lastDot = rootUrl.lastIndexOf('.');
  16344. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16345. var loader = null;
  16346. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16347. var availableLoader = _a[_i];
  16348. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16349. loader = availableLoader;
  16350. break;
  16351. }
  16352. }
  16353. var onInternalError = function (request, exception) {
  16354. if (loader) {
  16355. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16356. if (fallbackUrl) {
  16357. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16358. }
  16359. }
  16360. if (onError && request) {
  16361. onError(request.status + " " + request.statusText, exception);
  16362. }
  16363. };
  16364. if (loader) {
  16365. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16366. var onloaddata = function (data) {
  16367. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16368. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16369. };
  16370. if (files && files.length === 6) {
  16371. if (loader.supportCascades) {
  16372. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16373. }
  16374. else if (onError) {
  16375. onError("Textures type does not support cascades.");
  16376. }
  16377. }
  16378. else {
  16379. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16380. }
  16381. }
  16382. else {
  16383. if (!files) {
  16384. throw new Error("Cannot load cubemap because files were not defined");
  16385. }
  16386. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16387. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16388. var height = width;
  16389. _this._prepareWorkingCanvas();
  16390. if (!_this._workingCanvas || !_this._workingContext) {
  16391. return;
  16392. }
  16393. _this._workingCanvas.width = width;
  16394. _this._workingCanvas.height = height;
  16395. var faces = [
  16396. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16397. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16398. ];
  16399. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16400. _this._unpackFlipY(false);
  16401. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16402. for (var index = 0; index < faces.length; index++) {
  16403. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16404. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16405. }
  16406. if (!noMipmap) {
  16407. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16408. }
  16409. _this._setCubeMapTextureParams(!noMipmap);
  16410. texture.width = width;
  16411. texture.height = height;
  16412. texture.isReady = true;
  16413. if (format) {
  16414. texture.format = format;
  16415. }
  16416. texture.onLoadedObservable.notifyObservers(texture);
  16417. texture.onLoadedObservable.clear();
  16418. if (onLoad) {
  16419. onLoad();
  16420. }
  16421. }, files, onError);
  16422. }
  16423. this._internalTexturesCache.push(texture);
  16424. return texture;
  16425. };
  16426. /**
  16427. * @hidden
  16428. */
  16429. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16430. var gl = this._gl;
  16431. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16432. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16433. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16434. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16435. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16436. // this.resetTextureCache();
  16437. };
  16438. /**
  16439. * Update a raw cube texture
  16440. * @param texture defines the texture to udpdate
  16441. * @param data defines the data to store
  16442. * @param format defines the data format
  16443. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16444. * @param invertY defines if data must be stored with Y axis inverted
  16445. * @param compression defines the compression used (null by default)
  16446. * @param level defines which level of the texture to update
  16447. */
  16448. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16449. if (compression === void 0) { compression = null; }
  16450. if (level === void 0) { level = 0; }
  16451. texture._bufferViewArray = data;
  16452. texture.format = format;
  16453. texture.type = type;
  16454. texture.invertY = invertY;
  16455. texture._compression = compression;
  16456. var gl = this._gl;
  16457. var textureType = this._getWebGLTextureType(type);
  16458. var internalFormat = this._getInternalFormat(format);
  16459. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16460. var needConversion = false;
  16461. if (internalFormat === gl.RGB) {
  16462. internalFormat = gl.RGBA;
  16463. needConversion = true;
  16464. }
  16465. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16466. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16467. if (texture.width % 4 !== 0) {
  16468. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16469. }
  16470. // Data are known to be in +X +Y +Z -X -Y -Z
  16471. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16472. var faceData = data[faceIndex];
  16473. if (compression) {
  16474. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16475. }
  16476. else {
  16477. if (needConversion) {
  16478. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16479. }
  16480. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16481. }
  16482. }
  16483. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16484. if (isPot && texture.generateMipMaps && level === 0) {
  16485. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16486. }
  16487. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16488. // this.resetTextureCache();
  16489. texture.isReady = true;
  16490. };
  16491. /**
  16492. * Creates a new raw cube texture
  16493. * @param data defines the array of data to use to create each face
  16494. * @param size defines the size of the textures
  16495. * @param format defines the format of the data
  16496. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16497. * @param generateMipMaps defines if the engine should generate the mip levels
  16498. * @param invertY defines if data must be stored with Y axis inverted
  16499. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16500. * @param compression defines the compression used (null by default)
  16501. * @returns the cube texture as an InternalTexture
  16502. */
  16503. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16504. if (compression === void 0) { compression = null; }
  16505. var gl = this._gl;
  16506. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16507. texture.isCube = true;
  16508. texture.format = format;
  16509. texture.type = type;
  16510. if (!this._doNotHandleContextLost) {
  16511. texture._bufferViewArray = data;
  16512. }
  16513. var textureType = this._getWebGLTextureType(type);
  16514. var internalFormat = this._getInternalFormat(format);
  16515. if (internalFormat === gl.RGB) {
  16516. internalFormat = gl.RGBA;
  16517. }
  16518. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16519. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16520. generateMipMaps = false;
  16521. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16522. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16523. }
  16524. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16525. generateMipMaps = false;
  16526. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16527. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16528. }
  16529. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16530. generateMipMaps = false;
  16531. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16532. }
  16533. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16534. generateMipMaps = false;
  16535. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16536. }
  16537. var width = size;
  16538. var height = width;
  16539. texture.width = width;
  16540. texture.height = height;
  16541. // Double check on POT to generate Mips.
  16542. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16543. if (!isPot) {
  16544. generateMipMaps = false;
  16545. }
  16546. // Upload data if needed. The texture won't be ready until then.
  16547. if (data) {
  16548. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16549. }
  16550. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16551. // Filters
  16552. if (data && generateMipMaps) {
  16553. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16554. }
  16555. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16559. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16560. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16561. texture.generateMipMaps = generateMipMaps;
  16562. return texture;
  16563. };
  16564. /**
  16565. * Creates a new raw cube texture from a specified url
  16566. * @param url defines the url where the data is located
  16567. * @param scene defines the current scene
  16568. * @param size defines the size of the textures
  16569. * @param format defines the format of the data
  16570. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16571. * @param noMipmap defines if the engine should avoid generating the mip levels
  16572. * @param callback defines a callback used to extract texture data from loaded data
  16573. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16574. * @param onLoad defines a callback called when texture is loaded
  16575. * @param onError defines a callback called if there is an error
  16576. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16577. * @param invertY defines if data must be stored with Y axis inverted
  16578. * @returns the cube texture as an InternalTexture
  16579. */
  16580. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16581. var _this = this;
  16582. if (onLoad === void 0) { onLoad = null; }
  16583. if (onError === void 0) { onError = null; }
  16584. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16585. if (invertY === void 0) { invertY = false; }
  16586. var gl = this._gl;
  16587. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16588. scene._addPendingData(texture);
  16589. texture.url = url;
  16590. this._internalTexturesCache.push(texture);
  16591. var onerror = function (request, exception) {
  16592. scene._removePendingData(texture);
  16593. if (onError && request) {
  16594. onError(request.status + " " + request.statusText, exception);
  16595. }
  16596. };
  16597. var internalCallback = function (data) {
  16598. var width = texture.width;
  16599. var faceDataArrays = callback(data);
  16600. if (!faceDataArrays) {
  16601. return;
  16602. }
  16603. if (mipmapGenerator) {
  16604. var textureType = _this._getWebGLTextureType(type);
  16605. var internalFormat = _this._getInternalFormat(format);
  16606. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16607. var needConversion = false;
  16608. if (internalFormat === gl.RGB) {
  16609. internalFormat = gl.RGBA;
  16610. needConversion = true;
  16611. }
  16612. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16613. _this._unpackFlipY(false);
  16614. var mipData = mipmapGenerator(faceDataArrays);
  16615. for (var level = 0; level < mipData.length; level++) {
  16616. var mipSize = width >> level;
  16617. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16618. var mipFaceData = mipData[level][faceIndex];
  16619. if (needConversion) {
  16620. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16621. }
  16622. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16623. }
  16624. }
  16625. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16626. }
  16627. else {
  16628. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16629. }
  16630. texture.isReady = true;
  16631. // this.resetTextureCache();
  16632. scene._removePendingData(texture);
  16633. if (onLoad) {
  16634. onLoad();
  16635. }
  16636. };
  16637. this._loadFile(url, function (data) {
  16638. internalCallback(data);
  16639. }, undefined, scene.database, true, onerror);
  16640. return texture;
  16641. };
  16642. ;
  16643. /**
  16644. * Update a raw 3D texture
  16645. * @param texture defines the texture to update
  16646. * @param data defines the data to store
  16647. * @param format defines the data format
  16648. * @param invertY defines if data must be stored with Y axis inverted
  16649. * @param compression defines the used compression (can be null)
  16650. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16651. */
  16652. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16653. if (compression === void 0) { compression = null; }
  16654. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16655. var internalType = this._getWebGLTextureType(textureType);
  16656. var internalFormat = this._getInternalFormat(format);
  16657. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16658. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16659. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16660. if (!this._doNotHandleContextLost) {
  16661. texture._bufferView = data;
  16662. texture.format = format;
  16663. texture.invertY = invertY;
  16664. texture._compression = compression;
  16665. }
  16666. if (texture.width % 4 !== 0) {
  16667. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16668. }
  16669. if (compression && data) {
  16670. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16671. }
  16672. else {
  16673. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16674. }
  16675. if (texture.generateMipMaps) {
  16676. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16677. }
  16678. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16679. // this.resetTextureCache();
  16680. texture.isReady = true;
  16681. };
  16682. /**
  16683. * Creates a new raw 3D texture
  16684. * @param data defines the data used to create the texture
  16685. * @param width defines the width of the texture
  16686. * @param height defines the height of the texture
  16687. * @param depth defines the depth of the texture
  16688. * @param format defines the format of the texture
  16689. * @param generateMipMaps defines if the engine must generate mip levels
  16690. * @param invertY defines if data must be stored with Y axis inverted
  16691. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16692. * @param compression defines the compressed used (can be null)
  16693. * @param textureType defines the compressed used (can be null)
  16694. * @returns a new raw 3D texture (stored in an InternalTexture)
  16695. */
  16696. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16697. if (compression === void 0) { compression = null; }
  16698. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16699. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16700. texture.baseWidth = width;
  16701. texture.baseHeight = height;
  16702. texture.baseDepth = depth;
  16703. texture.width = width;
  16704. texture.height = height;
  16705. texture.depth = depth;
  16706. texture.format = format;
  16707. texture.type = textureType;
  16708. texture.generateMipMaps = generateMipMaps;
  16709. texture.samplingMode = samplingMode;
  16710. texture.is3D = true;
  16711. if (!this._doNotHandleContextLost) {
  16712. texture._bufferView = data;
  16713. }
  16714. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16715. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16716. // Filters
  16717. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16718. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16719. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16720. if (generateMipMaps) {
  16721. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16722. }
  16723. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16724. this._internalTexturesCache.push(texture);
  16725. return texture;
  16726. };
  16727. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16728. var gl = this._gl;
  16729. if (!gl) {
  16730. return;
  16731. }
  16732. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16733. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16734. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16735. if (!noMipmap && !isCompressed) {
  16736. gl.generateMipmap(gl.TEXTURE_2D);
  16737. }
  16738. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16739. // this.resetTextureCache();
  16740. if (scene) {
  16741. scene._removePendingData(texture);
  16742. }
  16743. texture.onLoadedObservable.notifyObservers(texture);
  16744. texture.onLoadedObservable.clear();
  16745. };
  16746. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16747. var _this = this;
  16748. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16749. var maxTextureSize = this.getCaps().maxTextureSize;
  16750. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16751. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16752. var gl = this._gl;
  16753. if (!gl) {
  16754. return;
  16755. }
  16756. if (!texture._webGLTexture) {
  16757. // this.resetTextureCache();
  16758. if (scene) {
  16759. scene._removePendingData(texture);
  16760. }
  16761. return;
  16762. }
  16763. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16764. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16765. texture.baseWidth = width;
  16766. texture.baseHeight = height;
  16767. texture.width = potWidth;
  16768. texture.height = potHeight;
  16769. texture.isReady = true;
  16770. if (processFunction(potWidth, potHeight, function () {
  16771. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16772. })) {
  16773. // Returning as texture needs extra async steps
  16774. return;
  16775. }
  16776. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16777. };
  16778. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16779. // Create new RGBA data container.
  16780. var rgbaData;
  16781. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16782. rgbaData = new Float32Array(width * height * 4);
  16783. }
  16784. else {
  16785. rgbaData = new Uint32Array(width * height * 4);
  16786. }
  16787. // Convert each pixel.
  16788. for (var x = 0; x < width; x++) {
  16789. for (var y = 0; y < height; y++) {
  16790. var index = (y * width + x) * 3;
  16791. var newIndex = (y * width + x) * 4;
  16792. // Map Old Value to new value.
  16793. rgbaData[newIndex + 0] = rgbData[index + 0];
  16794. rgbaData[newIndex + 1] = rgbData[index + 1];
  16795. rgbaData[newIndex + 2] = rgbData[index + 2];
  16796. // Add fully opaque alpha channel.
  16797. rgbaData[newIndex + 3] = 1;
  16798. }
  16799. }
  16800. return rgbaData;
  16801. };
  16802. /** @hidden */
  16803. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16804. var gl = this._gl;
  16805. if (texture._framebuffer) {
  16806. gl.deleteFramebuffer(texture._framebuffer);
  16807. texture._framebuffer = null;
  16808. }
  16809. if (texture._depthStencilBuffer) {
  16810. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16811. texture._depthStencilBuffer = null;
  16812. }
  16813. if (texture._MSAAFramebuffer) {
  16814. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16815. texture._MSAAFramebuffer = null;
  16816. }
  16817. if (texture._MSAARenderBuffer) {
  16818. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16819. texture._MSAARenderBuffer = null;
  16820. }
  16821. };
  16822. /** @hidden */
  16823. Engine.prototype._releaseTexture = function (texture) {
  16824. var gl = this._gl;
  16825. this._releaseFramebufferObjects(texture);
  16826. gl.deleteTexture(texture._webGLTexture);
  16827. // Unbind channels
  16828. this.unbindAllTextures();
  16829. var index = this._internalTexturesCache.indexOf(texture);
  16830. if (index !== -1) {
  16831. this._internalTexturesCache.splice(index, 1);
  16832. }
  16833. // Integrated fixed lod samplers.
  16834. if (texture._lodTextureHigh) {
  16835. texture._lodTextureHigh.dispose();
  16836. }
  16837. if (texture._lodTextureMid) {
  16838. texture._lodTextureMid.dispose();
  16839. }
  16840. if (texture._lodTextureLow) {
  16841. texture._lodTextureLow.dispose();
  16842. }
  16843. // Set output texture of post process to null if the texture has been released/disposed
  16844. this.scenes.forEach(function (scene) {
  16845. scene.postProcesses.forEach(function (postProcess) {
  16846. if (postProcess._outputTexture == texture) {
  16847. postProcess._outputTexture = null;
  16848. }
  16849. });
  16850. scene.cameras.forEach(function (camera) {
  16851. camera._postProcesses.forEach(function (postProcess) {
  16852. if (postProcess) {
  16853. if (postProcess._outputTexture == texture) {
  16854. postProcess._outputTexture = null;
  16855. }
  16856. }
  16857. });
  16858. });
  16859. });
  16860. };
  16861. Engine.prototype.setProgram = function (program) {
  16862. if (this._currentProgram !== program) {
  16863. this._gl.useProgram(program);
  16864. this._currentProgram = program;
  16865. }
  16866. };
  16867. /**
  16868. * Binds an effect to the webGL context
  16869. * @param effect defines the effect to bind
  16870. */
  16871. Engine.prototype.bindSamplers = function (effect) {
  16872. this.setProgram(effect.getProgram());
  16873. var samplers = effect.getSamplers();
  16874. for (var index = 0; index < samplers.length; index++) {
  16875. var uniform = effect.getUniform(samplers[index]);
  16876. if (uniform) {
  16877. this._boundUniforms[index] = uniform;
  16878. }
  16879. }
  16880. this._currentEffect = null;
  16881. };
  16882. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16883. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16884. return;
  16885. }
  16886. // Remove
  16887. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16888. // Bind last to it
  16889. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16890. // Bind to dummy
  16891. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16892. };
  16893. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16894. if (!internalTexture) {
  16895. return -1;
  16896. }
  16897. internalTexture._initialSlot = channel;
  16898. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16899. if (channel !== internalTexture._designatedSlot) {
  16900. this._textureCollisions.addCount(1, false);
  16901. }
  16902. }
  16903. else {
  16904. if (channel !== internalTexture._designatedSlot) {
  16905. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16906. return internalTexture._designatedSlot;
  16907. }
  16908. else {
  16909. // No slot for this texture, let's pick a new one (if we find a free slot)
  16910. if (this._nextFreeTextureSlots.length) {
  16911. return this._nextFreeTextureSlots[0];
  16912. }
  16913. // We need to recycle the oldest bound texture, sorry.
  16914. this._textureCollisions.addCount(1, false);
  16915. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16916. }
  16917. }
  16918. }
  16919. return channel;
  16920. };
  16921. Engine.prototype._linkTrackers = function (previous, next) {
  16922. previous.next = next;
  16923. next.previous = previous;
  16924. };
  16925. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16926. var currentSlot = internalTexture._designatedSlot;
  16927. if (currentSlot === -1) {
  16928. return -1;
  16929. }
  16930. internalTexture._designatedSlot = -1;
  16931. if (this.disableTextureBindingOptimization) {
  16932. return -1;
  16933. }
  16934. // Remove from bound list
  16935. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16936. // Free the slot
  16937. this._boundTexturesCache[currentSlot] = null;
  16938. this._nextFreeTextureSlots.push(currentSlot);
  16939. return currentSlot;
  16940. };
  16941. Engine.prototype._activateCurrentTexture = function () {
  16942. if (this._currentTextureChannel !== this._activeChannel) {
  16943. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16944. this._currentTextureChannel = this._activeChannel;
  16945. }
  16946. };
  16947. /** @hidden */
  16948. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16949. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16950. if (force === void 0) { force = false; }
  16951. var wasPreviouslyBound = false;
  16952. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16953. this._activeChannel = texture._designatedSlot;
  16954. }
  16955. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16956. var isTextureForRendering = texture && texture._initialSlot > -1;
  16957. if (currentTextureBound !== texture || force) {
  16958. if (currentTextureBound) {
  16959. this._removeDesignatedSlot(currentTextureBound);
  16960. }
  16961. this._activateCurrentTexture();
  16962. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16963. this._boundTexturesCache[this._activeChannel] = texture;
  16964. if (texture) {
  16965. if (!this.disableTextureBindingOptimization) {
  16966. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16967. if (slotIndex > -1) {
  16968. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16969. }
  16970. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16971. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16972. }
  16973. texture._designatedSlot = this._activeChannel;
  16974. }
  16975. }
  16976. else if (forTextureDataUpdate) {
  16977. wasPreviouslyBound = true;
  16978. this._activateCurrentTexture();
  16979. }
  16980. if (isTextureForRendering && !forTextureDataUpdate) {
  16981. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16982. }
  16983. return wasPreviouslyBound;
  16984. };
  16985. /** @hidden */
  16986. Engine.prototype._bindTexture = function (channel, texture) {
  16987. if (channel < 0) {
  16988. return;
  16989. }
  16990. if (texture) {
  16991. channel = this._getCorrectTextureChannel(channel, texture);
  16992. }
  16993. this._activeChannel = channel;
  16994. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16995. };
  16996. /**
  16997. * Sets a texture to the webGL context from a postprocess
  16998. * @param channel defines the channel to use
  16999. * @param postProcess defines the source postprocess
  17000. */
  17001. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17002. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17003. };
  17004. /**
  17005. * Binds the output of the passed in post process to the texture channel specified
  17006. * @param channel The channel the texture should be bound to
  17007. * @param postProcess The post process which's output should be bound
  17008. */
  17009. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17010. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17011. };
  17012. /**
  17013. * Unbind all textures from the webGL context
  17014. */
  17015. Engine.prototype.unbindAllTextures = function () {
  17016. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17017. this._activeChannel = channel;
  17018. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17019. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17020. if (this.webGLVersion > 1) {
  17021. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17022. }
  17023. }
  17024. };
  17025. /**
  17026. * Sets a texture to the according uniform.
  17027. * @param channel The texture channel
  17028. * @param uniform The uniform to set
  17029. * @param texture The texture to apply
  17030. */
  17031. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17032. if (channel < 0) {
  17033. return;
  17034. }
  17035. if (uniform) {
  17036. this._boundUniforms[channel] = uniform;
  17037. }
  17038. this._setTexture(channel, texture);
  17039. };
  17040. /**
  17041. * Sets a depth stencil texture from a render target to the according uniform.
  17042. * @param channel The texture channel
  17043. * @param uniform The uniform to set
  17044. * @param texture The render target texture containing the depth stencil texture to apply
  17045. */
  17046. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17047. if (channel < 0) {
  17048. return;
  17049. }
  17050. if (uniform) {
  17051. this._boundUniforms[channel] = uniform;
  17052. }
  17053. if (!texture || !texture.depthStencilTexture) {
  17054. this._setTexture(channel, null);
  17055. }
  17056. else {
  17057. this._setTexture(channel, texture, false, true);
  17058. }
  17059. };
  17060. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17061. var uniform = this._boundUniforms[sourceSlot];
  17062. if (uniform._currentState === destination) {
  17063. return;
  17064. }
  17065. this._gl.uniform1i(uniform, destination);
  17066. uniform._currentState = destination;
  17067. };
  17068. Engine.prototype._getTextureWrapMode = function (mode) {
  17069. switch (mode) {
  17070. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17071. return this._gl.REPEAT;
  17072. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17073. return this._gl.CLAMP_TO_EDGE;
  17074. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17075. return this._gl.MIRRORED_REPEAT;
  17076. }
  17077. return this._gl.REPEAT;
  17078. };
  17079. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17080. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17081. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17082. // Not ready?
  17083. if (!texture) {
  17084. if (this._boundTexturesCache[channel] != null) {
  17085. this._activeChannel = channel;
  17086. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17087. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17088. if (this.webGLVersion > 1) {
  17089. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17090. }
  17091. }
  17092. return false;
  17093. }
  17094. // Video
  17095. if (texture.video) {
  17096. this._activeChannel = channel;
  17097. texture.update();
  17098. }
  17099. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17100. texture.delayLoad();
  17101. return false;
  17102. }
  17103. var internalTexture;
  17104. if (depthStencilTexture) {
  17105. internalTexture = texture.depthStencilTexture;
  17106. }
  17107. else if (texture.isReady()) {
  17108. internalTexture = texture.getInternalTexture();
  17109. }
  17110. else if (texture.isCube) {
  17111. internalTexture = this.emptyCubeTexture;
  17112. }
  17113. else if (texture.is3D) {
  17114. internalTexture = this.emptyTexture3D;
  17115. }
  17116. else {
  17117. internalTexture = this.emptyTexture;
  17118. }
  17119. if (!isPartOfTextureArray) {
  17120. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17121. }
  17122. var needToBind = true;
  17123. if (this._boundTexturesCache[channel] === internalTexture) {
  17124. this._moveBoundTextureOnTop(internalTexture);
  17125. if (!isPartOfTextureArray) {
  17126. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17127. }
  17128. needToBind = false;
  17129. }
  17130. this._activeChannel = channel;
  17131. if (internalTexture && internalTexture.is3D) {
  17132. if (needToBind) {
  17133. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17134. }
  17135. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17136. internalTexture._cachedWrapU = texture.wrapU;
  17137. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17138. }
  17139. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17140. internalTexture._cachedWrapV = texture.wrapV;
  17141. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17142. }
  17143. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17144. internalTexture._cachedWrapR = texture.wrapR;
  17145. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17146. }
  17147. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17148. }
  17149. else if (internalTexture && internalTexture.isCube) {
  17150. if (needToBind) {
  17151. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17152. }
  17153. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17154. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17155. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17156. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17157. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17158. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17159. }
  17160. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17161. }
  17162. else {
  17163. if (needToBind) {
  17164. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17165. }
  17166. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17167. internalTexture._cachedWrapU = texture.wrapU;
  17168. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17169. }
  17170. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17171. internalTexture._cachedWrapV = texture.wrapV;
  17172. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17173. }
  17174. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17175. }
  17176. return true;
  17177. };
  17178. /**
  17179. * Sets an array of texture to the webGL context
  17180. * @param channel defines the channel where the texture array must be set
  17181. * @param uniform defines the associated uniform location
  17182. * @param textures defines the array of textures to bind
  17183. */
  17184. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17185. if (channel < 0 || !uniform) {
  17186. return;
  17187. }
  17188. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17189. this._textureUnits = new Int32Array(textures.length);
  17190. }
  17191. for (var i = 0; i < textures.length; i++) {
  17192. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17193. }
  17194. this._gl.uniform1iv(uniform, this._textureUnits);
  17195. for (var index = 0; index < textures.length; index++) {
  17196. this._setTexture(this._textureUnits[index], textures[index], true);
  17197. }
  17198. };
  17199. /** @hidden */
  17200. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17201. var internalTexture = texture.getInternalTexture();
  17202. if (!internalTexture) {
  17203. return;
  17204. }
  17205. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17206. var value = texture.anisotropicFilteringLevel;
  17207. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17208. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17209. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17210. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17211. }
  17212. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17213. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17214. internalTexture._cachedAnisotropicFilteringLevel = value;
  17215. }
  17216. };
  17217. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17218. this._bindTextureDirectly(target, texture, true, true);
  17219. this._gl.texParameterf(target, parameter, value);
  17220. };
  17221. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17222. if (texture) {
  17223. this._bindTextureDirectly(target, texture, true, true);
  17224. }
  17225. this._gl.texParameteri(target, parameter, value);
  17226. };
  17227. /**
  17228. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17229. * @param x defines the x coordinate of the rectangle where pixels must be read
  17230. * @param y defines the y coordinate of the rectangle where pixels must be read
  17231. * @param width defines the width of the rectangle where pixels must be read
  17232. * @param height defines the height of the rectangle where pixels must be read
  17233. * @returns a Uint8Array containing RGBA colors
  17234. */
  17235. Engine.prototype.readPixels = function (x, y, width, height) {
  17236. var data = new Uint8Array(height * width * 4);
  17237. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17238. return data;
  17239. };
  17240. /**
  17241. * Add an externaly attached data from its key.
  17242. * This method call will fail and return false, if such key already exists.
  17243. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17244. * @param key the unique key that identifies the data
  17245. * @param data the data object to associate to the key for this Engine instance
  17246. * @return true if no such key were already present and the data was added successfully, false otherwise
  17247. */
  17248. Engine.prototype.addExternalData = function (key, data) {
  17249. if (!this._externalData) {
  17250. this._externalData = new BABYLON.StringDictionary();
  17251. }
  17252. return this._externalData.add(key, data);
  17253. };
  17254. /**
  17255. * Get an externaly attached data from its key
  17256. * @param key the unique key that identifies the data
  17257. * @return the associated data, if present (can be null), or undefined if not present
  17258. */
  17259. Engine.prototype.getExternalData = function (key) {
  17260. if (!this._externalData) {
  17261. this._externalData = new BABYLON.StringDictionary();
  17262. }
  17263. return this._externalData.get(key);
  17264. };
  17265. /**
  17266. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17267. * @param key the unique key that identifies the data
  17268. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17269. * @return the associated data, can be null if the factory returned null.
  17270. */
  17271. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17272. if (!this._externalData) {
  17273. this._externalData = new BABYLON.StringDictionary();
  17274. }
  17275. return this._externalData.getOrAddWithFactory(key, factory);
  17276. };
  17277. /**
  17278. * Remove an externaly attached data from the Engine instance
  17279. * @param key the unique key that identifies the data
  17280. * @return true if the data was successfully removed, false if it doesn't exist
  17281. */
  17282. Engine.prototype.removeExternalData = function (key) {
  17283. if (!this._externalData) {
  17284. this._externalData = new BABYLON.StringDictionary();
  17285. }
  17286. return this._externalData.remove(key);
  17287. };
  17288. /**
  17289. * Unbind all vertex attributes from the webGL context
  17290. */
  17291. Engine.prototype.unbindAllAttributes = function () {
  17292. if (this._mustWipeVertexAttributes) {
  17293. this._mustWipeVertexAttributes = false;
  17294. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17295. this._gl.disableVertexAttribArray(i);
  17296. this._vertexAttribArraysEnabled[i] = false;
  17297. this._currentBufferPointers[i].active = false;
  17298. }
  17299. return;
  17300. }
  17301. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17302. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17303. continue;
  17304. }
  17305. this._gl.disableVertexAttribArray(i);
  17306. this._vertexAttribArraysEnabled[i] = false;
  17307. this._currentBufferPointers[i].active = false;
  17308. }
  17309. };
  17310. /**
  17311. * 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
  17312. */
  17313. Engine.prototype.releaseEffects = function () {
  17314. for (var name in this._compiledEffects) {
  17315. this._deleteProgram(this._compiledEffects[name]._program);
  17316. }
  17317. this._compiledEffects = {};
  17318. };
  17319. /**
  17320. * Dispose and release all associated resources
  17321. */
  17322. Engine.prototype.dispose = function () {
  17323. this.hideLoadingUI();
  17324. this.stopRenderLoop();
  17325. // Release postProcesses
  17326. while (this.postProcesses.length) {
  17327. this.postProcesses[0].dispose();
  17328. }
  17329. // Empty texture
  17330. if (this._emptyTexture) {
  17331. this._releaseTexture(this._emptyTexture);
  17332. this._emptyTexture = null;
  17333. }
  17334. if (this._emptyCubeTexture) {
  17335. this._releaseTexture(this._emptyCubeTexture);
  17336. this._emptyCubeTexture = null;
  17337. }
  17338. // Rescale PP
  17339. if (this._rescalePostProcess) {
  17340. this._rescalePostProcess.dispose();
  17341. }
  17342. // Release scenes
  17343. while (this.scenes.length) {
  17344. this.scenes[0].dispose();
  17345. }
  17346. // Release audio engine
  17347. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17348. Engine.audioEngine.dispose();
  17349. }
  17350. // Release effects
  17351. this.releaseEffects();
  17352. // Unbind
  17353. this.unbindAllAttributes();
  17354. this._boundUniforms = [];
  17355. if (this._dummyFramebuffer) {
  17356. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17357. }
  17358. //WebVR
  17359. this.disableVR();
  17360. // Events
  17361. if (BABYLON.Tools.IsWindowObjectExist()) {
  17362. window.removeEventListener("blur", this._onBlur);
  17363. window.removeEventListener("focus", this._onFocus);
  17364. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17365. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17366. if (this._renderingCanvas) {
  17367. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17368. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17369. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17370. if (!this._doNotHandleContextLost) {
  17371. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17372. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17373. }
  17374. }
  17375. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17376. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17377. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17378. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17379. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17380. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17381. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17382. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17383. if (this._onVrDisplayConnect) {
  17384. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17385. if (this._onVrDisplayDisconnect) {
  17386. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17387. }
  17388. if (this._onVrDisplayPresentChange) {
  17389. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17390. }
  17391. this._onVrDisplayConnect = null;
  17392. this._onVrDisplayDisconnect = null;
  17393. }
  17394. }
  17395. // Remove from Instances
  17396. var index = Engine.Instances.indexOf(this);
  17397. if (index >= 0) {
  17398. Engine.Instances.splice(index, 1);
  17399. }
  17400. this._workingCanvas = null;
  17401. this._workingContext = null;
  17402. this._currentBufferPointers = [];
  17403. this._renderingCanvas = null;
  17404. this._currentProgram = null;
  17405. this._bindedRenderFunction = null;
  17406. this.onResizeObservable.clear();
  17407. this.onCanvasBlurObservable.clear();
  17408. this.onCanvasFocusObservable.clear();
  17409. this.onCanvasPointerOutObservable.clear();
  17410. this.onBeginFrameObservable.clear();
  17411. this.onEndFrameObservable.clear();
  17412. BABYLON.Effect.ResetCache();
  17413. // Abort active requests
  17414. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17415. var request = _a[_i];
  17416. request.abort();
  17417. }
  17418. };
  17419. // Loading screen
  17420. /**
  17421. * Display the loading screen
  17422. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17423. */
  17424. Engine.prototype.displayLoadingUI = function () {
  17425. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17426. return;
  17427. }
  17428. var loadingScreen = this.loadingScreen;
  17429. if (loadingScreen) {
  17430. loadingScreen.displayLoadingUI();
  17431. }
  17432. };
  17433. /**
  17434. * Hide the loading screen
  17435. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17436. */
  17437. Engine.prototype.hideLoadingUI = function () {
  17438. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17439. return;
  17440. }
  17441. var loadingScreen = this.loadingScreen;
  17442. if (loadingScreen) {
  17443. loadingScreen.hideLoadingUI();
  17444. }
  17445. };
  17446. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17447. /**
  17448. * Gets the current loading screen object
  17449. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17450. */
  17451. get: function () {
  17452. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17453. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17454. return this._loadingScreen;
  17455. },
  17456. /**
  17457. * Sets the current loading screen object
  17458. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17459. */
  17460. set: function (loadingScreen) {
  17461. this._loadingScreen = loadingScreen;
  17462. },
  17463. enumerable: true,
  17464. configurable: true
  17465. });
  17466. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17467. /**
  17468. * Sets the current loading screen text
  17469. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17470. */
  17471. set: function (text) {
  17472. this.loadingScreen.loadingUIText = text;
  17473. },
  17474. enumerable: true,
  17475. configurable: true
  17476. });
  17477. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17478. /**
  17479. * Sets the current loading screen background color
  17480. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17481. */
  17482. set: function (color) {
  17483. this.loadingScreen.loadingUIBackgroundColor = color;
  17484. },
  17485. enumerable: true,
  17486. configurable: true
  17487. });
  17488. /**
  17489. * Attach a new callback raised when context lost event is fired
  17490. * @param callback defines the callback to call
  17491. */
  17492. Engine.prototype.attachContextLostEvent = function (callback) {
  17493. if (this._renderingCanvas) {
  17494. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17495. }
  17496. };
  17497. /**
  17498. * Attach a new callback raised when context restored event is fired
  17499. * @param callback defines the callback to call
  17500. */
  17501. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17502. if (this._renderingCanvas) {
  17503. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17504. }
  17505. };
  17506. /**
  17507. * Gets the source code of the vertex shader associated with a specific webGL program
  17508. * @param program defines the program to use
  17509. * @returns a string containing the source code of the vertex shader associated with the program
  17510. */
  17511. Engine.prototype.getVertexShaderSource = function (program) {
  17512. var shaders = this._gl.getAttachedShaders(program);
  17513. if (!shaders) {
  17514. return null;
  17515. }
  17516. return this._gl.getShaderSource(shaders[0]);
  17517. };
  17518. /**
  17519. * Gets the source code of the fragment shader associated with a specific webGL program
  17520. * @param program defines the program to use
  17521. * @returns a string containing the source code of the fragment shader associated with the program
  17522. */
  17523. Engine.prototype.getFragmentShaderSource = function (program) {
  17524. var shaders = this._gl.getAttachedShaders(program);
  17525. if (!shaders) {
  17526. return null;
  17527. }
  17528. return this._gl.getShaderSource(shaders[1]);
  17529. };
  17530. /**
  17531. * Get the current error code of the webGL context
  17532. * @returns the error code
  17533. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17534. */
  17535. Engine.prototype.getError = function () {
  17536. return this._gl.getError();
  17537. };
  17538. // FPS
  17539. /**
  17540. * Gets the current framerate
  17541. * @returns a number representing the framerate
  17542. */
  17543. Engine.prototype.getFps = function () {
  17544. return this._fps;
  17545. };
  17546. /**
  17547. * Gets the time spent between current and previous frame
  17548. * @returns a number representing the delta time in ms
  17549. */
  17550. Engine.prototype.getDeltaTime = function () {
  17551. return this._deltaTime;
  17552. };
  17553. Engine.prototype._measureFps = function () {
  17554. this._performanceMonitor.sampleFrame();
  17555. this._fps = this._performanceMonitor.averageFPS;
  17556. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17557. };
  17558. /** @hidden */
  17559. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17560. if (faceIndex === void 0) { faceIndex = -1; }
  17561. if (level === void 0) { level = 0; }
  17562. if (buffer === void 0) { buffer = null; }
  17563. var gl = this._gl;
  17564. if (!this._dummyFramebuffer) {
  17565. var dummy = gl.createFramebuffer();
  17566. if (!dummy) {
  17567. throw new Error("Unable to create dummy framebuffer");
  17568. }
  17569. this._dummyFramebuffer = dummy;
  17570. }
  17571. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17572. if (faceIndex > -1) {
  17573. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17574. }
  17575. else {
  17576. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17577. }
  17578. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17579. switch (readType) {
  17580. case gl.UNSIGNED_BYTE:
  17581. if (!buffer) {
  17582. buffer = new Uint8Array(4 * width * height);
  17583. }
  17584. readType = gl.UNSIGNED_BYTE;
  17585. break;
  17586. default:
  17587. if (!buffer) {
  17588. buffer = new Float32Array(4 * width * height);
  17589. }
  17590. readType = gl.FLOAT;
  17591. break;
  17592. }
  17593. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17594. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17595. return buffer;
  17596. };
  17597. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17598. if (this._webGLVersion > 1) {
  17599. return this._caps.colorBufferFloat;
  17600. }
  17601. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17602. };
  17603. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17604. if (this._webGLVersion > 1) {
  17605. return this._caps.colorBufferFloat;
  17606. }
  17607. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17608. };
  17609. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17610. Engine.prototype._canRenderToFramebuffer = function (type) {
  17611. var gl = this._gl;
  17612. //clear existing errors
  17613. while (gl.getError() !== gl.NO_ERROR) { }
  17614. var successful = true;
  17615. var texture = gl.createTexture();
  17616. gl.bindTexture(gl.TEXTURE_2D, texture);
  17617. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17618. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17619. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17620. var fb = gl.createFramebuffer();
  17621. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17622. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17623. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17624. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17625. successful = successful && (gl.getError() === gl.NO_ERROR);
  17626. //try render by clearing frame buffer's color buffer
  17627. if (successful) {
  17628. gl.clear(gl.COLOR_BUFFER_BIT);
  17629. successful = successful && (gl.getError() === gl.NO_ERROR);
  17630. }
  17631. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17632. if (successful) {
  17633. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17634. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17635. var readFormat = gl.RGBA;
  17636. var readType = gl.UNSIGNED_BYTE;
  17637. var buffer = new Uint8Array(4);
  17638. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17639. successful = successful && (gl.getError() === gl.NO_ERROR);
  17640. }
  17641. //clean up
  17642. gl.deleteTexture(texture);
  17643. gl.deleteFramebuffer(fb);
  17644. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17645. //clear accumulated errors
  17646. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17647. return successful;
  17648. };
  17649. /** @hidden */
  17650. Engine.prototype._getWebGLTextureType = function (type) {
  17651. if (this._webGLVersion === 1) {
  17652. switch (type) {
  17653. case Engine.TEXTURETYPE_FLOAT:
  17654. return this._gl.FLOAT;
  17655. case Engine.TEXTURETYPE_HALF_FLOAT:
  17656. return this._gl.HALF_FLOAT_OES;
  17657. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17658. return this._gl.UNSIGNED_BYTE;
  17659. }
  17660. return this._gl.UNSIGNED_BYTE;
  17661. }
  17662. switch (type) {
  17663. case Engine.TEXTURETYPE_BYTE:
  17664. return this._gl.BYTE;
  17665. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17666. return this._gl.UNSIGNED_BYTE;
  17667. case Engine.TEXTURETYPE_SHORT:
  17668. return this._gl.SHORT;
  17669. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17670. return this._gl.UNSIGNED_SHORT;
  17671. case Engine.TEXTURETYPE_INT:
  17672. return this._gl.INT;
  17673. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17674. return this._gl.UNSIGNED_INT;
  17675. case Engine.TEXTURETYPE_FLOAT:
  17676. return this._gl.FLOAT;
  17677. case Engine.TEXTURETYPE_HALF_FLOAT:
  17678. return this._gl.HALF_FLOAT;
  17679. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17680. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17681. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17682. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17683. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17684. return this._gl.UNSIGNED_SHORT_5_6_5;
  17685. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17686. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17687. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17688. return this._gl.UNSIGNED_INT_24_8;
  17689. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17690. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17691. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17692. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17693. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17694. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17695. }
  17696. return this._gl.UNSIGNED_BYTE;
  17697. };
  17698. ;
  17699. Engine.prototype._getInternalFormat = function (format) {
  17700. var internalFormat = this._gl.RGBA;
  17701. switch (format) {
  17702. case Engine.TEXTUREFORMAT_ALPHA:
  17703. internalFormat = this._gl.ALPHA;
  17704. break;
  17705. case Engine.TEXTUREFORMAT_LUMINANCE:
  17706. internalFormat = this._gl.LUMINANCE;
  17707. break;
  17708. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17709. internalFormat = this._gl.LUMINANCE_ALPHA;
  17710. break;
  17711. case Engine.TEXTUREFORMAT_RED:
  17712. internalFormat = this._gl.RED;
  17713. break;
  17714. case Engine.TEXTUREFORMAT_RG:
  17715. internalFormat = this._gl.RG;
  17716. break;
  17717. case Engine.TEXTUREFORMAT_RGB:
  17718. internalFormat = this._gl.RGB;
  17719. break;
  17720. case Engine.TEXTUREFORMAT_RGBA:
  17721. internalFormat = this._gl.RGBA;
  17722. break;
  17723. }
  17724. if (this._webGLVersion > 1) {
  17725. switch (format) {
  17726. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17727. internalFormat = this._gl.RED_INTEGER;
  17728. break;
  17729. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17730. internalFormat = this._gl.RG_INTEGER;
  17731. break;
  17732. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17733. internalFormat = this._gl.RGB_INTEGER;
  17734. break;
  17735. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17736. internalFormat = this._gl.RGBA_INTEGER;
  17737. break;
  17738. }
  17739. }
  17740. return internalFormat;
  17741. };
  17742. /** @hidden */
  17743. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17744. if (this._webGLVersion === 1) {
  17745. if (format !== undefined) {
  17746. switch (format) {
  17747. case Engine.TEXTUREFORMAT_ALPHA:
  17748. return this._gl.ALPHA;
  17749. case Engine.TEXTUREFORMAT_LUMINANCE:
  17750. return this._gl.LUMINANCE;
  17751. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17752. return this._gl.LUMINANCE_ALPHA;
  17753. }
  17754. }
  17755. return this._gl.RGBA;
  17756. }
  17757. switch (type) {
  17758. case Engine.TEXTURETYPE_BYTE:
  17759. switch (format) {
  17760. case Engine.TEXTUREFORMAT_RED:
  17761. return this._gl.R8_SNORM;
  17762. case Engine.TEXTUREFORMAT_RG:
  17763. return this._gl.RG8_SNORM;
  17764. case Engine.TEXTUREFORMAT_RGB:
  17765. return this._gl.RGB8_SNORM;
  17766. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17767. return this._gl.R8I;
  17768. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17769. return this._gl.RG8I;
  17770. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17771. return this._gl.RGB8I;
  17772. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17773. return this._gl.RGBA8I;
  17774. default:
  17775. return this._gl.RGBA8_SNORM;
  17776. }
  17777. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17778. switch (format) {
  17779. case Engine.TEXTUREFORMAT_RED:
  17780. return this._gl.R8;
  17781. case Engine.TEXTUREFORMAT_RG:
  17782. return this._gl.RG8;
  17783. case Engine.TEXTUREFORMAT_RGB:
  17784. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17785. case Engine.TEXTUREFORMAT_RGBA:
  17786. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17787. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17788. return this._gl.R8UI;
  17789. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17790. return this._gl.RG8UI;
  17791. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17792. return this._gl.RGB8UI;
  17793. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17794. return this._gl.RGBA8UI;
  17795. default:
  17796. return this._gl.RGBA8;
  17797. }
  17798. case Engine.TEXTURETYPE_SHORT:
  17799. switch (format) {
  17800. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17801. return this._gl.R16I;
  17802. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17803. return this._gl.RG16I;
  17804. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17805. return this._gl.RGB16I;
  17806. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17807. return this._gl.RGBA16I;
  17808. default:
  17809. return this._gl.RGBA16I;
  17810. }
  17811. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17812. switch (format) {
  17813. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17814. return this._gl.R16UI;
  17815. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17816. return this._gl.RG16UI;
  17817. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17818. return this._gl.RGB16UI;
  17819. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17820. return this._gl.RGBA16UI;
  17821. default:
  17822. return this._gl.RGBA16UI;
  17823. }
  17824. case Engine.TEXTURETYPE_INT:
  17825. switch (format) {
  17826. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17827. return this._gl.R32I;
  17828. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17829. return this._gl.RG32I;
  17830. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17831. return this._gl.RGB32I;
  17832. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17833. return this._gl.RGBA32I;
  17834. default:
  17835. return this._gl.RGBA32I;
  17836. }
  17837. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17838. switch (format) {
  17839. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17840. return this._gl.R32UI;
  17841. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17842. return this._gl.RG32UI;
  17843. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17844. return this._gl.RGB32UI;
  17845. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17846. return this._gl.RGBA32UI;
  17847. default:
  17848. return this._gl.RGBA32UI;
  17849. }
  17850. case Engine.TEXTURETYPE_FLOAT:
  17851. switch (format) {
  17852. case Engine.TEXTUREFORMAT_RED:
  17853. return this._gl.R32F; // By default. Other possibility is R16F.
  17854. case Engine.TEXTUREFORMAT_RG:
  17855. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17856. case Engine.TEXTUREFORMAT_RGB:
  17857. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17858. case Engine.TEXTUREFORMAT_RGBA:
  17859. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17860. default:
  17861. return this._gl.RGBA32F;
  17862. }
  17863. case Engine.TEXTURETYPE_HALF_FLOAT:
  17864. switch (format) {
  17865. case Engine.TEXTUREFORMAT_RED:
  17866. return this._gl.R16F;
  17867. case Engine.TEXTUREFORMAT_RG:
  17868. return this._gl.RG16F;
  17869. case Engine.TEXTUREFORMAT_RGB:
  17870. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17871. case Engine.TEXTUREFORMAT_RGBA:
  17872. return this._gl.RGBA16F;
  17873. default:
  17874. return this._gl.RGBA16F;
  17875. }
  17876. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17877. return this._gl.RGB565;
  17878. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17879. return this._gl.R11F_G11F_B10F;
  17880. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17881. return this._gl.RGB9_E5;
  17882. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17883. return this._gl.RGBA4;
  17884. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17885. return this._gl.RGB5_A1;
  17886. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17887. switch (format) {
  17888. case Engine.TEXTUREFORMAT_RGBA:
  17889. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17890. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17891. return this._gl.RGB10_A2UI;
  17892. default:
  17893. return this._gl.RGB10_A2;
  17894. }
  17895. }
  17896. return this._gl.RGBA8;
  17897. };
  17898. ;
  17899. /** @hidden */
  17900. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17901. if (type === Engine.TEXTURETYPE_FLOAT) {
  17902. return this._gl.RGBA32F;
  17903. }
  17904. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17905. return this._gl.RGBA16F;
  17906. }
  17907. return this._gl.RGBA8;
  17908. };
  17909. ;
  17910. /** @hidden */
  17911. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17912. var _this = this;
  17913. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17914. this._activeRequests.push(request);
  17915. request.onCompleteObservable.add(function (request) {
  17916. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17917. });
  17918. return request;
  17919. };
  17920. /** @hidden */
  17921. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17922. var _this = this;
  17923. return new Promise(function (resolve, reject) {
  17924. _this._loadFile(url, function (data) {
  17925. resolve(data);
  17926. }, undefined, database, useArrayBuffer, function (request, exception) {
  17927. reject(exception);
  17928. });
  17929. });
  17930. };
  17931. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17932. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17933. var onload = function (data) {
  17934. loadedFiles[index] = data;
  17935. loadedFiles._internalCount++;
  17936. if (loadedFiles._internalCount === 6) {
  17937. onfinish(loadedFiles);
  17938. }
  17939. };
  17940. var onerror = function (request, exception) {
  17941. if (onErrorCallBack && request) {
  17942. onErrorCallBack(request.status + " " + request.statusText, exception);
  17943. }
  17944. };
  17945. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17946. };
  17947. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17948. if (onError === void 0) { onError = null; }
  17949. var loadedFiles = [];
  17950. loadedFiles._internalCount = 0;
  17951. for (var index = 0; index < 6; index++) {
  17952. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17953. }
  17954. };
  17955. // Statics
  17956. /**
  17957. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17958. * @returns true if the engine can be created
  17959. * @ignorenaming
  17960. */
  17961. Engine.isSupported = function () {
  17962. try {
  17963. var tempcanvas = document.createElement("canvas");
  17964. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17965. return gl != null && !!window.WebGLRenderingContext;
  17966. }
  17967. catch (e) {
  17968. return false;
  17969. }
  17970. };
  17971. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17972. Engine.ExceptionList = [
  17973. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17974. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17975. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17976. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17977. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17978. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17979. ];
  17980. /** Gets the list of created engines */
  17981. Engine.Instances = new Array();
  17982. /**
  17983. * Hidden
  17984. */
  17985. Engine._TextureLoaders = [];
  17986. // Const statics
  17987. /** Defines that alpha blending is disabled */
  17988. Engine.ALPHA_DISABLE = 0;
  17989. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17990. Engine.ALPHA_ADD = 1;
  17991. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17992. Engine.ALPHA_COMBINE = 2;
  17993. /** Defines that alpha blending to DEST - SRC * DEST */
  17994. Engine.ALPHA_SUBTRACT = 3;
  17995. /** Defines that alpha blending to SRC * DEST */
  17996. Engine.ALPHA_MULTIPLY = 4;
  17997. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17998. Engine.ALPHA_MAXIMIZED = 5;
  17999. /** Defines that alpha blending to SRC + DEST */
  18000. Engine.ALPHA_ONEONE = 6;
  18001. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18002. Engine.ALPHA_PREMULTIPLIED = 7;
  18003. /**
  18004. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18005. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18006. */
  18007. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18008. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18009. Engine.ALPHA_INTERPOLATE = 9;
  18010. /**
  18011. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18012. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18013. */
  18014. Engine.ALPHA_SCREENMODE = 10;
  18015. /** Defines that the ressource is not delayed*/
  18016. Engine.DELAYLOADSTATE_NONE = 0;
  18017. /** Defines that the ressource was successfully delay loaded */
  18018. Engine.DELAYLOADSTATE_LOADED = 1;
  18019. /** Defines that the ressource is currently delay loading */
  18020. Engine.DELAYLOADSTATE_LOADING = 2;
  18021. /** Defines that the ressource is delayed and has not started loading */
  18022. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18023. // Depht or Stencil test Constants.
  18024. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18025. Engine.NEVER = 0x0200;
  18026. /** 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 */
  18027. Engine.ALWAYS = 0x0207;
  18028. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18029. Engine.LESS = 0x0201;
  18030. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18031. Engine.EQUAL = 0x0202;
  18032. /** 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 */
  18033. Engine.LEQUAL = 0x0203;
  18034. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18035. Engine.GREATER = 0x0204;
  18036. /** 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 */
  18037. Engine.GEQUAL = 0x0206;
  18038. /** 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 */
  18039. Engine.NOTEQUAL = 0x0205;
  18040. // Stencil Actions Constants.
  18041. /** Passed to stencilOperation to specify that stencil value must be kept */
  18042. Engine.KEEP = 0x1E00;
  18043. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18044. Engine.REPLACE = 0x1E01;
  18045. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18046. Engine.INCR = 0x1E02;
  18047. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18048. Engine.DECR = 0x1E03;
  18049. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18050. Engine.INVERT = 0x150A;
  18051. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18052. Engine.INCR_WRAP = 0x8507;
  18053. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18054. Engine.DECR_WRAP = 0x8508;
  18055. /** Texture is not repeating outside of 0..1 UVs */
  18056. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18057. /** Texture is repeating outside of 0..1 UVs */
  18058. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18059. /** Texture is repeating and mirrored */
  18060. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18061. /** ALPHA */
  18062. Engine.TEXTUREFORMAT_ALPHA = 0;
  18063. /** LUMINANCE */
  18064. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18065. /** LUMINANCE_ALPHA */
  18066. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18067. /** RGB */
  18068. Engine.TEXTUREFORMAT_RGB = 4;
  18069. /** RGBA */
  18070. Engine.TEXTUREFORMAT_RGBA = 5;
  18071. /** RED */
  18072. Engine.TEXTUREFORMAT_RED = 6;
  18073. /** RED (2nd reference) */
  18074. Engine.TEXTUREFORMAT_R = 6;
  18075. /** RG */
  18076. Engine.TEXTUREFORMAT_RG = 7;
  18077. /** RED_INTEGER */
  18078. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18079. /** RED_INTEGER (2nd reference) */
  18080. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18081. /** RG_INTEGER */
  18082. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18083. /** RGB_INTEGER */
  18084. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18085. /** RGBA_INTEGER */
  18086. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18087. /** UNSIGNED_BYTE */
  18088. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18089. /** UNSIGNED_BYTE (2nd reference) */
  18090. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18091. /** FLOAT */
  18092. Engine.TEXTURETYPE_FLOAT = 1;
  18093. /** HALF_FLOAT */
  18094. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18095. /** BYTE */
  18096. Engine.TEXTURETYPE_BYTE = 3;
  18097. /** SHORT */
  18098. Engine.TEXTURETYPE_SHORT = 4;
  18099. /** UNSIGNED_SHORT */
  18100. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18101. /** INT */
  18102. Engine.TEXTURETYPE_INT = 6;
  18103. /** UNSIGNED_INT */
  18104. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18105. /** UNSIGNED_SHORT_4_4_4_4 */
  18106. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18107. /** UNSIGNED_SHORT_5_5_5_1 */
  18108. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18109. /** UNSIGNED_SHORT_5_6_5 */
  18110. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18111. /** UNSIGNED_INT_2_10_10_10_REV */
  18112. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18113. /** UNSIGNED_INT_24_8 */
  18114. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18115. /** UNSIGNED_INT_10F_11F_11F_REV */
  18116. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18117. /** UNSIGNED_INT_5_9_9_9_REV */
  18118. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18119. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18120. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18121. /** nearest is mag = nearest and min = nearest and mip = linear */
  18122. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18123. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18124. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18125. /** Trilinear is mag = linear and min = linear and mip = linear */
  18126. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18127. /** nearest is mag = nearest and min = nearest and mip = linear */
  18128. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18129. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18130. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18131. /** Trilinear is mag = linear and min = linear and mip = linear */
  18132. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18133. /** mag = nearest and min = nearest and mip = nearest */
  18134. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18135. /** mag = nearest and min = linear and mip = nearest */
  18136. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18137. /** mag = nearest and min = linear and mip = linear */
  18138. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18139. /** mag = nearest and min = linear and mip = none */
  18140. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18141. /** mag = nearest and min = nearest and mip = none */
  18142. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18143. /** mag = linear and min = nearest and mip = nearest */
  18144. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18145. /** mag = linear and min = nearest and mip = linear */
  18146. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18147. /** mag = linear and min = linear and mip = none */
  18148. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18149. /** mag = linear and min = nearest and mip = none */
  18150. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18151. /** Explicit coordinates mode */
  18152. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18153. /** Spherical coordinates mode */
  18154. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18155. /** Planar coordinates mode */
  18156. Engine.TEXTURE_PLANAR_MODE = 2;
  18157. /** Cubic coordinates mode */
  18158. Engine.TEXTURE_CUBIC_MODE = 3;
  18159. /** Projection coordinates mode */
  18160. Engine.TEXTURE_PROJECTION_MODE = 4;
  18161. /** Skybox coordinates mode */
  18162. Engine.TEXTURE_SKYBOX_MODE = 5;
  18163. /** Inverse Cubic coordinates mode */
  18164. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18165. /** Equirectangular coordinates mode */
  18166. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18167. /** Equirectangular Fixed coordinates mode */
  18168. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18169. /** Equirectangular Fixed Mirrored coordinates mode */
  18170. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18171. // Texture rescaling mode
  18172. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18173. Engine.SCALEMODE_FLOOR = 1;
  18174. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18175. Engine.SCALEMODE_NEAREST = 2;
  18176. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18177. Engine.SCALEMODE_CEILING = 3;
  18178. // Updatable statics so stick with vars here
  18179. /**
  18180. * Gets or sets the epsilon value used by collision engine
  18181. */
  18182. Engine.CollisionsEpsilon = 0.001;
  18183. /**
  18184. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18185. */
  18186. Engine.CodeRepository = "src/";
  18187. /**
  18188. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18189. */
  18190. Engine.ShadersRepository = "src/Shaders/";
  18191. return Engine;
  18192. }());
  18193. BABYLON.Engine = Engine;
  18194. })(BABYLON || (BABYLON = {}));
  18195. //# sourceMappingURL=babylon.engine.js.map
  18196. var BABYLON;
  18197. (function (BABYLON) {
  18198. /**
  18199. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18200. */
  18201. var Node = /** @class */ (function () {
  18202. /**
  18203. * Creates a new Node
  18204. * @param {string} name - the name and id to be given to this node
  18205. * @param {BABYLON.Scene} the scene this node will be added to
  18206. */
  18207. function Node(name, scene) {
  18208. if (scene === void 0) { scene = null; }
  18209. /**
  18210. * Gets or sets a string used to store user defined state for the node
  18211. */
  18212. this.state = "";
  18213. /**
  18214. * Gets or sets an object used to store user defined information for the node
  18215. */
  18216. this.metadata = null;
  18217. /**
  18218. * Gets or sets a boolean used to define if the node must be serialized
  18219. */
  18220. this.doNotSerialize = false;
  18221. /** @hidden */
  18222. this._isDisposed = false;
  18223. /**
  18224. * Gets a list of Animations associated with the node
  18225. */
  18226. this.animations = new Array();
  18227. this._ranges = {};
  18228. this._isEnabled = true;
  18229. this._isParentEnabled = true;
  18230. this._isReady = true;
  18231. /** @hidden */
  18232. this._currentRenderId = -1;
  18233. this._parentRenderId = -1;
  18234. this._childRenderId = -1;
  18235. /** @hidden */
  18236. this._worldMatrix = BABYLON.Matrix.Identity();
  18237. /** @hidden */
  18238. this._worldMatrixDeterminant = 0;
  18239. /** @hidden */
  18240. this._sceneRootNodesIndex = -1;
  18241. this._animationPropertiesOverride = null;
  18242. /**
  18243. * An event triggered when the mesh is disposed
  18244. */
  18245. this.onDisposeObservable = new BABYLON.Observable();
  18246. // Behaviors
  18247. this._behaviors = new Array();
  18248. this.name = name;
  18249. this.id = name;
  18250. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18251. this.uniqueId = this._scene.getUniqueId();
  18252. this._initCache();
  18253. this.addToSceneRootNodes();
  18254. }
  18255. /**
  18256. * Add a new node constructor
  18257. * @param type defines the type name of the node to construct
  18258. * @param constructorFunc defines the constructor function
  18259. */
  18260. Node.AddNodeConstructor = function (type, constructorFunc) {
  18261. this._NodeConstructors[type] = constructorFunc;
  18262. };
  18263. /**
  18264. * Returns a node constructor based on type name
  18265. * @param type defines the type name
  18266. * @param name defines the new node name
  18267. * @param scene defines the hosting scene
  18268. * @param options defines optional options to transmit to constructors
  18269. * @returns the new constructor or null
  18270. */
  18271. Node.Construct = function (type, name, scene, options) {
  18272. var constructorFunc = this._NodeConstructors[type];
  18273. if (!constructorFunc) {
  18274. return null;
  18275. }
  18276. return constructorFunc(name, scene, options);
  18277. };
  18278. /**
  18279. * Gets a boolean indicating if the node has been disposed
  18280. * @returns true if the node was disposed
  18281. */
  18282. Node.prototype.isDisposed = function () {
  18283. return this._isDisposed;
  18284. };
  18285. Object.defineProperty(Node.prototype, "parent", {
  18286. get: function () {
  18287. return this._parentNode;
  18288. },
  18289. /**
  18290. * Gets or sets the parent of the node
  18291. */
  18292. set: function (parent) {
  18293. if (this._parentNode === parent) {
  18294. return;
  18295. }
  18296. var previousParentNode = this._parentNode;
  18297. // Remove self from list of children of parent
  18298. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18299. var index = this._parentNode._children.indexOf(this);
  18300. if (index !== -1) {
  18301. this._parentNode._children.splice(index, 1);
  18302. }
  18303. if (!parent) {
  18304. this.addToSceneRootNodes();
  18305. }
  18306. }
  18307. // Store new parent
  18308. this._parentNode = parent;
  18309. // Add as child to new parent
  18310. if (this._parentNode) {
  18311. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18312. this._parentNode._children = new Array();
  18313. }
  18314. this._parentNode._children.push(this);
  18315. if (!previousParentNode) {
  18316. this.removeFromSceneRootNodes();
  18317. }
  18318. }
  18319. // Enabled state
  18320. this._syncParentEnabledState();
  18321. },
  18322. enumerable: true,
  18323. configurable: true
  18324. });
  18325. Node.prototype.addToSceneRootNodes = function () {
  18326. if (this._sceneRootNodesIndex === -1) {
  18327. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18328. this._scene.rootNodes.push(this);
  18329. }
  18330. };
  18331. Node.prototype.removeFromSceneRootNodes = function () {
  18332. if (this._sceneRootNodesIndex !== -1) {
  18333. var rootNodes = this._scene.rootNodes;
  18334. var lastIdx = rootNodes.length - 1;
  18335. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18336. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18337. this._scene.rootNodes.pop();
  18338. this._sceneRootNodesIndex = -1;
  18339. }
  18340. };
  18341. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18342. /**
  18343. * Gets or sets the animation properties override
  18344. */
  18345. get: function () {
  18346. if (!this._animationPropertiesOverride) {
  18347. return this._scene.animationPropertiesOverride;
  18348. }
  18349. return this._animationPropertiesOverride;
  18350. },
  18351. set: function (value) {
  18352. this._animationPropertiesOverride = value;
  18353. },
  18354. enumerable: true,
  18355. configurable: true
  18356. });
  18357. /**
  18358. * Gets a string idenfifying the name of the class
  18359. * @returns "Node" string
  18360. */
  18361. Node.prototype.getClassName = function () {
  18362. return "Node";
  18363. };
  18364. Object.defineProperty(Node.prototype, "onDispose", {
  18365. /**
  18366. * Sets a callback that will be raised when the node will be disposed
  18367. */
  18368. set: function (callback) {
  18369. if (this._onDisposeObserver) {
  18370. this.onDisposeObservable.remove(this._onDisposeObserver);
  18371. }
  18372. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18373. },
  18374. enumerable: true,
  18375. configurable: true
  18376. });
  18377. /**
  18378. * Gets the scene of the node
  18379. * @returns a {BABYLON.Scene}
  18380. */
  18381. Node.prototype.getScene = function () {
  18382. return this._scene;
  18383. };
  18384. /**
  18385. * Gets the engine of the node
  18386. * @returns a {BABYLON.Engine}
  18387. */
  18388. Node.prototype.getEngine = function () {
  18389. return this._scene.getEngine();
  18390. };
  18391. /**
  18392. * Attach a behavior to the node
  18393. * @see http://doc.babylonjs.com/features/behaviour
  18394. * @param behavior defines the behavior to attach
  18395. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18396. * @returns the current Node
  18397. */
  18398. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18399. var _this = this;
  18400. if (attachImmediately === void 0) { attachImmediately = false; }
  18401. var index = this._behaviors.indexOf(behavior);
  18402. if (index !== -1) {
  18403. return this;
  18404. }
  18405. behavior.init();
  18406. if (this._scene.isLoading && !attachImmediately) {
  18407. // We defer the attach when the scene will be loaded
  18408. this._scene.onDataLoadedObservable.addOnce(function () {
  18409. behavior.attach(_this);
  18410. });
  18411. }
  18412. else {
  18413. behavior.attach(this);
  18414. }
  18415. this._behaviors.push(behavior);
  18416. return this;
  18417. };
  18418. /**
  18419. * Remove an attached behavior
  18420. * @see http://doc.babylonjs.com/features/behaviour
  18421. * @param behavior defines the behavior to attach
  18422. * @returns the current Node
  18423. */
  18424. Node.prototype.removeBehavior = function (behavior) {
  18425. var index = this._behaviors.indexOf(behavior);
  18426. if (index === -1) {
  18427. return this;
  18428. }
  18429. this._behaviors[index].detach();
  18430. this._behaviors.splice(index, 1);
  18431. return this;
  18432. };
  18433. Object.defineProperty(Node.prototype, "behaviors", {
  18434. /**
  18435. * Gets the list of attached behaviors
  18436. * @see http://doc.babylonjs.com/features/behaviour
  18437. */
  18438. get: function () {
  18439. return this._behaviors;
  18440. },
  18441. enumerable: true,
  18442. configurable: true
  18443. });
  18444. /**
  18445. * Gets an attached behavior by name
  18446. * @param name defines the name of the behavior to look for
  18447. * @see http://doc.babylonjs.com/features/behaviour
  18448. * @returns null if behavior was not found else the requested behavior
  18449. */
  18450. Node.prototype.getBehaviorByName = function (name) {
  18451. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18452. var behavior = _a[_i];
  18453. if (behavior.name === name) {
  18454. return behavior;
  18455. }
  18456. }
  18457. return null;
  18458. };
  18459. /**
  18460. * Returns the latest update of the World matrix
  18461. * @returns a Matrix
  18462. */
  18463. Node.prototype.getWorldMatrix = function () {
  18464. if (this._currentRenderId !== this._scene.getRenderId()) {
  18465. this.computeWorldMatrix();
  18466. }
  18467. return this._worldMatrix;
  18468. };
  18469. /** @hidden */
  18470. Node.prototype._getWorldMatrixDeterminant = function () {
  18471. return this._worldMatrixDeterminant;
  18472. };
  18473. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18474. /**
  18475. * Returns directly the latest state of the mesh World matrix.
  18476. * A Matrix is returned.
  18477. */
  18478. get: function () {
  18479. return this._worldMatrix;
  18480. },
  18481. enumerable: true,
  18482. configurable: true
  18483. });
  18484. // override it in derived class if you add new variables to the cache
  18485. // and call the parent class method
  18486. /** @hidden */
  18487. Node.prototype._initCache = function () {
  18488. this._cache = {};
  18489. this._cache.parent = undefined;
  18490. };
  18491. /** @hidden */
  18492. Node.prototype.updateCache = function (force) {
  18493. if (!force && this.isSynchronized())
  18494. return;
  18495. this._cache.parent = this.parent;
  18496. this._updateCache();
  18497. };
  18498. // override it in derived class if you add new variables to the cache
  18499. // and call the parent class method if !ignoreParentClass
  18500. /** @hidden */
  18501. Node.prototype._updateCache = function (ignoreParentClass) {
  18502. };
  18503. // override it in derived class if you add new variables to the cache
  18504. /** @hidden */
  18505. Node.prototype._isSynchronized = function () {
  18506. return true;
  18507. };
  18508. /** @hidden */
  18509. Node.prototype._markSyncedWithParent = function () {
  18510. if (this._parentNode) {
  18511. this._parentRenderId = this._parentNode._childRenderId;
  18512. }
  18513. };
  18514. /** @hidden */
  18515. Node.prototype.isSynchronizedWithParent = function () {
  18516. if (!this._parentNode) {
  18517. return true;
  18518. }
  18519. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18520. return false;
  18521. }
  18522. return this._parentNode.isSynchronized();
  18523. };
  18524. /** @hidden */
  18525. Node.prototype.isSynchronized = function () {
  18526. if (this._cache.parent != this._parentNode) {
  18527. this._cache.parent = this._parentNode;
  18528. return false;
  18529. }
  18530. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18531. return false;
  18532. }
  18533. return this._isSynchronized();
  18534. };
  18535. /**
  18536. * Is this node ready to be used/rendered
  18537. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18538. * @return true if the node is ready
  18539. */
  18540. Node.prototype.isReady = function (completeCheck) {
  18541. if (completeCheck === void 0) { completeCheck = false; }
  18542. return this._isReady;
  18543. };
  18544. /**
  18545. * Is this node enabled?
  18546. * 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
  18547. * @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
  18548. * @return whether this node (and its parent) is enabled
  18549. */
  18550. Node.prototype.isEnabled = function (checkAncestors) {
  18551. if (checkAncestors === void 0) { checkAncestors = true; }
  18552. if (checkAncestors === false) {
  18553. return this._isEnabled;
  18554. }
  18555. if (!this._isEnabled) {
  18556. return false;
  18557. }
  18558. return this._isParentEnabled;
  18559. };
  18560. /** @hidden */
  18561. Node.prototype._syncParentEnabledState = function () {
  18562. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18563. if (this._children) {
  18564. this._children.forEach(function (c) {
  18565. c._syncParentEnabledState(); // Force children to update accordingly
  18566. });
  18567. }
  18568. };
  18569. /**
  18570. * Set the enabled state of this node
  18571. * @param value defines the new enabled state
  18572. */
  18573. Node.prototype.setEnabled = function (value) {
  18574. this._isEnabled = value;
  18575. this._syncParentEnabledState();
  18576. };
  18577. /**
  18578. * Is this node a descendant of the given node?
  18579. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18580. * @param ancestor defines the parent node to inspect
  18581. * @returns a boolean indicating if this node is a descendant of the given node
  18582. */
  18583. Node.prototype.isDescendantOf = function (ancestor) {
  18584. if (this.parent) {
  18585. if (this.parent === ancestor) {
  18586. return true;
  18587. }
  18588. return this.parent.isDescendantOf(ancestor);
  18589. }
  18590. return false;
  18591. };
  18592. /** @hidden */
  18593. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18594. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18595. if (!this._children) {
  18596. return;
  18597. }
  18598. for (var index = 0; index < this._children.length; index++) {
  18599. var item = this._children[index];
  18600. if (!predicate || predicate(item)) {
  18601. results.push(item);
  18602. }
  18603. if (!directDescendantsOnly) {
  18604. item._getDescendants(results, false, predicate);
  18605. }
  18606. }
  18607. };
  18608. /**
  18609. * Will return all nodes that have this node as ascendant
  18610. * @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
  18611. * @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
  18612. * @return all children nodes of all types
  18613. */
  18614. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18615. var results = new Array();
  18616. this._getDescendants(results, directDescendantsOnly, predicate);
  18617. return results;
  18618. };
  18619. /**
  18620. * Get all child-meshes of this node
  18621. * @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
  18622. * @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
  18623. * @returns an array of {BABYLON.AbstractMesh}
  18624. */
  18625. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18626. var results = [];
  18627. this._getDescendants(results, directDescendantsOnly, function (node) {
  18628. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18629. });
  18630. return results;
  18631. };
  18632. /**
  18633. * Get all child-transformNodes of this node
  18634. * @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
  18635. * @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
  18636. * @returns an array of {BABYLON.TransformNode}
  18637. */
  18638. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18639. var results = [];
  18640. this._getDescendants(results, directDescendantsOnly, function (node) {
  18641. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18642. });
  18643. return results;
  18644. };
  18645. /**
  18646. * Get all direct children of this node
  18647. * @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
  18648. * @returns an array of {BABYLON.Node}
  18649. */
  18650. Node.prototype.getChildren = function (predicate) {
  18651. return this.getDescendants(true, predicate);
  18652. };
  18653. /** @hidden */
  18654. Node.prototype._setReady = function (state) {
  18655. if (state === this._isReady) {
  18656. return;
  18657. }
  18658. if (!state) {
  18659. this._isReady = false;
  18660. return;
  18661. }
  18662. if (this.onReady) {
  18663. this.onReady(this);
  18664. }
  18665. this._isReady = true;
  18666. };
  18667. /**
  18668. * Get an animation by name
  18669. * @param name defines the name of the animation to look for
  18670. * @returns null if not found else the requested animation
  18671. */
  18672. Node.prototype.getAnimationByName = function (name) {
  18673. for (var i = 0; i < this.animations.length; i++) {
  18674. var animation = this.animations[i];
  18675. if (animation.name === name) {
  18676. return animation;
  18677. }
  18678. }
  18679. return null;
  18680. };
  18681. /**
  18682. * Creates an animation range for this node
  18683. * @param name defines the name of the range
  18684. * @param from defines the starting key
  18685. * @param to defines the end key
  18686. */
  18687. Node.prototype.createAnimationRange = function (name, from, to) {
  18688. // check name not already in use
  18689. if (!this._ranges[name]) {
  18690. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18691. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18692. if (this.animations[i]) {
  18693. this.animations[i].createRange(name, from, to);
  18694. }
  18695. }
  18696. }
  18697. };
  18698. /**
  18699. * Delete a specific animation range
  18700. * @param name defines the name of the range to delete
  18701. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18702. */
  18703. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18704. if (deleteFrames === void 0) { deleteFrames = true; }
  18705. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18706. if (this.animations[i]) {
  18707. this.animations[i].deleteRange(name, deleteFrames);
  18708. }
  18709. }
  18710. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18711. };
  18712. /**
  18713. * Get an animation range by name
  18714. * @param name defines the name of the animation range to look for
  18715. * @returns null if not found else the requested animation range
  18716. */
  18717. Node.prototype.getAnimationRange = function (name) {
  18718. return this._ranges[name];
  18719. };
  18720. /**
  18721. * Will start the animation sequence
  18722. * @param name defines the range frames for animation sequence
  18723. * @param loop defines if the animation should loop (false by default)
  18724. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18725. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18726. * @returns the object created for this animation. If range does not exist, it will return null
  18727. */
  18728. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18729. var range = this.getAnimationRange(name);
  18730. if (!range) {
  18731. return null;
  18732. }
  18733. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18734. };
  18735. /**
  18736. * Serialize animation ranges into a JSON compatible object
  18737. * @returns serialization object
  18738. */
  18739. Node.prototype.serializeAnimationRanges = function () {
  18740. var serializationRanges = [];
  18741. for (var name in this._ranges) {
  18742. var localRange = this._ranges[name];
  18743. if (!localRange) {
  18744. continue;
  18745. }
  18746. var range = {};
  18747. range.name = name;
  18748. range.from = localRange.from;
  18749. range.to = localRange.to;
  18750. serializationRanges.push(range);
  18751. }
  18752. return serializationRanges;
  18753. };
  18754. /**
  18755. * Computes the world matrix of the node
  18756. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18757. * @returns the world matrix
  18758. */
  18759. Node.prototype.computeWorldMatrix = function (force) {
  18760. if (!this._worldMatrix) {
  18761. this._worldMatrix = BABYLON.Matrix.Identity();
  18762. }
  18763. return this._worldMatrix;
  18764. };
  18765. /**
  18766. * Releases resources associated with this node.
  18767. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18768. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18769. */
  18770. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18771. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18772. if (!doNotRecurse) {
  18773. var nodes = this.getDescendants(true);
  18774. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18775. var node = nodes_1[_i];
  18776. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18777. }
  18778. }
  18779. else {
  18780. var transformNodes = this.getChildTransformNodes(true);
  18781. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18782. var transformNode = transformNodes_1[_a];
  18783. transformNode.parent = null;
  18784. transformNode.computeWorldMatrix(true);
  18785. }
  18786. }
  18787. if (!this.parent) {
  18788. this.removeFromSceneRootNodes();
  18789. }
  18790. else {
  18791. this.parent = null;
  18792. }
  18793. // Callback
  18794. this.onDisposeObservable.notifyObservers(this);
  18795. this.onDisposeObservable.clear();
  18796. // Behaviors
  18797. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18798. var behavior = _c[_b];
  18799. behavior.detach();
  18800. }
  18801. this._behaviors = [];
  18802. this._isDisposed = true;
  18803. };
  18804. /**
  18805. * Parse animation range data from a serialization object and store them into a given node
  18806. * @param node defines where to store the animation ranges
  18807. * @param parsedNode defines the serialization object to read data from
  18808. * @param scene defines the hosting scene
  18809. */
  18810. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18811. if (parsedNode.ranges) {
  18812. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18813. var data = parsedNode.ranges[index];
  18814. node.createAnimationRange(data.name, data.from, data.to);
  18815. }
  18816. }
  18817. };
  18818. Node._NodeConstructors = {};
  18819. __decorate([
  18820. BABYLON.serialize()
  18821. ], Node.prototype, "name", void 0);
  18822. __decorate([
  18823. BABYLON.serialize()
  18824. ], Node.prototype, "id", void 0);
  18825. __decorate([
  18826. BABYLON.serialize()
  18827. ], Node.prototype, "uniqueId", void 0);
  18828. __decorate([
  18829. BABYLON.serialize()
  18830. ], Node.prototype, "state", void 0);
  18831. __decorate([
  18832. BABYLON.serialize()
  18833. ], Node.prototype, "metadata", void 0);
  18834. return Node;
  18835. }());
  18836. BABYLON.Node = Node;
  18837. })(BABYLON || (BABYLON = {}));
  18838. //# sourceMappingURL=babylon.node.js.map
  18839. var BABYLON;
  18840. (function (BABYLON) {
  18841. // This matrix is used as a value to reset the bounding box.
  18842. var _identityMatrix = BABYLON.Matrix.Identity();
  18843. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18844. /**
  18845. * Class used to store bounding sphere information
  18846. */
  18847. var BoundingSphere = /** @class */ (function () {
  18848. /**
  18849. * Creates a new bounding sphere
  18850. * @param min defines the minimum vector (in local space)
  18851. * @param max defines the maximum vector (in local space)
  18852. */
  18853. function BoundingSphere(min, max) {
  18854. this.center = BABYLON.Vector3.Zero();
  18855. this.centerWorld = BABYLON.Vector3.Zero();
  18856. this.reConstruct(min, max);
  18857. }
  18858. /**
  18859. * Recreates the entire bounding sphere from scratch
  18860. * @param min defines the new minimum vector (in local space)
  18861. * @param max defines the new maximum vector (in local space)
  18862. */
  18863. BoundingSphere.prototype.reConstruct = function (min, max) {
  18864. this.minimum = min.clone();
  18865. this.maximum = max.clone();
  18866. var distance = BABYLON.Vector3.Distance(min, max);
  18867. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18868. this.radius = distance * 0.5;
  18869. this.centerWorld.set(0, 0, 0);
  18870. this._update(_identityMatrix);
  18871. };
  18872. /**
  18873. * Scale the current bounding sphere by applying a scale factor
  18874. * @param factor defines the scale factor to apply
  18875. * @returns the current bounding box
  18876. */
  18877. BoundingSphere.prototype.scale = function (factor) {
  18878. var newRadius = this.radius * factor;
  18879. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18880. var min = this.center.subtract(_tempRadiusVector);
  18881. var max = this.center.add(_tempRadiusVector);
  18882. this.reConstruct(min, max);
  18883. return this;
  18884. };
  18885. // Methods
  18886. /** @hidden */
  18887. BoundingSphere.prototype._update = function (world) {
  18888. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18889. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18890. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18891. };
  18892. /**
  18893. * Tests if the bounding sphere is intersecting the frustum planes
  18894. * @param frustumPlanes defines the frustum planes to test
  18895. * @returns true if there is an intersection
  18896. */
  18897. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18898. for (var i = 0; i < 6; i++) {
  18899. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18900. return false;
  18901. }
  18902. return true;
  18903. };
  18904. /**
  18905. * Tests if a point is inside the bounding sphere
  18906. * @param point defines the point to test
  18907. * @returns true if the point is inside the bounding sphere
  18908. */
  18909. BoundingSphere.prototype.intersectsPoint = function (point) {
  18910. var x = this.centerWorld.x - point.x;
  18911. var y = this.centerWorld.y - point.y;
  18912. var z = this.centerWorld.z - point.z;
  18913. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18914. if (this.radiusWorld < distance)
  18915. return false;
  18916. return true;
  18917. };
  18918. // Statics
  18919. /**
  18920. * Checks if two sphere intersct
  18921. * @param sphere0 sphere 0
  18922. * @param sphere1 sphere 1
  18923. * @returns true if the speres intersect
  18924. */
  18925. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18926. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18927. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18928. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18929. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18930. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18931. return false;
  18932. return true;
  18933. };
  18934. return BoundingSphere;
  18935. }());
  18936. BABYLON.BoundingSphere = BoundingSphere;
  18937. })(BABYLON || (BABYLON = {}));
  18938. //# sourceMappingURL=babylon.boundingSphere.js.map
  18939. var BABYLON;
  18940. (function (BABYLON) {
  18941. /**
  18942. * Class used to store bounding box information
  18943. */
  18944. var BoundingBox = /** @class */ (function () {
  18945. /**
  18946. * Creates a new bounding box
  18947. * @param min defines the minimum vector (in local space)
  18948. * @param max defines the maximum vector (in local space)
  18949. */
  18950. function BoundingBox(min, max) {
  18951. /**
  18952. * Gets the 8 vectors representing the bounding box in world space
  18953. */
  18954. this.vectorsWorld = new Array();
  18955. this.reConstruct(min, max);
  18956. }
  18957. // Methods
  18958. /**
  18959. * Recreates the entire bounding box from scratch
  18960. * @param min defines the new minimum vector (in local space)
  18961. * @param max defines the new maximum vector (in local space)
  18962. */
  18963. BoundingBox.prototype.reConstruct = function (min, max) {
  18964. this.minimum = min.clone();
  18965. this.maximum = max.clone();
  18966. // Bounding vectors
  18967. this.vectors = [
  18968. this.minimum.clone(),
  18969. this.maximum.clone(),
  18970. this.minimum.clone(),
  18971. this.minimum.clone(),
  18972. this.minimum.clone(),
  18973. this.maximum.clone(),
  18974. this.maximum.clone(),
  18975. this.maximum.clone()
  18976. ];
  18977. this.vectors[2].x = this.maximum.x;
  18978. this.vectors[3].y = this.maximum.y;
  18979. this.vectors[4].z = this.maximum.z;
  18980. this.vectors[5].z = this.minimum.z;
  18981. this.vectors[6].x = this.minimum.x;
  18982. this.vectors[7].y = this.minimum.y;
  18983. // OBB
  18984. this.center = this.maximum.add(this.minimum).scale(0.5);
  18985. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18986. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18987. // World
  18988. for (var index = 0; index < this.vectors.length; index++) {
  18989. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18990. }
  18991. this.minimumWorld = BABYLON.Vector3.Zero();
  18992. this.maximumWorld = BABYLON.Vector3.Zero();
  18993. this.centerWorld = BABYLON.Vector3.Zero();
  18994. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18995. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18996. };
  18997. /**
  18998. * Scale the current bounding box by applying a scale factor
  18999. * @param factor defines the scale factor to apply
  19000. * @returns the current bounding box
  19001. */
  19002. BoundingBox.prototype.scale = function (factor) {
  19003. var diff = this.maximum.subtract(this.minimum);
  19004. var distance = diff.length() * factor;
  19005. diff.normalize();
  19006. var newRadius = diff.scale(distance / 2);
  19007. var min = this.center.subtract(newRadius);
  19008. var max = this.center.add(newRadius);
  19009. this.reConstruct(min, max);
  19010. return this;
  19011. };
  19012. /**
  19013. * Gets the world matrix of the bounding box
  19014. * @returns a matrix
  19015. */
  19016. BoundingBox.prototype.getWorldMatrix = function () {
  19017. return this._worldMatrix;
  19018. };
  19019. /**
  19020. * Sets the world matrix stored in the bounding box
  19021. * @param matrix defines the matrix to store
  19022. * @returns current bounding box
  19023. */
  19024. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19025. this._worldMatrix.copyFrom(matrix);
  19026. return this;
  19027. };
  19028. /** @hidden */
  19029. BoundingBox.prototype._update = function (world) {
  19030. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19031. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19032. for (var index = 0; index < this.vectors.length; index++) {
  19033. var v = this.vectorsWorld[index];
  19034. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19035. if (v.x < this.minimumWorld.x)
  19036. this.minimumWorld.x = v.x;
  19037. if (v.y < this.minimumWorld.y)
  19038. this.minimumWorld.y = v.y;
  19039. if (v.z < this.minimumWorld.z)
  19040. this.minimumWorld.z = v.z;
  19041. if (v.x > this.maximumWorld.x)
  19042. this.maximumWorld.x = v.x;
  19043. if (v.y > this.maximumWorld.y)
  19044. this.maximumWorld.y = v.y;
  19045. if (v.z > this.maximumWorld.z)
  19046. this.maximumWorld.z = v.z;
  19047. }
  19048. // Extend
  19049. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19050. this.extendSizeWorld.scaleInPlace(0.5);
  19051. // OBB
  19052. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19053. this.centerWorld.scaleInPlace(0.5);
  19054. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19055. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19056. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19057. this._worldMatrix = world;
  19058. };
  19059. /**
  19060. * Tests if the bounding box is intersecting the frustum planes
  19061. * @param frustumPlanes defines the frustum planes to test
  19062. * @returns true if there is an intersection
  19063. */
  19064. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19065. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19066. };
  19067. /**
  19068. * Tests if the bounding box is entirely inside the frustum planes
  19069. * @param frustumPlanes defines the frustum planes to test
  19070. * @returns true if there is an inclusion
  19071. */
  19072. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19073. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19074. };
  19075. /**
  19076. * Tests if a point is inside the bounding box
  19077. * @param point defines the point to test
  19078. * @returns true if the point is inside the bounding box
  19079. */
  19080. BoundingBox.prototype.intersectsPoint = function (point) {
  19081. var delta = -BABYLON.Epsilon;
  19082. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  19083. return false;
  19084. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  19085. return false;
  19086. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  19087. return false;
  19088. return true;
  19089. };
  19090. /**
  19091. * Tests if the bounding box intersects with a bounding sphere
  19092. * @param sphere defines the sphere to test
  19093. * @returns true if there is an intersection
  19094. */
  19095. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19096. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19097. };
  19098. /**
  19099. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19100. * @param min defines the min vector to use
  19101. * @param max defines the max vector to use
  19102. * @returns true if there is an intersection
  19103. */
  19104. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19105. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  19106. return false;
  19107. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  19108. return false;
  19109. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  19110. return false;
  19111. return true;
  19112. };
  19113. // Statics
  19114. /**
  19115. * Tests if two bounding boxes are intersections
  19116. * @param box0 defines the first box to test
  19117. * @param box1 defines the second box to test
  19118. * @returns true if there is an intersection
  19119. */
  19120. BoundingBox.Intersects = function (box0, box1) {
  19121. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  19122. return false;
  19123. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  19124. return false;
  19125. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  19126. return false;
  19127. return true;
  19128. };
  19129. /**
  19130. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19131. * @param minPoint defines the minimum vector of the bounding box
  19132. * @param maxPoint defines the maximum vector of the bounding box
  19133. * @param sphereCenter defines the sphere center
  19134. * @param sphereRadius defines the sphere radius
  19135. * @returns true if there is an intersection
  19136. */
  19137. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19138. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19139. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19140. return (num <= (sphereRadius * sphereRadius));
  19141. };
  19142. /**
  19143. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19144. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19145. * @param frustumPlanes defines the frustum planes to test
  19146. * @return true if there is an inclusion
  19147. */
  19148. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19149. for (var p = 0; p < 6; p++) {
  19150. for (var i = 0; i < 8; i++) {
  19151. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19152. return false;
  19153. }
  19154. }
  19155. }
  19156. return true;
  19157. };
  19158. /**
  19159. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19160. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19161. * @param frustumPlanes defines the frustum planes to test
  19162. * @return true if there is an intersection
  19163. */
  19164. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19165. for (var p = 0; p < 6; p++) {
  19166. var inCount = 8;
  19167. for (var i = 0; i < 8; i++) {
  19168. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19169. --inCount;
  19170. }
  19171. else {
  19172. break;
  19173. }
  19174. }
  19175. if (inCount === 0)
  19176. return false;
  19177. }
  19178. return true;
  19179. };
  19180. return BoundingBox;
  19181. }());
  19182. BABYLON.BoundingBox = BoundingBox;
  19183. })(BABYLON || (BABYLON = {}));
  19184. //# sourceMappingURL=babylon.boundingBox.js.map
  19185. var BABYLON;
  19186. (function (BABYLON) {
  19187. var computeBoxExtents = function (axis, box) {
  19188. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19189. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19190. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19191. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19192. var r = r0 + r1 + r2;
  19193. return {
  19194. min: p - r,
  19195. max: p + r
  19196. };
  19197. };
  19198. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19199. var axisOverlap = function (axis, box0, box1) {
  19200. var result0 = computeBoxExtents(axis, box0);
  19201. var result1 = computeBoxExtents(axis, box1);
  19202. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19203. };
  19204. /**
  19205. * Info for a bounding data of a mesh
  19206. */
  19207. var BoundingInfo = /** @class */ (function () {
  19208. /**
  19209. * Constructs bounding info
  19210. * @param minimum min vector of the bounding box/sphere
  19211. * @param maximum max vector of the bounding box/sphere
  19212. */
  19213. function BoundingInfo(
  19214. /**
  19215. * min vector of the bounding box/sphere
  19216. */
  19217. minimum,
  19218. /**
  19219. * max vector of the bounding box/sphere
  19220. */
  19221. maximum) {
  19222. this.minimum = minimum;
  19223. this.maximum = maximum;
  19224. this._isLocked = false;
  19225. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19226. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19227. }
  19228. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19229. /**
  19230. * If the info is locked and won't be updated to avoid perf overhead
  19231. */
  19232. get: function () {
  19233. return this._isLocked;
  19234. },
  19235. set: function (value) {
  19236. this._isLocked = value;
  19237. },
  19238. enumerable: true,
  19239. configurable: true
  19240. });
  19241. // Methods
  19242. /**
  19243. * Updates the boudning sphere and box
  19244. * @param world world matrix to be used to update
  19245. */
  19246. BoundingInfo.prototype.update = function (world) {
  19247. if (this._isLocked) {
  19248. return;
  19249. }
  19250. this.boundingBox._update(world);
  19251. this.boundingSphere._update(world);
  19252. };
  19253. /**
  19254. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19255. * @param center New center of the bounding info
  19256. * @param extend New extend of the bounding info
  19257. * @returns the current bounding info
  19258. */
  19259. BoundingInfo.prototype.centerOn = function (center, extend) {
  19260. this.minimum = center.subtract(extend);
  19261. this.maximum = center.add(extend);
  19262. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  19263. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  19264. return this;
  19265. };
  19266. /**
  19267. * Scale the current bounding info by applying a scale factor
  19268. * @param factor defines the scale factor to apply
  19269. * @returns the current bounding info
  19270. */
  19271. BoundingInfo.prototype.scale = function (factor) {
  19272. this.boundingBox.scale(factor);
  19273. this.boundingSphere.scale(factor);
  19274. return this;
  19275. };
  19276. /**
  19277. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19278. * @param frustumPlanes defines the frustum to test
  19279. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19280. * @returns true if the bounding info is in the frustum planes
  19281. */
  19282. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19283. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19284. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19285. return false;
  19286. }
  19287. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19288. return true;
  19289. }
  19290. return this.boundingBox.isInFrustum(frustumPlanes);
  19291. };
  19292. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19293. /**
  19294. * Gets the world distance between the min and max points of the bounding box
  19295. */
  19296. get: function () {
  19297. var boundingBox = this.boundingBox;
  19298. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19299. return size.length();
  19300. },
  19301. enumerable: true,
  19302. configurable: true
  19303. });
  19304. /**
  19305. * Checks if a cullable object (mesh...) is in the camera frustum
  19306. * Unlike isInFrustum this cheks the full bounding box
  19307. * @param frustumPlanes Camera near/planes
  19308. * @returns true if the object is in frustum otherwise false
  19309. */
  19310. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19311. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19312. };
  19313. /** @hidden */
  19314. BoundingInfo.prototype._checkCollision = function (collider) {
  19315. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19316. };
  19317. /**
  19318. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19319. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19320. * @param point the point to check intersection with
  19321. * @returns if the point intersects
  19322. */
  19323. BoundingInfo.prototype.intersectsPoint = function (point) {
  19324. if (!this.boundingSphere.centerWorld) {
  19325. return false;
  19326. }
  19327. if (!this.boundingSphere.intersectsPoint(point)) {
  19328. return false;
  19329. }
  19330. if (!this.boundingBox.intersectsPoint(point)) {
  19331. return false;
  19332. }
  19333. return true;
  19334. };
  19335. /**
  19336. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19337. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19338. * @param boundingInfo the bounding info to check intersection with
  19339. * @param precise if the intersection should be done using OBB
  19340. * @returns if the bounding info intersects
  19341. */
  19342. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19343. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19344. return false;
  19345. }
  19346. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19347. return false;
  19348. }
  19349. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19350. return false;
  19351. }
  19352. if (!precise) {
  19353. return true;
  19354. }
  19355. var box0 = this.boundingBox;
  19356. var box1 = boundingInfo.boundingBox;
  19357. if (!axisOverlap(box0.directions[0], box0, box1))
  19358. return false;
  19359. if (!axisOverlap(box0.directions[1], box0, box1))
  19360. return false;
  19361. if (!axisOverlap(box0.directions[2], box0, box1))
  19362. return false;
  19363. if (!axisOverlap(box1.directions[0], box0, box1))
  19364. return false;
  19365. if (!axisOverlap(box1.directions[1], box0, box1))
  19366. return false;
  19367. if (!axisOverlap(box1.directions[2], box0, box1))
  19368. return false;
  19369. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  19370. return false;
  19371. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  19372. return false;
  19373. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  19374. return false;
  19375. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  19376. return false;
  19377. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  19378. return false;
  19379. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  19380. return false;
  19381. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  19382. return false;
  19383. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  19384. return false;
  19385. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  19386. return false;
  19387. return true;
  19388. };
  19389. return BoundingInfo;
  19390. }());
  19391. BABYLON.BoundingInfo = BoundingInfo;
  19392. })(BABYLON || (BABYLON = {}));
  19393. //# sourceMappingURL=babylon.boundingInfo.js.map
  19394. var BABYLON;
  19395. (function (BABYLON) {
  19396. var TransformNode = /** @class */ (function (_super) {
  19397. __extends(TransformNode, _super);
  19398. function TransformNode(name, scene, isPure) {
  19399. if (scene === void 0) { scene = null; }
  19400. if (isPure === void 0) { isPure = true; }
  19401. var _this = _super.call(this, name, scene) || this;
  19402. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19403. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19404. _this._up = new BABYLON.Vector3(0, 1, 0);
  19405. _this._right = new BABYLON.Vector3(1, 0, 0);
  19406. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19407. // Properties
  19408. _this._position = BABYLON.Vector3.Zero();
  19409. _this._rotation = BABYLON.Vector3.Zero();
  19410. _this._scaling = BABYLON.Vector3.One();
  19411. _this._isDirty = false;
  19412. /**
  19413. * Set the billboard mode. Default is 0.
  19414. *
  19415. * | Value | Type | Description |
  19416. * | --- | --- | --- |
  19417. * | 0 | BILLBOARDMODE_NONE | |
  19418. * | 1 | BILLBOARDMODE_X | |
  19419. * | 2 | BILLBOARDMODE_Y | |
  19420. * | 4 | BILLBOARDMODE_Z | |
  19421. * | 7 | BILLBOARDMODE_ALL | |
  19422. *
  19423. */
  19424. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19425. _this.scalingDeterminant = 1;
  19426. _this.infiniteDistance = false;
  19427. /**
  19428. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19429. * By default the system will update normals to compensate
  19430. */
  19431. _this.ignoreNonUniformScaling = false;
  19432. _this._localWorld = BABYLON.Matrix.Zero();
  19433. _this._absolutePosition = BABYLON.Vector3.Zero();
  19434. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19435. _this._postMultiplyPivotMatrix = false;
  19436. _this._isWorldMatrixFrozen = false;
  19437. /**
  19438. * An event triggered after the world matrix is updated
  19439. */
  19440. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19441. _this._nonUniformScaling = false;
  19442. if (isPure) {
  19443. _this.getScene().addTransformNode(_this);
  19444. }
  19445. return _this;
  19446. }
  19447. /**
  19448. * Gets a string identifying the name of the class
  19449. * @returns "TransformNode" string
  19450. */
  19451. TransformNode.prototype.getClassName = function () {
  19452. return "TransformNode";
  19453. };
  19454. Object.defineProperty(TransformNode.prototype, "position", {
  19455. /**
  19456. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19457. */
  19458. get: function () {
  19459. return this._position;
  19460. },
  19461. set: function (newPosition) {
  19462. this._position = newPosition;
  19463. this._isDirty = true;
  19464. },
  19465. enumerable: true,
  19466. configurable: true
  19467. });
  19468. Object.defineProperty(TransformNode.prototype, "rotation", {
  19469. /**
  19470. * 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)).
  19471. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19472. */
  19473. get: function () {
  19474. return this._rotation;
  19475. },
  19476. set: function (newRotation) {
  19477. this._rotation = newRotation;
  19478. this._isDirty = true;
  19479. },
  19480. enumerable: true,
  19481. configurable: true
  19482. });
  19483. Object.defineProperty(TransformNode.prototype, "scaling", {
  19484. /**
  19485. * 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)).
  19486. */
  19487. get: function () {
  19488. return this._scaling;
  19489. },
  19490. set: function (newScaling) {
  19491. this._scaling = newScaling;
  19492. this._isDirty = true;
  19493. },
  19494. enumerable: true,
  19495. configurable: true
  19496. });
  19497. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19498. /**
  19499. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19500. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19501. */
  19502. get: function () {
  19503. return this._rotationQuaternion;
  19504. },
  19505. set: function (quaternion) {
  19506. this._rotationQuaternion = quaternion;
  19507. //reset the rotation vector.
  19508. if (quaternion && this.rotation.length()) {
  19509. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19510. }
  19511. },
  19512. enumerable: true,
  19513. configurable: true
  19514. });
  19515. Object.defineProperty(TransformNode.prototype, "forward", {
  19516. /**
  19517. * The forward direction of that transform in world space.
  19518. */
  19519. get: function () {
  19520. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19521. },
  19522. enumerable: true,
  19523. configurable: true
  19524. });
  19525. Object.defineProperty(TransformNode.prototype, "up", {
  19526. /**
  19527. * The up direction of that transform in world space.
  19528. */
  19529. get: function () {
  19530. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19531. },
  19532. enumerable: true,
  19533. configurable: true
  19534. });
  19535. Object.defineProperty(TransformNode.prototype, "right", {
  19536. /**
  19537. * The right direction of that transform in world space.
  19538. */
  19539. get: function () {
  19540. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. /**
  19546. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19547. * Returns the TransformNode.
  19548. */
  19549. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19550. this._poseMatrix.copyFrom(matrix);
  19551. return this;
  19552. };
  19553. /**
  19554. * Returns the mesh Pose matrix.
  19555. * Returned object : Matrix
  19556. */
  19557. TransformNode.prototype.getPoseMatrix = function () {
  19558. return this._poseMatrix;
  19559. };
  19560. /** @hidden */
  19561. TransformNode.prototype._isSynchronized = function () {
  19562. if (this._isDirty) {
  19563. return false;
  19564. }
  19565. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19566. return false;
  19567. if (this._cache.pivotMatrixUpdated) {
  19568. return false;
  19569. }
  19570. if (this.infiniteDistance) {
  19571. return false;
  19572. }
  19573. if (!this._cache.position.equals(this._position))
  19574. return false;
  19575. if (this._rotationQuaternion) {
  19576. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19577. return false;
  19578. }
  19579. if (!this._cache.rotation.equals(this._rotation))
  19580. return false;
  19581. if (!this._cache.scaling.equals(this._scaling))
  19582. return false;
  19583. return true;
  19584. };
  19585. /** @hidden */
  19586. TransformNode.prototype._initCache = function () {
  19587. _super.prototype._initCache.call(this);
  19588. this._cache.localMatrixUpdated = false;
  19589. this._cache.position = BABYLON.Vector3.Zero();
  19590. this._cache.scaling = BABYLON.Vector3.Zero();
  19591. this._cache.rotation = BABYLON.Vector3.Zero();
  19592. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19593. this._cache.billboardMode = -1;
  19594. };
  19595. TransformNode.prototype.markAsDirty = function (property) {
  19596. if (property === "rotation") {
  19597. this.rotationQuaternion = null;
  19598. }
  19599. this._currentRenderId = Number.MAX_VALUE;
  19600. this._isDirty = true;
  19601. return this;
  19602. };
  19603. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19604. /**
  19605. * Returns the current mesh absolute position.
  19606. * Returns a Vector3.
  19607. */
  19608. get: function () {
  19609. return this._absolutePosition;
  19610. },
  19611. enumerable: true,
  19612. configurable: true
  19613. });
  19614. /**
  19615. * Sets a new matrix to apply before all other transformation
  19616. * @param matrix defines the transform matrix
  19617. * @returns the current TransformNode
  19618. */
  19619. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19620. return this.setPivotMatrix(matrix, false);
  19621. };
  19622. /**
  19623. * Sets a new pivot matrix to the current node
  19624. * @param matrix defines the new pivot matrix to use
  19625. * @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
  19626. * @returns the current TransformNode
  19627. */
  19628. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19629. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19630. this._pivotMatrix = matrix.clone();
  19631. this._cache.pivotMatrixUpdated = true;
  19632. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19633. if (this._postMultiplyPivotMatrix) {
  19634. if (!this._pivotMatrixInverse) {
  19635. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19636. }
  19637. else {
  19638. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19639. }
  19640. }
  19641. return this;
  19642. };
  19643. /**
  19644. * Returns the mesh pivot matrix.
  19645. * Default : Identity.
  19646. * A Matrix is returned.
  19647. */
  19648. TransformNode.prototype.getPivotMatrix = function () {
  19649. return this._pivotMatrix;
  19650. };
  19651. /**
  19652. * Prevents the World matrix to be computed any longer.
  19653. * Returns the TransformNode.
  19654. */
  19655. TransformNode.prototype.freezeWorldMatrix = function () {
  19656. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19657. this.computeWorldMatrix(true);
  19658. this._isWorldMatrixFrozen = true;
  19659. return this;
  19660. };
  19661. /**
  19662. * Allows back the World matrix computation.
  19663. * Returns the TransformNode.
  19664. */
  19665. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19666. this._isWorldMatrixFrozen = false;
  19667. this.computeWorldMatrix(true);
  19668. return this;
  19669. };
  19670. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19671. /**
  19672. * True if the World matrix has been frozen.
  19673. * Returns a boolean.
  19674. */
  19675. get: function () {
  19676. return this._isWorldMatrixFrozen;
  19677. },
  19678. enumerable: true,
  19679. configurable: true
  19680. });
  19681. /**
  19682. * Retuns the mesh absolute position in the World.
  19683. * Returns a Vector3.
  19684. */
  19685. TransformNode.prototype.getAbsolutePosition = function () {
  19686. this.computeWorldMatrix();
  19687. return this._absolutePosition;
  19688. };
  19689. /**
  19690. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19691. * Returns the TransformNode.
  19692. */
  19693. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19694. if (!absolutePosition) {
  19695. return this;
  19696. }
  19697. var absolutePositionX;
  19698. var absolutePositionY;
  19699. var absolutePositionZ;
  19700. if (absolutePosition.x === undefined) {
  19701. if (arguments.length < 3) {
  19702. return this;
  19703. }
  19704. absolutePositionX = arguments[0];
  19705. absolutePositionY = arguments[1];
  19706. absolutePositionZ = arguments[2];
  19707. }
  19708. else {
  19709. absolutePositionX = absolutePosition.x;
  19710. absolutePositionY = absolutePosition.y;
  19711. absolutePositionZ = absolutePosition.z;
  19712. }
  19713. if (this.parent) {
  19714. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19715. invertParentWorldMatrix.invert();
  19716. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19717. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19718. }
  19719. else {
  19720. this.position.x = absolutePositionX;
  19721. this.position.y = absolutePositionY;
  19722. this.position.z = absolutePositionZ;
  19723. }
  19724. return this;
  19725. };
  19726. /**
  19727. * Sets the mesh position in its local space.
  19728. * Returns the TransformNode.
  19729. */
  19730. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19731. this.computeWorldMatrix();
  19732. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19733. return this;
  19734. };
  19735. /**
  19736. * Returns the mesh position in the local space from the current World matrix values.
  19737. * Returns a new Vector3.
  19738. */
  19739. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19740. this.computeWorldMatrix();
  19741. var invLocalWorldMatrix = this._localWorld.clone();
  19742. invLocalWorldMatrix.invert();
  19743. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19744. };
  19745. /**
  19746. * Translates the mesh along the passed Vector3 in its local space.
  19747. * Returns the TransformNode.
  19748. */
  19749. TransformNode.prototype.locallyTranslate = function (vector3) {
  19750. this.computeWorldMatrix(true);
  19751. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19752. return this;
  19753. };
  19754. /**
  19755. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19756. * @param targetPoint the position (must be in same space as current mesh) to look at
  19757. * @param yawCor optional yaw (y-axis) correction in radians
  19758. * @param pitchCor optional pitch (x-axis) correction in radians
  19759. * @param rollCor optional roll (z-axis) correction in radians
  19760. * @param space the choosen space of the target
  19761. * @returns the TransformNode.
  19762. */
  19763. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19764. if (yawCor === void 0) { yawCor = 0; }
  19765. if (pitchCor === void 0) { pitchCor = 0; }
  19766. if (rollCor === void 0) { rollCor = 0; }
  19767. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19768. var dv = TransformNode._lookAtVectorCache;
  19769. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19770. targetPoint.subtractToRef(pos, dv);
  19771. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19772. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19773. var pitch = Math.atan2(dv.y, len);
  19774. if (this.rotationQuaternion) {
  19775. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19776. }
  19777. else {
  19778. this.rotation.x = pitch + pitchCor;
  19779. this.rotation.y = yaw + yawCor;
  19780. this.rotation.z = rollCor;
  19781. }
  19782. return this;
  19783. };
  19784. /**
  19785. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19786. * This Vector3 is expressed in the World space.
  19787. */
  19788. TransformNode.prototype.getDirection = function (localAxis) {
  19789. var result = BABYLON.Vector3.Zero();
  19790. this.getDirectionToRef(localAxis, result);
  19791. return result;
  19792. };
  19793. /**
  19794. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19795. * localAxis is expressed in the mesh local space.
  19796. * result is computed in the Wordl space from the mesh World matrix.
  19797. * Returns the TransformNode.
  19798. */
  19799. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19800. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19801. return this;
  19802. };
  19803. /**
  19804. * Sets a new pivot point to the current node
  19805. * @param point defines the new pivot point to use
  19806. * @param space defines if the point is in world or local space (local by default)
  19807. * @returns the current TransformNode
  19808. */
  19809. TransformNode.prototype.setPivotPoint = function (point, space) {
  19810. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19811. if (this.getScene().getRenderId() == 0) {
  19812. this.computeWorldMatrix(true);
  19813. }
  19814. var wm = this.getWorldMatrix();
  19815. if (space == BABYLON.Space.WORLD) {
  19816. var tmat = BABYLON.Tmp.Matrix[0];
  19817. wm.invertToRef(tmat);
  19818. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19819. }
  19820. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19821. };
  19822. /**
  19823. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19824. */
  19825. TransformNode.prototype.getPivotPoint = function () {
  19826. var point = BABYLON.Vector3.Zero();
  19827. this.getPivotPointToRef(point);
  19828. return point;
  19829. };
  19830. /**
  19831. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19832. * Returns the TransformNode.
  19833. */
  19834. TransformNode.prototype.getPivotPointToRef = function (result) {
  19835. result.x = -this._pivotMatrix.m[12];
  19836. result.y = -this._pivotMatrix.m[13];
  19837. result.z = -this._pivotMatrix.m[14];
  19838. return this;
  19839. };
  19840. /**
  19841. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19842. */
  19843. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19844. var point = BABYLON.Vector3.Zero();
  19845. this.getAbsolutePivotPointToRef(point);
  19846. return point;
  19847. };
  19848. /**
  19849. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19850. * Returns the TransformNode.
  19851. */
  19852. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19853. result.x = this._pivotMatrix.m[12];
  19854. result.y = this._pivotMatrix.m[13];
  19855. result.z = this._pivotMatrix.m[14];
  19856. this.getPivotPointToRef(result);
  19857. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19858. return this;
  19859. };
  19860. /**
  19861. * Defines the passed node as the parent of the current node.
  19862. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19863. * Returns the TransformNode.
  19864. */
  19865. TransformNode.prototype.setParent = function (node) {
  19866. if (!node && !this.parent) {
  19867. return this;
  19868. }
  19869. if (!node) {
  19870. var rotation = BABYLON.Tmp.Quaternion[0];
  19871. var position = BABYLON.Tmp.Vector3[0];
  19872. var scale = BABYLON.Tmp.Vector3[1];
  19873. if (this.parent && this.parent.computeWorldMatrix) {
  19874. this.parent.computeWorldMatrix(true);
  19875. }
  19876. this.computeWorldMatrix(true);
  19877. this.getWorldMatrix().decompose(scale, rotation, position);
  19878. if (this.rotationQuaternion) {
  19879. this.rotationQuaternion.copyFrom(rotation);
  19880. }
  19881. else {
  19882. rotation.toEulerAnglesToRef(this.rotation);
  19883. }
  19884. this.scaling.x = scale.x;
  19885. this.scaling.y = scale.y;
  19886. this.scaling.z = scale.z;
  19887. this.position.x = position.x;
  19888. this.position.y = position.y;
  19889. this.position.z = position.z;
  19890. }
  19891. else {
  19892. var rotation = BABYLON.Tmp.Quaternion[0];
  19893. var position = BABYLON.Tmp.Vector3[0];
  19894. var scale = BABYLON.Tmp.Vector3[1];
  19895. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19896. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19897. this.computeWorldMatrix(true);
  19898. node.computeWorldMatrix(true);
  19899. node.getWorldMatrix().invertToRef(invParentMatrix);
  19900. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19901. diffMatrix.decompose(scale, rotation, position);
  19902. if (this.rotationQuaternion) {
  19903. this.rotationQuaternion.copyFrom(rotation);
  19904. }
  19905. else {
  19906. rotation.toEulerAnglesToRef(this.rotation);
  19907. }
  19908. this.position.x = position.x;
  19909. this.position.y = position.y;
  19910. this.position.z = position.z;
  19911. this.scaling.x = scale.x;
  19912. this.scaling.y = scale.y;
  19913. this.scaling.z = scale.z;
  19914. }
  19915. this.parent = node;
  19916. return this;
  19917. };
  19918. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19919. get: function () {
  19920. return this._nonUniformScaling;
  19921. },
  19922. enumerable: true,
  19923. configurable: true
  19924. });
  19925. /** @hidden */
  19926. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19927. if (this._nonUniformScaling === value) {
  19928. return false;
  19929. }
  19930. this._nonUniformScaling = value;
  19931. return true;
  19932. };
  19933. /**
  19934. * Attach the current TransformNode to another TransformNode associated with a bone
  19935. * @param bone Bone affecting the TransformNode
  19936. * @param affectedTransformNode TransformNode associated with the bone
  19937. */
  19938. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19939. this._transformToBoneReferal = affectedTransformNode;
  19940. this.parent = bone;
  19941. if (bone.getWorldMatrix().determinant() < 0) {
  19942. this.scalingDeterminant *= -1;
  19943. }
  19944. return this;
  19945. };
  19946. TransformNode.prototype.detachFromBone = function () {
  19947. if (!this.parent) {
  19948. return this;
  19949. }
  19950. if (this.parent.getWorldMatrix().determinant() < 0) {
  19951. this.scalingDeterminant *= -1;
  19952. }
  19953. this._transformToBoneReferal = null;
  19954. this.parent = null;
  19955. return this;
  19956. };
  19957. /**
  19958. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19959. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19960. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19961. * The passed axis is also normalized.
  19962. * Returns the TransformNode.
  19963. */
  19964. TransformNode.prototype.rotate = function (axis, amount, space) {
  19965. axis.normalize();
  19966. if (!this.rotationQuaternion) {
  19967. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19968. this.rotation = BABYLON.Vector3.Zero();
  19969. }
  19970. var rotationQuaternion;
  19971. if (!space || space === BABYLON.Space.LOCAL) {
  19972. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19973. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19974. }
  19975. else {
  19976. if (this.parent) {
  19977. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19978. invertParentWorldMatrix.invert();
  19979. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19980. }
  19981. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19982. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19983. }
  19984. return this;
  19985. };
  19986. /**
  19987. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19988. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19989. * The passed axis is also normalized.
  19990. * Returns the TransformNode.
  19991. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19992. */
  19993. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19994. axis.normalize();
  19995. if (!this.rotationQuaternion) {
  19996. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19997. this.rotation.copyFromFloats(0, 0, 0);
  19998. }
  19999. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  20000. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  20001. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  20002. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  20003. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  20004. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  20005. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  20006. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  20007. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20008. return this;
  20009. };
  20010. /**
  20011. * Translates the mesh along the axis vector for the passed distance in the given space.
  20012. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20013. * Returns the TransformNode.
  20014. */
  20015. TransformNode.prototype.translate = function (axis, distance, space) {
  20016. var displacementVector = axis.scale(distance);
  20017. if (!space || space === BABYLON.Space.LOCAL) {
  20018. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20019. this.setPositionWithLocalVector(tempV3);
  20020. }
  20021. else {
  20022. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20023. }
  20024. return this;
  20025. };
  20026. /**
  20027. * Adds a rotation step to the mesh current rotation.
  20028. * x, y, z are Euler angles expressed in radians.
  20029. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20030. * This means this rotation is made in the mesh local space only.
  20031. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20032. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20033. * ```javascript
  20034. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20035. * ```
  20036. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20037. * 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.
  20038. * Returns the TransformNode.
  20039. */
  20040. TransformNode.prototype.addRotation = function (x, y, z) {
  20041. var rotationQuaternion;
  20042. if (this.rotationQuaternion) {
  20043. rotationQuaternion = this.rotationQuaternion;
  20044. }
  20045. else {
  20046. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20047. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20048. }
  20049. var accumulation = BABYLON.Tmp.Quaternion[0];
  20050. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20051. rotationQuaternion.multiplyInPlace(accumulation);
  20052. if (!this.rotationQuaternion) {
  20053. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20054. }
  20055. return this;
  20056. };
  20057. /**
  20058. * Computes the world matrix of the node
  20059. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20060. * @returns the world matrix
  20061. */
  20062. TransformNode.prototype.computeWorldMatrix = function (force) {
  20063. if (this._isWorldMatrixFrozen) {
  20064. return this._worldMatrix;
  20065. }
  20066. if (!force && this.isSynchronized()) {
  20067. this._currentRenderId = this.getScene().getRenderId();
  20068. return this._worldMatrix;
  20069. }
  20070. this._updateCache();
  20071. this._cache.position.copyFrom(this.position);
  20072. this._cache.scaling.copyFrom(this.scaling);
  20073. this._cache.pivotMatrixUpdated = false;
  20074. this._cache.billboardMode = this.billboardMode;
  20075. this._currentRenderId = this.getScene().getRenderId();
  20076. this._childRenderId = this.getScene().getRenderId();
  20077. this._isDirty = false;
  20078. // Scaling
  20079. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20080. // Rotation
  20081. //rotate, if quaternion is set and rotation was used
  20082. if (this.rotationQuaternion) {
  20083. var len = this.rotation.length();
  20084. if (len) {
  20085. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20086. this.rotation.copyFromFloats(0, 0, 0);
  20087. }
  20088. }
  20089. if (this.rotationQuaternion) {
  20090. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20091. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20092. }
  20093. else {
  20094. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20095. this._cache.rotation.copyFrom(this.rotation);
  20096. }
  20097. // Translation
  20098. var camera = this.getScene().activeCamera;
  20099. if (this.infiniteDistance && !this.parent && camera) {
  20100. var cameraWorldMatrix = camera.getWorldMatrix();
  20101. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20102. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20103. }
  20104. else {
  20105. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20106. }
  20107. // Composing transformations
  20108. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20109. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20110. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20111. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20112. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20113. // Need to decompose each rotation here
  20114. var currentPosition = BABYLON.Tmp.Vector3[3];
  20115. if (this.parent && this.parent.getWorldMatrix) {
  20116. if (this._transformToBoneReferal) {
  20117. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20118. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20119. }
  20120. else {
  20121. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20122. }
  20123. }
  20124. else {
  20125. currentPosition.copyFrom(this.position);
  20126. }
  20127. currentPosition.subtractInPlace(camera.globalPosition);
  20128. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20129. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20130. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20131. }
  20132. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20133. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20134. }
  20135. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20136. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20137. }
  20138. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20139. }
  20140. else {
  20141. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20142. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20143. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20144. }
  20145. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20146. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20147. }
  20148. // Post multiply inverse of pivotMatrix
  20149. if (this._postMultiplyPivotMatrix) {
  20150. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20151. }
  20152. // Local world
  20153. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20154. // Parent
  20155. if (this.parent && this.parent.getWorldMatrix) {
  20156. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20157. if (this._transformToBoneReferal) {
  20158. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20159. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20160. }
  20161. else {
  20162. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20163. }
  20164. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20165. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20166. this._worldMatrix.copyFrom(this._localWorld);
  20167. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20168. }
  20169. else {
  20170. if (this._transformToBoneReferal) {
  20171. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20172. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20173. }
  20174. else {
  20175. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20176. }
  20177. }
  20178. this._markSyncedWithParent();
  20179. }
  20180. else {
  20181. this._worldMatrix.copyFrom(this._localWorld);
  20182. }
  20183. // Normal matrix
  20184. if (!this.ignoreNonUniformScaling) {
  20185. if (this.scaling.isNonUniform) {
  20186. this._updateNonUniformScalingState(true);
  20187. }
  20188. else if (this.parent && this.parent._nonUniformScaling) {
  20189. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20190. }
  20191. else {
  20192. this._updateNonUniformScalingState(false);
  20193. }
  20194. }
  20195. else {
  20196. this._updateNonUniformScalingState(false);
  20197. }
  20198. this._afterComputeWorldMatrix();
  20199. // Absolute position
  20200. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20201. // Callbacks
  20202. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20203. if (!this._poseMatrix) {
  20204. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20205. }
  20206. // Cache the determinant
  20207. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20208. return this._worldMatrix;
  20209. };
  20210. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20211. };
  20212. /**
  20213. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20214. * @param func: callback function to add
  20215. *
  20216. * Returns the TransformNode.
  20217. */
  20218. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20219. this.onAfterWorldMatrixUpdateObservable.add(func);
  20220. return this;
  20221. };
  20222. /**
  20223. * Removes a registered callback function.
  20224. * Returns the TransformNode.
  20225. */
  20226. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20227. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20228. return this;
  20229. };
  20230. /**
  20231. * Clone the current transform node
  20232. * Returns the new transform node
  20233. * @param name Name of the new clone
  20234. * @param newParent New parent for the clone
  20235. * @param doNotCloneChildren Do not clone children hierarchy
  20236. */
  20237. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20238. var _this = this;
  20239. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20240. result.name = name;
  20241. result.id = name;
  20242. if (newParent) {
  20243. result.parent = newParent;
  20244. }
  20245. if (!doNotCloneChildren) {
  20246. // Children
  20247. var directDescendants = this.getDescendants(true);
  20248. for (var index = 0; index < directDescendants.length; index++) {
  20249. var child = directDescendants[index];
  20250. if (child.clone) {
  20251. child.clone(name + "." + child.name, result);
  20252. }
  20253. }
  20254. }
  20255. return result;
  20256. };
  20257. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20258. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20259. serializationObject.type = this.getClassName();
  20260. // Parent
  20261. if (this.parent) {
  20262. serializationObject.parentId = this.parent.id;
  20263. }
  20264. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20265. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20266. }
  20267. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20268. serializationObject.isEnabled = this.isEnabled();
  20269. // Parent
  20270. if (this.parent) {
  20271. serializationObject.parentId = this.parent.id;
  20272. }
  20273. return serializationObject;
  20274. };
  20275. // Statics
  20276. /**
  20277. * Returns a new TransformNode object parsed from the source provided.
  20278. * The parameter `parsedMesh` is the source.
  20279. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20280. */
  20281. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20282. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20283. if (BABYLON.Tags) {
  20284. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20285. }
  20286. if (parsedTransformNode.localMatrix) {
  20287. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20288. }
  20289. else if (parsedTransformNode.pivotMatrix) {
  20290. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20291. }
  20292. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20293. // Parent
  20294. if (parsedTransformNode.parentId) {
  20295. transformNode._waitingParentId = parsedTransformNode.parentId;
  20296. }
  20297. return transformNode;
  20298. };
  20299. /**
  20300. * Releases resources associated with this transform node.
  20301. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20302. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20303. */
  20304. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20305. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20306. // Animations
  20307. this.getScene().stopAnimation(this);
  20308. // Remove from scene
  20309. this.getScene().removeTransformNode(this);
  20310. this.onAfterWorldMatrixUpdateObservable.clear();
  20311. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20312. };
  20313. // Statics
  20314. TransformNode.BILLBOARDMODE_NONE = 0;
  20315. TransformNode.BILLBOARDMODE_X = 1;
  20316. TransformNode.BILLBOARDMODE_Y = 2;
  20317. TransformNode.BILLBOARDMODE_Z = 4;
  20318. TransformNode.BILLBOARDMODE_ALL = 7;
  20319. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20320. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20321. __decorate([
  20322. BABYLON.serializeAsVector3("position")
  20323. ], TransformNode.prototype, "_position", void 0);
  20324. __decorate([
  20325. BABYLON.serializeAsVector3("rotation")
  20326. ], TransformNode.prototype, "_rotation", void 0);
  20327. __decorate([
  20328. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20329. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20330. __decorate([
  20331. BABYLON.serializeAsVector3("scaling")
  20332. ], TransformNode.prototype, "_scaling", void 0);
  20333. __decorate([
  20334. BABYLON.serialize()
  20335. ], TransformNode.prototype, "billboardMode", void 0);
  20336. __decorate([
  20337. BABYLON.serialize()
  20338. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20339. __decorate([
  20340. BABYLON.serialize()
  20341. ], TransformNode.prototype, "infiniteDistance", void 0);
  20342. __decorate([
  20343. BABYLON.serialize()
  20344. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20345. return TransformNode;
  20346. }(BABYLON.Node));
  20347. BABYLON.TransformNode = TransformNode;
  20348. })(BABYLON || (BABYLON = {}));
  20349. //# sourceMappingURL=babylon.transformNode.js.map
  20350. var BABYLON;
  20351. (function (BABYLON) {
  20352. /** @hidden */
  20353. var _FacetDataStorage = /** @class */ (function () {
  20354. function _FacetDataStorage() {
  20355. this.facetNb = 0; // facet number
  20356. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20357. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20358. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20359. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20360. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20361. this.subDiv = {
  20362. max: 1,
  20363. X: 1,
  20364. Y: 1,
  20365. Z: 1
  20366. };
  20367. this.facetDepthSort = false; // is the facet depth sort to be computed
  20368. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20369. }
  20370. return _FacetDataStorage;
  20371. }());
  20372. /**
  20373. * Class used to store all common mesh properties
  20374. */
  20375. var AbstractMesh = /** @class */ (function (_super) {
  20376. __extends(AbstractMesh, _super);
  20377. // Constructor
  20378. /**
  20379. * Creates a new AbstractMesh
  20380. * @param name defines the name of the mesh
  20381. * @param scene defines the hosting scene
  20382. */
  20383. function AbstractMesh(name, scene) {
  20384. if (scene === void 0) { scene = null; }
  20385. var _this = _super.call(this, name, scene, false) || this;
  20386. _this._facetData = new _FacetDataStorage();
  20387. /** Gets ot sets the culling strategy to use to find visible meshes */
  20388. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20389. // Events
  20390. /**
  20391. * An event triggered when this mesh collides with another one
  20392. */
  20393. _this.onCollideObservable = new BABYLON.Observable();
  20394. /**
  20395. * An event triggered when the collision's position changes
  20396. */
  20397. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20398. /**
  20399. * An event triggered when material is changed
  20400. */
  20401. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20402. // Properties
  20403. /**
  20404. * Gets or sets the orientation for POV movement & rotation
  20405. */
  20406. _this.definedFacingForward = true;
  20407. _this._visibility = 1.0;
  20408. /** Gets or sets the alpha index used to sort transparent meshes
  20409. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20410. */
  20411. _this.alphaIndex = Number.MAX_VALUE;
  20412. /**
  20413. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20414. */
  20415. _this.isVisible = true;
  20416. /**
  20417. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20418. */
  20419. _this.isPickable = true;
  20420. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20421. _this.showSubMeshesBoundingBox = false;
  20422. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20423. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20424. */
  20425. _this.isBlocker = false;
  20426. /**
  20427. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20428. */
  20429. _this.enablePointerMoveEvents = false;
  20430. /**
  20431. * Specifies the rendering group id for this mesh (0 by default)
  20432. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20433. */
  20434. _this.renderingGroupId = 0;
  20435. _this._receiveShadows = false;
  20436. /** Defines color to use when rendering outline */
  20437. _this.outlineColor = BABYLON.Color3.Red();
  20438. /** Define width to use when rendering outline */
  20439. _this.outlineWidth = 0.02;
  20440. /** Defines color to use when rendering overlay */
  20441. _this.overlayColor = BABYLON.Color3.Red();
  20442. /** Defines alpha to use when rendering overlay */
  20443. _this.overlayAlpha = 0.5;
  20444. _this._hasVertexAlpha = false;
  20445. _this._useVertexColors = true;
  20446. _this._computeBonesUsingShaders = true;
  20447. _this._numBoneInfluencers = 4;
  20448. _this._applyFog = true;
  20449. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20450. _this.useOctreeForRenderingSelection = true;
  20451. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20452. _this.useOctreeForPicking = true;
  20453. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20454. _this.useOctreeForCollisions = true;
  20455. _this._layerMask = 0x0FFFFFFF;
  20456. /**
  20457. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20458. */
  20459. _this.alwaysSelectAsActiveMesh = false;
  20460. /**
  20461. * Gets or sets the current action manager
  20462. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20463. */
  20464. _this.actionManager = null;
  20465. // Collisions
  20466. _this._checkCollisions = false;
  20467. _this._collisionMask = -1;
  20468. _this._collisionGroup = -1;
  20469. /**
  20470. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20471. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20472. */
  20473. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20474. /**
  20475. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20476. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20477. */
  20478. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20479. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20480. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20481. // Edges
  20482. /**
  20483. * Defines edge width used when edgesRenderer is enabled
  20484. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20485. */
  20486. _this.edgesWidth = 1;
  20487. /**
  20488. * Defines edge color used when edgesRenderer is enabled
  20489. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20490. */
  20491. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20492. // Cache
  20493. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  20494. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  20495. /** @hidden */
  20496. _this._renderId = 0;
  20497. /** @hidden */
  20498. _this._intersectionsInProgress = new Array();
  20499. /** @hidden */
  20500. _this._unIndexed = false;
  20501. /** @hidden */
  20502. _this._lightSources = new Array();
  20503. /**
  20504. * An event triggered when the mesh is rebuilt.
  20505. */
  20506. _this.onRebuildObservable = new BABYLON.Observable();
  20507. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20508. if (collidedMesh === void 0) { collidedMesh = null; }
  20509. //TODO move this to the collision coordinator!
  20510. if (_this.getScene().workerCollisions)
  20511. newPosition.multiplyInPlace(_this._collider._radius);
  20512. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20513. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20514. _this.position.addInPlace(_this._diffPositionForCollisions);
  20515. }
  20516. if (collidedMesh) {
  20517. _this.onCollideObservable.notifyObservers(collidedMesh);
  20518. }
  20519. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20520. };
  20521. _this.getScene().addMesh(_this);
  20522. _this._resyncLightSources();
  20523. return _this;
  20524. }
  20525. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20526. /**
  20527. * No billboard
  20528. */
  20529. get: function () {
  20530. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20531. },
  20532. enumerable: true,
  20533. configurable: true
  20534. });
  20535. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20536. /** Billboard on X axis */
  20537. get: function () {
  20538. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20539. },
  20540. enumerable: true,
  20541. configurable: true
  20542. });
  20543. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20544. /** Billboard on Y axis */
  20545. get: function () {
  20546. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20547. },
  20548. enumerable: true,
  20549. configurable: true
  20550. });
  20551. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20552. /** Billboard on Z axis */
  20553. get: function () {
  20554. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20555. },
  20556. enumerable: true,
  20557. configurable: true
  20558. });
  20559. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20560. /** Billboard on all axes */
  20561. get: function () {
  20562. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20563. },
  20564. enumerable: true,
  20565. configurable: true
  20566. });
  20567. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20568. /**
  20569. * Gets the number of facets in the mesh
  20570. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20571. */
  20572. get: function () {
  20573. return this._facetData.facetNb;
  20574. },
  20575. enumerable: true,
  20576. configurable: true
  20577. });
  20578. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20579. /**
  20580. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20581. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20582. */
  20583. get: function () {
  20584. return this._facetData.partitioningSubdivisions;
  20585. },
  20586. set: function (nb) {
  20587. this._facetData.partitioningSubdivisions = nb;
  20588. },
  20589. enumerable: true,
  20590. configurable: true
  20591. });
  20592. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20593. /**
  20594. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20595. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20596. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20597. */
  20598. get: function () {
  20599. return this._facetData.partitioningBBoxRatio;
  20600. },
  20601. set: function (ratio) {
  20602. this._facetData.partitioningBBoxRatio = ratio;
  20603. },
  20604. enumerable: true,
  20605. configurable: true
  20606. });
  20607. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20608. /**
  20609. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20610. * Works only for updatable meshes.
  20611. * Doesn't work with multi-materials
  20612. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20613. */
  20614. get: function () {
  20615. return this._facetData.facetDepthSort;
  20616. },
  20617. set: function (sort) {
  20618. this._facetData.facetDepthSort = sort;
  20619. },
  20620. enumerable: true,
  20621. configurable: true
  20622. });
  20623. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20624. /**
  20625. * The location (Vector3) where the facet depth sort must be computed from.
  20626. * By default, the active camera position.
  20627. * Used only when facet depth sort is enabled
  20628. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20629. */
  20630. get: function () {
  20631. return this._facetData.facetDepthSortFrom;
  20632. },
  20633. set: function (location) {
  20634. this._facetData.facetDepthSortFrom = location;
  20635. },
  20636. enumerable: true,
  20637. configurable: true
  20638. });
  20639. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20640. /**
  20641. * gets a boolean indicating if facetData is enabled
  20642. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20643. */
  20644. get: function () {
  20645. return this._facetData.facetDataEnabled;
  20646. },
  20647. enumerable: true,
  20648. configurable: true
  20649. });
  20650. /** @hidden */
  20651. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20652. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20653. return false;
  20654. }
  20655. this._markSubMeshesAsMiscDirty();
  20656. return true;
  20657. };
  20658. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20659. /** Set a function to call when this mesh collides with another one */
  20660. set: function (callback) {
  20661. if (this._onCollideObserver) {
  20662. this.onCollideObservable.remove(this._onCollideObserver);
  20663. }
  20664. this._onCollideObserver = this.onCollideObservable.add(callback);
  20665. },
  20666. enumerable: true,
  20667. configurable: true
  20668. });
  20669. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20670. /** Set a function to call when the collision's position changes */
  20671. set: function (callback) {
  20672. if (this._onCollisionPositionChangeObserver) {
  20673. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20674. }
  20675. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20676. },
  20677. enumerable: true,
  20678. configurable: true
  20679. });
  20680. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20681. /**
  20682. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20683. */
  20684. get: function () {
  20685. return this._visibility;
  20686. },
  20687. /**
  20688. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20689. */
  20690. set: function (value) {
  20691. if (this._visibility === value) {
  20692. return;
  20693. }
  20694. this._visibility = value;
  20695. this._markSubMeshesAsMiscDirty();
  20696. },
  20697. enumerable: true,
  20698. configurable: true
  20699. });
  20700. Object.defineProperty(AbstractMesh.prototype, "material", {
  20701. /** Gets or sets current material */
  20702. get: function () {
  20703. return this._material;
  20704. },
  20705. set: function (value) {
  20706. if (this._material === value) {
  20707. return;
  20708. }
  20709. this._material = value;
  20710. if (this.onMaterialChangedObservable.hasObservers) {
  20711. this.onMaterialChangedObservable.notifyObservers(this);
  20712. }
  20713. if (!this.subMeshes) {
  20714. return;
  20715. }
  20716. this._unBindEffect();
  20717. },
  20718. enumerable: true,
  20719. configurable: true
  20720. });
  20721. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20722. /**
  20723. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20724. * @see http://doc.babylonjs.com/babylon101/shadows
  20725. */
  20726. get: function () {
  20727. return this._receiveShadows;
  20728. },
  20729. set: function (value) {
  20730. if (this._receiveShadows === value) {
  20731. return;
  20732. }
  20733. this._receiveShadows = value;
  20734. this._markSubMeshesAsLightDirty();
  20735. },
  20736. enumerable: true,
  20737. configurable: true
  20738. });
  20739. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20740. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20741. get: function () {
  20742. return this._hasVertexAlpha;
  20743. },
  20744. set: function (value) {
  20745. if (this._hasVertexAlpha === value) {
  20746. return;
  20747. }
  20748. this._hasVertexAlpha = value;
  20749. this._markSubMeshesAsAttributesDirty();
  20750. this._markSubMeshesAsMiscDirty();
  20751. },
  20752. enumerable: true,
  20753. configurable: true
  20754. });
  20755. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20756. /** 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) */
  20757. get: function () {
  20758. return this._useVertexColors;
  20759. },
  20760. set: function (value) {
  20761. if (this._useVertexColors === value) {
  20762. return;
  20763. }
  20764. this._useVertexColors = value;
  20765. this._markSubMeshesAsAttributesDirty();
  20766. },
  20767. enumerable: true,
  20768. configurable: true
  20769. });
  20770. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20771. /**
  20772. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20773. */
  20774. get: function () {
  20775. return this._computeBonesUsingShaders;
  20776. },
  20777. set: function (value) {
  20778. if (this._computeBonesUsingShaders === value) {
  20779. return;
  20780. }
  20781. this._computeBonesUsingShaders = value;
  20782. this._markSubMeshesAsAttributesDirty();
  20783. },
  20784. enumerable: true,
  20785. configurable: true
  20786. });
  20787. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20788. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20789. get: function () {
  20790. return this._numBoneInfluencers;
  20791. },
  20792. set: function (value) {
  20793. if (this._numBoneInfluencers === value) {
  20794. return;
  20795. }
  20796. this._numBoneInfluencers = value;
  20797. this._markSubMeshesAsAttributesDirty();
  20798. },
  20799. enumerable: true,
  20800. configurable: true
  20801. });
  20802. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20803. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20804. get: function () {
  20805. return this._applyFog;
  20806. },
  20807. set: function (value) {
  20808. if (this._applyFog === value) {
  20809. return;
  20810. }
  20811. this._applyFog = value;
  20812. this._markSubMeshesAsMiscDirty();
  20813. },
  20814. enumerable: true,
  20815. configurable: true
  20816. });
  20817. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20818. /**
  20819. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20820. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20821. */
  20822. get: function () {
  20823. return this._layerMask;
  20824. },
  20825. set: function (value) {
  20826. if (value === this._layerMask) {
  20827. return;
  20828. }
  20829. this._layerMask = value;
  20830. this._resyncLightSources();
  20831. },
  20832. enumerable: true,
  20833. configurable: true
  20834. });
  20835. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20836. /**
  20837. * Gets or sets a collision mask used to mask collisions (default is -1).
  20838. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20839. */
  20840. get: function () {
  20841. return this._collisionMask;
  20842. },
  20843. set: function (mask) {
  20844. this._collisionMask = !isNaN(mask) ? mask : -1;
  20845. },
  20846. enumerable: true,
  20847. configurable: true
  20848. });
  20849. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20850. /**
  20851. * Gets or sets the current collision group mask (-1 by default).
  20852. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20853. */
  20854. get: function () {
  20855. return this._collisionGroup;
  20856. },
  20857. set: function (mask) {
  20858. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20859. },
  20860. enumerable: true,
  20861. configurable: true
  20862. });
  20863. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20864. /** @hidden */
  20865. get: function () {
  20866. return null;
  20867. },
  20868. enumerable: true,
  20869. configurable: true
  20870. });
  20871. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20872. get: function () {
  20873. return this._skeleton;
  20874. },
  20875. /**
  20876. * Gets or sets a skeleton to apply skining transformations
  20877. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20878. */
  20879. set: function (value) {
  20880. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20881. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20882. }
  20883. if (value && value.needInitialSkinMatrix) {
  20884. value._registerMeshWithPoseMatrix(this);
  20885. }
  20886. this._skeleton = value;
  20887. if (!this._skeleton) {
  20888. this._bonesTransformMatrices = null;
  20889. }
  20890. this._markSubMeshesAsAttributesDirty();
  20891. },
  20892. enumerable: true,
  20893. configurable: true
  20894. });
  20895. /**
  20896. * Returns the string "AbstractMesh"
  20897. * @returns "AbstractMesh"
  20898. */
  20899. AbstractMesh.prototype.getClassName = function () {
  20900. return "AbstractMesh";
  20901. };
  20902. /**
  20903. * Gets a string representation of the current mesh
  20904. * @param fullDetails defines a boolean indicating if full details must be included
  20905. * @returns a string representation of the current mesh
  20906. */
  20907. AbstractMesh.prototype.toString = function (fullDetails) {
  20908. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20909. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20910. if (this._skeleton) {
  20911. ret += ", skeleton: " + this._skeleton.name;
  20912. }
  20913. if (fullDetails) {
  20914. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20915. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20916. }
  20917. return ret;
  20918. };
  20919. /** @hidden */
  20920. AbstractMesh.prototype._rebuild = function () {
  20921. this.onRebuildObservable.notifyObservers(this);
  20922. if (this._occlusionQuery) {
  20923. this._occlusionQuery = null;
  20924. }
  20925. if (!this.subMeshes) {
  20926. return;
  20927. }
  20928. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20929. var subMesh = _a[_i];
  20930. subMesh._rebuild();
  20931. }
  20932. };
  20933. /** @hidden */
  20934. AbstractMesh.prototype._resyncLightSources = function () {
  20935. this._lightSources.length = 0;
  20936. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20937. var light = _a[_i];
  20938. if (!light.isEnabled()) {
  20939. continue;
  20940. }
  20941. if (light.canAffectMesh(this)) {
  20942. this._lightSources.push(light);
  20943. }
  20944. }
  20945. this._markSubMeshesAsLightDirty();
  20946. };
  20947. /** @hidden */
  20948. AbstractMesh.prototype._resyncLighSource = function (light) {
  20949. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20950. var index = this._lightSources.indexOf(light);
  20951. if (index === -1) {
  20952. if (!isIn) {
  20953. return;
  20954. }
  20955. this._lightSources.push(light);
  20956. }
  20957. else {
  20958. if (isIn) {
  20959. return;
  20960. }
  20961. this._lightSources.splice(index, 1);
  20962. }
  20963. this._markSubMeshesAsLightDirty();
  20964. };
  20965. /** @hidden */
  20966. AbstractMesh.prototype._unBindEffect = function () {
  20967. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20968. var subMesh = _a[_i];
  20969. subMesh.setEffect(null);
  20970. }
  20971. };
  20972. /** @hidden */
  20973. AbstractMesh.prototype._removeLightSource = function (light) {
  20974. var index = this._lightSources.indexOf(light);
  20975. if (index === -1) {
  20976. return;
  20977. }
  20978. this._lightSources.splice(index, 1);
  20979. this._markSubMeshesAsLightDirty();
  20980. };
  20981. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20982. if (!this.subMeshes) {
  20983. return;
  20984. }
  20985. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20986. var subMesh = _a[_i];
  20987. if (subMesh._materialDefines) {
  20988. func(subMesh._materialDefines);
  20989. }
  20990. }
  20991. };
  20992. /** @hidden */
  20993. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20994. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20995. };
  20996. /** @hidden */
  20997. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20998. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20999. };
  21000. /** @hidden */
  21001. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21002. if (!this.subMeshes) {
  21003. return;
  21004. }
  21005. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21006. var subMesh = _a[_i];
  21007. var material = subMesh.getMaterial();
  21008. if (material) {
  21009. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21010. }
  21011. }
  21012. };
  21013. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21014. /**
  21015. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21016. */
  21017. get: function () {
  21018. return this._scaling;
  21019. },
  21020. set: function (newScaling) {
  21021. this._scaling = newScaling;
  21022. if (this.physicsImpostor) {
  21023. this.physicsImpostor.forceUpdate();
  21024. }
  21025. },
  21026. enumerable: true,
  21027. configurable: true
  21028. });
  21029. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21030. // Methods
  21031. /**
  21032. * Returns true if the mesh is blocked. Implemented by child classes
  21033. */
  21034. get: function () {
  21035. return false;
  21036. },
  21037. enumerable: true,
  21038. configurable: true
  21039. });
  21040. /**
  21041. * Returns the mesh itself by default. Implemented by child classes
  21042. * @param camera defines the camera to use to pick the right LOD level
  21043. * @returns the currentAbstractMesh
  21044. */
  21045. AbstractMesh.prototype.getLOD = function (camera) {
  21046. return this;
  21047. };
  21048. /**
  21049. * Returns 0 by default. Implemented by child classes
  21050. * @returns an integer
  21051. */
  21052. AbstractMesh.prototype.getTotalVertices = function () {
  21053. return 0;
  21054. };
  21055. /**
  21056. * Returns null by default. Implemented by child classes
  21057. * @returns null
  21058. */
  21059. AbstractMesh.prototype.getIndices = function () {
  21060. return null;
  21061. };
  21062. /**
  21063. * Returns the array of the requested vertex data kind. Implemented by child classes
  21064. * @param kind defines the vertex data kind to use
  21065. * @returns null
  21066. */
  21067. AbstractMesh.prototype.getVerticesData = function (kind) {
  21068. return null;
  21069. };
  21070. /**
  21071. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21072. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21073. * Note that a new underlying VertexBuffer object is created each call.
  21074. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21075. * @param kind defines vertex data kind:
  21076. * * BABYLON.VertexBuffer.PositionKind
  21077. * * BABYLON.VertexBuffer.UVKind
  21078. * * BABYLON.VertexBuffer.UV2Kind
  21079. * * BABYLON.VertexBuffer.UV3Kind
  21080. * * BABYLON.VertexBuffer.UV4Kind
  21081. * * BABYLON.VertexBuffer.UV5Kind
  21082. * * BABYLON.VertexBuffer.UV6Kind
  21083. * * BABYLON.VertexBuffer.ColorKind
  21084. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21085. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21086. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21087. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21088. * @param data defines the data source
  21089. * @param updatable defines if the data must be flagged as updatable (or static)
  21090. * @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
  21091. * @returns the current mesh
  21092. */
  21093. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21094. return this;
  21095. };
  21096. /**
  21097. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21098. * If the mesh has no geometry, it is simply returned as it is.
  21099. * @param kind defines vertex data kind:
  21100. * * BABYLON.VertexBuffer.PositionKind
  21101. * * BABYLON.VertexBuffer.UVKind
  21102. * * BABYLON.VertexBuffer.UV2Kind
  21103. * * BABYLON.VertexBuffer.UV3Kind
  21104. * * BABYLON.VertexBuffer.UV4Kind
  21105. * * BABYLON.VertexBuffer.UV5Kind
  21106. * * BABYLON.VertexBuffer.UV6Kind
  21107. * * BABYLON.VertexBuffer.ColorKind
  21108. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21109. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21110. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21111. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21112. * @param data defines the data source
  21113. * @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
  21114. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21115. * @returns the current mesh
  21116. */
  21117. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21118. return this;
  21119. };
  21120. /**
  21121. * Sets the mesh indices,
  21122. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21123. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21124. * @param totalVertices Defines the total number of vertices
  21125. * @returns the current mesh
  21126. */
  21127. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21128. return this;
  21129. };
  21130. /**
  21131. * Gets a boolean indicating if specific vertex data is present
  21132. * @param kind defines the vertex data kind to use
  21133. * @returns true is data kind is present
  21134. */
  21135. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21136. return false;
  21137. };
  21138. /**
  21139. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21140. * @returns a BoundingInfo
  21141. */
  21142. AbstractMesh.prototype.getBoundingInfo = function () {
  21143. if (this._masterMesh) {
  21144. return this._masterMesh.getBoundingInfo();
  21145. }
  21146. if (!this._boundingInfo) {
  21147. // this._boundingInfo is being created here
  21148. this._updateBoundingInfo();
  21149. }
  21150. // cannot be null.
  21151. return this._boundingInfo;
  21152. };
  21153. /**
  21154. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21155. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21156. * @returns the current mesh
  21157. */
  21158. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21159. if (includeDescendants === void 0) { includeDescendants = true; }
  21160. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21161. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21162. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21163. if (maxDimension === 0) {
  21164. return this;
  21165. }
  21166. var scale = 1 / maxDimension;
  21167. this.scaling.scaleInPlace(scale);
  21168. return this;
  21169. };
  21170. /**
  21171. * Overwrite the current bounding info
  21172. * @param boundingInfo defines the new bounding info
  21173. * @returns the current mesh
  21174. */
  21175. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21176. this._boundingInfo = boundingInfo;
  21177. return this;
  21178. };
  21179. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21180. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21181. get: function () {
  21182. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21183. },
  21184. enumerable: true,
  21185. configurable: true
  21186. });
  21187. /** @hidden */
  21188. AbstractMesh.prototype._preActivate = function () {
  21189. };
  21190. /** @hidden */
  21191. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21192. };
  21193. /** @hidden */
  21194. AbstractMesh.prototype._activate = function (renderId) {
  21195. this._renderId = renderId;
  21196. };
  21197. /**
  21198. * Gets the current world matrix
  21199. * @returns a Matrix
  21200. */
  21201. AbstractMesh.prototype.getWorldMatrix = function () {
  21202. if (this._masterMesh) {
  21203. return this._masterMesh.getWorldMatrix();
  21204. }
  21205. return _super.prototype.getWorldMatrix.call(this);
  21206. };
  21207. /** @hidden */
  21208. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21209. if (this._masterMesh) {
  21210. return this._masterMesh._getWorldMatrixDeterminant();
  21211. }
  21212. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21213. };
  21214. // ================================== Point of View Movement =================================
  21215. /**
  21216. * Perform relative position change from the point of view of behind the front of the mesh.
  21217. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21218. * Supports definition of mesh facing forward or backward
  21219. * @param amountRight defines the distance on the right axis
  21220. * @param amountUp defines the distance on the up axis
  21221. * @param amountForward defines the distance on the forward axis
  21222. * @returns the current mesh
  21223. */
  21224. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21225. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21226. return this;
  21227. };
  21228. /**
  21229. * Calculate relative position change from the point of view of behind the front of the mesh.
  21230. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21231. * Supports definition of mesh facing forward or backward
  21232. * @param amountRight defines the distance on the right axis
  21233. * @param amountUp defines the distance on the up axis
  21234. * @param amountForward defines the distance on the forward axis
  21235. * @returns the new displacement vector
  21236. */
  21237. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21238. var rotMatrix = new BABYLON.Matrix();
  21239. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21240. rotQuaternion.toRotationMatrix(rotMatrix);
  21241. var translationDelta = BABYLON.Vector3.Zero();
  21242. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21243. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21244. return translationDelta;
  21245. };
  21246. // ================================== Point of View Rotation =================================
  21247. /**
  21248. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21249. * Supports definition of mesh facing forward or backward
  21250. * @param flipBack defines the flip
  21251. * @param twirlClockwise defines the twirl
  21252. * @param tiltRight defines the tilt
  21253. * @returns the current mesh
  21254. */
  21255. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21256. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21257. return this;
  21258. };
  21259. /**
  21260. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21261. * Supports definition of mesh facing forward or backward.
  21262. * @param flipBack defines the flip
  21263. * @param twirlClockwise defines the twirl
  21264. * @param tiltRight defines the tilt
  21265. * @returns the new rotation vector
  21266. */
  21267. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21268. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21269. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21270. };
  21271. /**
  21272. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21273. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21274. * @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
  21275. * @returns the new bounding vectors
  21276. */
  21277. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21278. if (includeDescendants === void 0) { includeDescendants = true; }
  21279. if (predicate === void 0) { predicate = null; }
  21280. // Ensures that all world matrix will be recomputed.
  21281. this.getScene().incrementRenderId();
  21282. this.computeWorldMatrix(true);
  21283. var min;
  21284. var max;
  21285. var boundingInfo = this.getBoundingInfo();
  21286. if (!this.subMeshes) {
  21287. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21288. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21289. }
  21290. else {
  21291. min = boundingInfo.boundingBox.minimumWorld;
  21292. max = boundingInfo.boundingBox.maximumWorld;
  21293. }
  21294. if (includeDescendants) {
  21295. var descendants = this.getDescendants(false);
  21296. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21297. var descendant = descendants_1[_i];
  21298. var childMesh = descendant;
  21299. childMesh.computeWorldMatrix(true);
  21300. // Filters meshes based on custom predicate function.
  21301. if (predicate && !predicate(childMesh)) {
  21302. continue;
  21303. }
  21304. //make sure we have the needed params to get mix and max
  21305. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21306. continue;
  21307. }
  21308. var childBoundingInfo = childMesh.getBoundingInfo();
  21309. var boundingBox = childBoundingInfo.boundingBox;
  21310. var minBox = boundingBox.minimumWorld;
  21311. var maxBox = boundingBox.maximumWorld;
  21312. BABYLON.Tools.CheckExtends(minBox, min, max);
  21313. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21314. }
  21315. }
  21316. return {
  21317. min: min,
  21318. max: max
  21319. };
  21320. };
  21321. /** @hidden */
  21322. AbstractMesh.prototype._updateBoundingInfo = function () {
  21323. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21324. this._boundingInfo.update(this.worldMatrixFromCache);
  21325. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21326. return this;
  21327. };
  21328. /** @hidden */
  21329. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21330. if (!this.subMeshes) {
  21331. return this;
  21332. }
  21333. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21334. var subMesh = this.subMeshes[subIndex];
  21335. if (!subMesh.IsGlobal) {
  21336. subMesh.updateBoundingInfo(matrix);
  21337. }
  21338. }
  21339. return this;
  21340. };
  21341. /** @hidden */
  21342. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21343. // Bounding info
  21344. this._updateBoundingInfo();
  21345. };
  21346. /**
  21347. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21348. * A mesh is in the frustum if its bounding box intersects the frustum
  21349. * @param frustumPlanes defines the frustum to test
  21350. * @returns true if the mesh is in the frustum planes
  21351. */
  21352. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21353. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21354. };
  21355. /**
  21356. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21357. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21358. * @param frustumPlanes defines the frustum to test
  21359. * @returns true if the mesh is completely in the frustum planes
  21360. */
  21361. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21362. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21363. };
  21364. /**
  21365. * True if the mesh intersects another mesh or a SolidParticle object
  21366. * @param mesh defines a target mesh or SolidParticle to test
  21367. * @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)
  21368. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21369. * @returns true if there is an intersection
  21370. */
  21371. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21372. if (precise === void 0) { precise = false; }
  21373. if (!this._boundingInfo || !mesh._boundingInfo) {
  21374. return false;
  21375. }
  21376. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21377. return true;
  21378. }
  21379. if (includeDescendants) {
  21380. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21381. var child = _a[_i];
  21382. if (child.intersectsMesh(mesh, precise, true)) {
  21383. return true;
  21384. }
  21385. }
  21386. }
  21387. return false;
  21388. };
  21389. /**
  21390. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21391. * @param point defines the point to test
  21392. * @returns true if there is an intersection
  21393. */
  21394. AbstractMesh.prototype.intersectsPoint = function (point) {
  21395. if (!this._boundingInfo) {
  21396. return false;
  21397. }
  21398. return this._boundingInfo.intersectsPoint(point);
  21399. };
  21400. /**
  21401. * Gets the position of the current mesh in camera space
  21402. * @param camera defines the camera to use
  21403. * @returns a position
  21404. */
  21405. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21406. if (camera === void 0) { camera = null; }
  21407. if (!camera) {
  21408. camera = this.getScene().activeCamera;
  21409. }
  21410. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21411. };
  21412. /**
  21413. * Returns the distance from the mesh to the active camera
  21414. * @param camera defines the camera to use
  21415. * @returns the distance
  21416. */
  21417. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21418. if (camera === void 0) { camera = null; }
  21419. if (!camera) {
  21420. camera = this.getScene().activeCamera;
  21421. }
  21422. return this.absolutePosition.subtract(camera.position).length();
  21423. };
  21424. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21425. // Collisions
  21426. /**
  21427. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21428. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21429. */
  21430. get: function () {
  21431. return this._checkCollisions;
  21432. },
  21433. set: function (collisionEnabled) {
  21434. this._checkCollisions = collisionEnabled;
  21435. if (this.getScene().workerCollisions) {
  21436. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21437. }
  21438. },
  21439. enumerable: true,
  21440. configurable: true
  21441. });
  21442. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21443. /**
  21444. * Gets Collider object used to compute collisions (not physics)
  21445. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21446. */
  21447. get: function () {
  21448. return this._collider;
  21449. },
  21450. enumerable: true,
  21451. configurable: true
  21452. });
  21453. /**
  21454. * Move the mesh using collision engine
  21455. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21456. * @param displacement defines the requested displacement vector
  21457. * @returns the current mesh
  21458. */
  21459. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21460. var globalPosition = this.getAbsolutePosition();
  21461. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21462. if (!this._collider) {
  21463. this._collider = new BABYLON.Collider();
  21464. }
  21465. this._collider._radius = this.ellipsoid;
  21466. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21467. return this;
  21468. };
  21469. // Collisions
  21470. /** @hidden */
  21471. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21472. this._generatePointsArray();
  21473. if (!this._positions) {
  21474. return this;
  21475. }
  21476. // Transformation
  21477. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21478. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21479. subMesh._lastColliderWorldVertices = [];
  21480. subMesh._trianglePlanes = [];
  21481. var start = subMesh.verticesStart;
  21482. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21483. for (var i = start; i < end; i++) {
  21484. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21485. }
  21486. }
  21487. // Collide
  21488. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21489. if (collider.collisionFound) {
  21490. collider.collidedMesh = this;
  21491. }
  21492. return this;
  21493. };
  21494. /** @hidden */
  21495. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21496. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21497. var len = subMeshes.length;
  21498. for (var index = 0; index < len; index++) {
  21499. var subMesh = subMeshes.data[index];
  21500. // Bounding test
  21501. if (len > 1 && !subMesh._checkCollision(collider))
  21502. continue;
  21503. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21504. }
  21505. return this;
  21506. };
  21507. /** @hidden */
  21508. AbstractMesh.prototype._checkCollision = function (collider) {
  21509. // Bounding box test
  21510. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21511. return this;
  21512. // Transformation matrix
  21513. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  21514. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  21515. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  21516. return this;
  21517. };
  21518. // Picking
  21519. /** @hidden */
  21520. AbstractMesh.prototype._generatePointsArray = function () {
  21521. return false;
  21522. };
  21523. /**
  21524. * Checks if the passed Ray intersects with the mesh
  21525. * @param ray defines the ray to use
  21526. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21527. * @returns the picking info
  21528. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21529. */
  21530. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21531. var pickingInfo = new BABYLON.PickingInfo();
  21532. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21533. return pickingInfo;
  21534. }
  21535. if (!this._generatePointsArray()) {
  21536. return pickingInfo;
  21537. }
  21538. var intersectInfo = null;
  21539. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21540. var len = subMeshes.length;
  21541. for (var index = 0; index < len; index++) {
  21542. var subMesh = subMeshes.data[index];
  21543. // Bounding test
  21544. if (len > 1 && !subMesh.canIntersects(ray))
  21545. continue;
  21546. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21547. if (currentIntersectInfo) {
  21548. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21549. intersectInfo = currentIntersectInfo;
  21550. intersectInfo.subMeshId = index;
  21551. if (fastCheck) {
  21552. break;
  21553. }
  21554. }
  21555. }
  21556. }
  21557. if (intersectInfo) {
  21558. // Get picked point
  21559. var world = this.getWorldMatrix();
  21560. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21561. var direction = ray.direction.clone();
  21562. direction = direction.scale(intersectInfo.distance);
  21563. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21564. var pickedPoint = worldOrigin.add(worldDirection);
  21565. // Return result
  21566. pickingInfo.hit = true;
  21567. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21568. pickingInfo.pickedPoint = pickedPoint;
  21569. pickingInfo.pickedMesh = this;
  21570. pickingInfo.bu = intersectInfo.bu || 0;
  21571. pickingInfo.bv = intersectInfo.bv || 0;
  21572. pickingInfo.faceId = intersectInfo.faceId;
  21573. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21574. return pickingInfo;
  21575. }
  21576. return pickingInfo;
  21577. };
  21578. /**
  21579. * Clones the current mesh
  21580. * @param name defines the mesh name
  21581. * @param newParent defines the new mesh parent
  21582. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21583. * @returns the new mesh
  21584. */
  21585. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21586. return null;
  21587. };
  21588. /**
  21589. * Disposes all the submeshes of the current meshnp
  21590. * @returns the current mesh
  21591. */
  21592. AbstractMesh.prototype.releaseSubMeshes = function () {
  21593. if (this.subMeshes) {
  21594. while (this.subMeshes.length) {
  21595. this.subMeshes[0].dispose();
  21596. }
  21597. }
  21598. else {
  21599. this.subMeshes = new Array();
  21600. }
  21601. return this;
  21602. };
  21603. /**
  21604. * Releases resources associated with this abstract mesh.
  21605. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21606. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21607. */
  21608. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21609. var _this = this;
  21610. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21611. var index;
  21612. // Smart Array Retainers.
  21613. this.getScene().freeActiveMeshes();
  21614. this.getScene().freeRenderingGroups();
  21615. // Action manager
  21616. if (this.actionManager !== undefined && this.actionManager !== null) {
  21617. this.actionManager.dispose();
  21618. this.actionManager = null;
  21619. }
  21620. // Skeleton
  21621. this._skeleton = null;
  21622. // Intersections in progress
  21623. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21624. var other = this._intersectionsInProgress[index];
  21625. var pos = other._intersectionsInProgress.indexOf(this);
  21626. other._intersectionsInProgress.splice(pos, 1);
  21627. }
  21628. this._intersectionsInProgress = [];
  21629. // Lights
  21630. var lights = this.getScene().lights;
  21631. lights.forEach(function (light) {
  21632. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21633. if (meshIndex !== -1) {
  21634. light.includedOnlyMeshes.splice(meshIndex, 1);
  21635. }
  21636. meshIndex = light.excludedMeshes.indexOf(_this);
  21637. if (meshIndex !== -1) {
  21638. light.excludedMeshes.splice(meshIndex, 1);
  21639. }
  21640. // Shadow generators
  21641. var generator = light.getShadowGenerator();
  21642. if (generator) {
  21643. var shadowMap = generator.getShadowMap();
  21644. if (shadowMap && shadowMap.renderList) {
  21645. meshIndex = shadowMap.renderList.indexOf(_this);
  21646. if (meshIndex !== -1) {
  21647. shadowMap.renderList.splice(meshIndex, 1);
  21648. }
  21649. }
  21650. }
  21651. });
  21652. // SubMeshes
  21653. if (this.getClassName() !== "InstancedMesh") {
  21654. this.releaseSubMeshes();
  21655. }
  21656. // Query
  21657. var engine = this.getScene().getEngine();
  21658. if (this._occlusionQuery) {
  21659. this.isOcclusionQueryInProgress = false;
  21660. engine.deleteQuery(this._occlusionQuery);
  21661. this._occlusionQuery = null;
  21662. }
  21663. // Engine
  21664. engine.wipeCaches();
  21665. // Remove from scene
  21666. this.getScene().removeMesh(this);
  21667. if (disposeMaterialAndTextures) {
  21668. if (this.material) {
  21669. this.material.dispose(false, true);
  21670. }
  21671. }
  21672. if (!doNotRecurse) {
  21673. // Particles
  21674. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21675. if (this.getScene().particleSystems[index].emitter === this) {
  21676. this.getScene().particleSystems[index].dispose();
  21677. index--;
  21678. }
  21679. }
  21680. }
  21681. // facet data
  21682. if (this._facetData.facetDataEnabled) {
  21683. this.disableFacetData();
  21684. }
  21685. this.onAfterWorldMatrixUpdateObservable.clear();
  21686. this.onCollideObservable.clear();
  21687. this.onCollisionPositionChangeObservable.clear();
  21688. this.onRebuildObservable.clear();
  21689. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21690. };
  21691. /**
  21692. * Adds the passed mesh as a child to the current mesh
  21693. * @param mesh defines the child mesh
  21694. * @returns the current mesh
  21695. */
  21696. AbstractMesh.prototype.addChild = function (mesh) {
  21697. mesh.setParent(this);
  21698. return this;
  21699. };
  21700. /**
  21701. * Removes the passed mesh from the current mesh children list
  21702. * @param mesh defines the child mesh
  21703. * @returns the current mesh
  21704. */
  21705. AbstractMesh.prototype.removeChild = function (mesh) {
  21706. mesh.setParent(null);
  21707. return this;
  21708. };
  21709. // Facet data
  21710. /** @hidden */
  21711. AbstractMesh.prototype._initFacetData = function () {
  21712. var data = this._facetData;
  21713. if (!data.facetNormals) {
  21714. data.facetNormals = new Array();
  21715. }
  21716. if (!data.facetPositions) {
  21717. data.facetPositions = new Array();
  21718. }
  21719. if (!data.facetPartitioning) {
  21720. data.facetPartitioning = new Array();
  21721. }
  21722. data.facetNb = (this.getIndices().length / 3) | 0;
  21723. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21724. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21725. for (var f = 0; f < data.facetNb; f++) {
  21726. data.facetNormals[f] = BABYLON.Vector3.Zero();
  21727. data.facetPositions[f] = BABYLON.Vector3.Zero();
  21728. }
  21729. data.facetDataEnabled = true;
  21730. return this;
  21731. };
  21732. /**
  21733. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21734. * This method can be called within the render loop.
  21735. * 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
  21736. * @returns the current mesh
  21737. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21738. */
  21739. AbstractMesh.prototype.updateFacetData = function () {
  21740. var data = this._facetData;
  21741. if (!data.facetDataEnabled) {
  21742. this._initFacetData();
  21743. }
  21744. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21745. var indices = this.getIndices();
  21746. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21747. var bInfo = this.getBoundingInfo();
  21748. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  21749. // init arrays, matrix and sort function on first call
  21750. data.facetDepthSortEnabled = true;
  21751. if (indices instanceof Uint16Array) {
  21752. data.depthSortedIndices = new Uint16Array(indices);
  21753. }
  21754. else if (indices instanceof Uint32Array) {
  21755. data.depthSortedIndices = new Uint32Array(indices);
  21756. }
  21757. else {
  21758. var needs32bits = false;
  21759. for (var i = 0; i < indices.length; i++) {
  21760. if (indices[i] > 65535) {
  21761. needs32bits = true;
  21762. break;
  21763. }
  21764. }
  21765. if (needs32bits) {
  21766. data.depthSortedIndices = new Uint32Array(indices);
  21767. }
  21768. else {
  21769. data.depthSortedIndices = new Uint16Array(indices);
  21770. }
  21771. }
  21772. data.facetDepthSortFunction = function (f1, f2) {
  21773. return (f2.sqDistance - f1.sqDistance);
  21774. };
  21775. if (!data.facetDepthSortFrom) {
  21776. var camera = this.getScene().activeCamera;
  21777. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21778. }
  21779. data.depthSortedFacets = [];
  21780. for (var f = 0; f < data.facetNb; f++) {
  21781. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21782. data.depthSortedFacets.push(depthSortedFacet);
  21783. }
  21784. data.invertedMatrix = BABYLON.Matrix.Identity();
  21785. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21786. }
  21787. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21788. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21789. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21790. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  21791. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  21792. data.subDiv.max = data.partitioningSubdivisions;
  21793. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21794. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  21795. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  21796. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  21797. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  21798. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  21799. // set the parameters for ComputeNormals()
  21800. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  21801. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  21802. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21803. data.facetParameters.bInfo = bInfo;
  21804. data.facetParameters.bbSize = data.bbSize;
  21805. data.facetParameters.subDiv = data.subDiv;
  21806. data.facetParameters.ratio = this.partitioningBBoxRatio;
  21807. data.facetParameters.depthSort = data.facetDepthSort;
  21808. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21809. this.computeWorldMatrix(true);
  21810. this._worldMatrix.invertToRef(data.invertedMatrix);
  21811. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  21812. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  21813. }
  21814. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  21815. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  21816. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21817. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  21818. var l = (data.depthSortedIndices.length / 3) | 0;
  21819. for (var f = 0; f < l; f++) {
  21820. var sind = data.depthSortedFacets[f].ind;
  21821. data.depthSortedIndices[f * 3] = indices[sind];
  21822. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21823. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21824. }
  21825. this.updateIndices(data.depthSortedIndices);
  21826. }
  21827. return this;
  21828. };
  21829. /**
  21830. * Returns the facetLocalNormals array.
  21831. * The normals are expressed in the mesh local spac
  21832. * @returns an array of Vector3
  21833. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21834. */
  21835. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21836. if (!this._facetData.facetNormals) {
  21837. this.updateFacetData();
  21838. }
  21839. return this._facetData.facetNormals;
  21840. };
  21841. /**
  21842. * Returns the facetLocalPositions array.
  21843. * The facet positions are expressed in the mesh local space
  21844. * @returns an array of Vector3
  21845. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21846. */
  21847. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21848. if (!this._facetData.facetPositions) {
  21849. this.updateFacetData();
  21850. }
  21851. return this._facetData.facetPositions;
  21852. };
  21853. /**
  21854. * Returns the facetLocalPartioning array
  21855. * @returns an array of array of numbers
  21856. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21857. */
  21858. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21859. if (!this._facetData.facetPartitioning) {
  21860. this.updateFacetData();
  21861. }
  21862. return this._facetData.facetPartitioning;
  21863. };
  21864. /**
  21865. * Returns the i-th facet position in the world system.
  21866. * This method allocates a new Vector3 per call
  21867. * @param i defines the facet index
  21868. * @returns a new Vector3
  21869. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21870. */
  21871. AbstractMesh.prototype.getFacetPosition = function (i) {
  21872. var pos = BABYLON.Vector3.Zero();
  21873. this.getFacetPositionToRef(i, pos);
  21874. return pos;
  21875. };
  21876. /**
  21877. * Sets the reference Vector3 with the i-th facet position in the world system
  21878. * @param i defines the facet index
  21879. * @param ref defines the target vector
  21880. * @returns the current mesh
  21881. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21882. */
  21883. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21884. var localPos = (this.getFacetLocalPositions())[i];
  21885. var world = this.getWorldMatrix();
  21886. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21887. return this;
  21888. };
  21889. /**
  21890. * Returns the i-th facet normal in the world system.
  21891. * This method allocates a new Vector3 per call
  21892. * @param i defines the facet index
  21893. * @returns a new Vector3
  21894. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21895. */
  21896. AbstractMesh.prototype.getFacetNormal = function (i) {
  21897. var norm = BABYLON.Vector3.Zero();
  21898. this.getFacetNormalToRef(i, norm);
  21899. return norm;
  21900. };
  21901. /**
  21902. * Sets the reference Vector3 with the i-th facet normal in the world system
  21903. * @param i defines the facet index
  21904. * @param ref defines the target vector
  21905. * @returns the current mesh
  21906. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21907. */
  21908. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21909. var localNorm = (this.getFacetLocalNormals())[i];
  21910. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21911. return this;
  21912. };
  21913. /**
  21914. * 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)
  21915. * @param x defines x coordinate
  21916. * @param y defines y coordinate
  21917. * @param z defines z coordinate
  21918. * @returns the array of facet indexes
  21919. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21920. */
  21921. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21922. var bInfo = this.getBoundingInfo();
  21923. var data = this._facetData;
  21924. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  21925. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  21926. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  21927. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  21928. return null;
  21929. }
  21930. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  21931. };
  21932. /**
  21933. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21934. * @param projected sets as the (x,y,z) world projection on the facet
  21935. * @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
  21936. * @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
  21937. * @param x defines x coordinate
  21938. * @param y defines y coordinate
  21939. * @param z defines z coordinate
  21940. * @returns the face index if found (or null instead)
  21941. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21942. */
  21943. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21944. if (checkFace === void 0) { checkFace = false; }
  21945. if (facing === void 0) { facing = true; }
  21946. var world = this.getWorldMatrix();
  21947. var invMat = BABYLON.Tmp.Matrix[5];
  21948. world.invertToRef(invMat);
  21949. var invVect = BABYLON.Tmp.Vector3[8];
  21950. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21951. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21952. if (projected) {
  21953. // tranform the local computed projected vector to world coordinates
  21954. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21955. }
  21956. return closest;
  21957. };
  21958. /**
  21959. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21960. * @param projected sets as the (x,y,z) local projection on the facet
  21961. * @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
  21962. * @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
  21963. * @param x defines x coordinate
  21964. * @param y defines y coordinate
  21965. * @param z defines z coordinate
  21966. * @returns the face index if found (or null instead)
  21967. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21968. */
  21969. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21970. if (checkFace === void 0) { checkFace = false; }
  21971. if (facing === void 0) { facing = true; }
  21972. var closest = null;
  21973. var tmpx = 0.0;
  21974. var tmpy = 0.0;
  21975. var tmpz = 0.0;
  21976. var d = 0.0; // tmp dot facet normal * facet position
  21977. var t0 = 0.0;
  21978. var projx = 0.0;
  21979. var projy = 0.0;
  21980. var projz = 0.0;
  21981. // Get all the facets in the same partitioning block than (x, y, z)
  21982. var facetPositions = this.getFacetLocalPositions();
  21983. var facetNormals = this.getFacetLocalNormals();
  21984. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21985. if (!facetsInBlock) {
  21986. return null;
  21987. }
  21988. // Get the closest facet to (x, y, z)
  21989. var shortest = Number.MAX_VALUE; // init distance vars
  21990. var tmpDistance = shortest;
  21991. var fib; // current facet in the block
  21992. var norm; // current facet normal
  21993. var p0; // current facet barycenter position
  21994. // loop on all the facets in the current partitioning block
  21995. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21996. fib = facetsInBlock[idx];
  21997. norm = facetNormals[fib];
  21998. p0 = facetPositions[fib];
  21999. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22000. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22001. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22002. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22003. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22004. projx = x + norm.x * t0;
  22005. projy = y + norm.y * t0;
  22006. projz = z + norm.z * t0;
  22007. tmpx = projx - x;
  22008. tmpy = projy - y;
  22009. tmpz = projz - z;
  22010. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22011. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22012. shortest = tmpDistance;
  22013. closest = fib;
  22014. if (projected) {
  22015. projected.x = projx;
  22016. projected.y = projy;
  22017. projected.z = projz;
  22018. }
  22019. }
  22020. }
  22021. }
  22022. return closest;
  22023. };
  22024. /**
  22025. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22026. * @returns the parameters
  22027. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22028. */
  22029. AbstractMesh.prototype.getFacetDataParameters = function () {
  22030. return this._facetData.facetParameters;
  22031. };
  22032. /**
  22033. * Disables the feature FacetData and frees the related memory
  22034. * @returns the current mesh
  22035. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22036. */
  22037. AbstractMesh.prototype.disableFacetData = function () {
  22038. if (this._facetData.facetDataEnabled) {
  22039. this._facetData.facetDataEnabled = false;
  22040. this._facetData.facetPositions = new Array();
  22041. this._facetData.facetNormals = new Array();
  22042. this._facetData.facetPartitioning = new Array();
  22043. this._facetData.facetParameters = null;
  22044. this._facetData.depthSortedIndices = new Uint32Array(0);
  22045. }
  22046. return this;
  22047. };
  22048. /**
  22049. * Updates the AbstractMesh indices array
  22050. * @param indices defines the data source
  22051. * @returns the current mesh
  22052. */
  22053. AbstractMesh.prototype.updateIndices = function (indices) {
  22054. return this;
  22055. };
  22056. /**
  22057. * Creates new normals data for the mesh
  22058. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22059. * @returns the current mesh
  22060. */
  22061. AbstractMesh.prototype.createNormals = function (updatable) {
  22062. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22063. var indices = this.getIndices();
  22064. var normals;
  22065. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22066. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22067. }
  22068. else {
  22069. normals = [];
  22070. }
  22071. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22072. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22073. return this;
  22074. };
  22075. /**
  22076. * Align the mesh with a normal
  22077. * @param normal defines the normal to use
  22078. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22079. * @returns the current mesh
  22080. */
  22081. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22082. if (!upDirection) {
  22083. upDirection = BABYLON.Axis.Y;
  22084. }
  22085. var axisX = BABYLON.Tmp.Vector3[0];
  22086. var axisZ = BABYLON.Tmp.Vector3[1];
  22087. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22088. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22089. if (this.rotationQuaternion) {
  22090. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22091. }
  22092. else {
  22093. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22094. }
  22095. return this;
  22096. };
  22097. /** @hidden */
  22098. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22099. return false;
  22100. };
  22101. /** No occlusion */
  22102. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22103. /** Occlusion set to optimisitic */
  22104. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22105. /** Occlusion set to strict */
  22106. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22107. /** Use an accurante occlusion algorithm */
  22108. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22109. /** Use a conservative occlusion algorithm */
  22110. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22111. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22112. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22113. /** Culling strategy with bounding sphere only and then frustum culling */
  22114. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22115. return AbstractMesh;
  22116. }(BABYLON.TransformNode));
  22117. BABYLON.AbstractMesh = AbstractMesh;
  22118. })(BABYLON || (BABYLON = {}));
  22119. //# sourceMappingURL=babylon.abstractMesh.js.map
  22120. var BABYLON;
  22121. (function (BABYLON) {
  22122. /**
  22123. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22124. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22125. * 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.
  22126. */
  22127. var Light = /** @class */ (function (_super) {
  22128. __extends(Light, _super);
  22129. /**
  22130. * Creates a Light object in the scene.
  22131. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22132. * @param name The firendly name of the light
  22133. * @param scene The scene the light belongs too
  22134. */
  22135. function Light(name, scene) {
  22136. var _this = _super.call(this, name, scene) || this;
  22137. /**
  22138. * Diffuse gives the basic color to an object.
  22139. */
  22140. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22141. /**
  22142. * Specular produces a highlight color on an object.
  22143. * Note: This is note affecting PBR materials.
  22144. */
  22145. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22146. /**
  22147. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22148. * falling off base on range or angle.
  22149. * This can be set to any values in Light.FALLOFF_x.
  22150. *
  22151. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22152. * other types of materials.
  22153. */
  22154. _this.falloffType = Light.FALLOFF_DEFAULT;
  22155. /**
  22156. * Strength of the light.
  22157. * Note: By default it is define in the framework own unit.
  22158. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22159. */
  22160. _this.intensity = 1.0;
  22161. _this._range = Number.MAX_VALUE;
  22162. _this._inverseSquaredRange = 0;
  22163. /**
  22164. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22165. * of light.
  22166. */
  22167. _this._photometricScale = 1.0;
  22168. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22169. _this._radius = 0.00001;
  22170. /**
  22171. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22172. * exceeding the number allowed of the materials.
  22173. */
  22174. _this.renderPriority = 0;
  22175. _this._shadowEnabled = true;
  22176. _this._excludeWithLayerMask = 0;
  22177. _this._includeOnlyWithLayerMask = 0;
  22178. _this._lightmapMode = 0;
  22179. /**
  22180. * @hidden Internal use only.
  22181. */
  22182. _this._excludedMeshesIds = new Array();
  22183. /**
  22184. * @hidden Internal use only.
  22185. */
  22186. _this._includedOnlyMeshesIds = new Array();
  22187. _this.getScene().addLight(_this);
  22188. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22189. _this._buildUniformLayout();
  22190. _this.includedOnlyMeshes = new Array();
  22191. _this.excludedMeshes = new Array();
  22192. _this._resyncMeshes();
  22193. return _this;
  22194. }
  22195. Object.defineProperty(Light.prototype, "range", {
  22196. /**
  22197. * Defines how far from the source the light is impacting in scene units.
  22198. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22199. */
  22200. get: function () {
  22201. return this._range;
  22202. },
  22203. /**
  22204. * Defines how far from the source the light is impacting in scene units.
  22205. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22206. */
  22207. set: function (value) {
  22208. this._range = value;
  22209. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22210. },
  22211. enumerable: true,
  22212. configurable: true
  22213. });
  22214. Object.defineProperty(Light.prototype, "intensityMode", {
  22215. /**
  22216. * Gets the photometric scale used to interpret the intensity.
  22217. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22218. */
  22219. get: function () {
  22220. return this._intensityMode;
  22221. },
  22222. /**
  22223. * Sets the photometric scale used to interpret the intensity.
  22224. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22225. */
  22226. set: function (value) {
  22227. this._intensityMode = value;
  22228. this._computePhotometricScale();
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. ;
  22234. ;
  22235. Object.defineProperty(Light.prototype, "radius", {
  22236. /**
  22237. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22238. */
  22239. get: function () {
  22240. return this._radius;
  22241. },
  22242. /**
  22243. * sets the light radius used by PBR Materials to simulate soft area lights.
  22244. */
  22245. set: function (value) {
  22246. this._radius = value;
  22247. this._computePhotometricScale();
  22248. },
  22249. enumerable: true,
  22250. configurable: true
  22251. });
  22252. ;
  22253. ;
  22254. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22255. /**
  22256. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22257. * the current shadow generator.
  22258. */
  22259. get: function () {
  22260. return this._shadowEnabled;
  22261. },
  22262. /**
  22263. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22264. * the current shadow generator.
  22265. */
  22266. set: function (value) {
  22267. if (this._shadowEnabled === value) {
  22268. return;
  22269. }
  22270. this._shadowEnabled = value;
  22271. this._markMeshesAsLightDirty();
  22272. },
  22273. enumerable: true,
  22274. configurable: true
  22275. });
  22276. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22277. /**
  22278. * Gets the only meshes impacted by this light.
  22279. */
  22280. get: function () {
  22281. return this._includedOnlyMeshes;
  22282. },
  22283. /**
  22284. * Sets the only meshes impacted by this light.
  22285. */
  22286. set: function (value) {
  22287. this._includedOnlyMeshes = value;
  22288. this._hookArrayForIncludedOnly(value);
  22289. },
  22290. enumerable: true,
  22291. configurable: true
  22292. });
  22293. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22294. /**
  22295. * Gets the meshes not impacted by this light.
  22296. */
  22297. get: function () {
  22298. return this._excludedMeshes;
  22299. },
  22300. /**
  22301. * Sets the meshes not impacted by this light.
  22302. */
  22303. set: function (value) {
  22304. this._excludedMeshes = value;
  22305. this._hookArrayForExcluded(value);
  22306. },
  22307. enumerable: true,
  22308. configurable: true
  22309. });
  22310. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22311. /**
  22312. * Gets the layer id use to find what meshes are not impacted by the light.
  22313. * Inactive if 0
  22314. */
  22315. get: function () {
  22316. return this._excludeWithLayerMask;
  22317. },
  22318. /**
  22319. * Sets the layer id use to find what meshes are not impacted by the light.
  22320. * Inactive if 0
  22321. */
  22322. set: function (value) {
  22323. this._excludeWithLayerMask = value;
  22324. this._resyncMeshes();
  22325. },
  22326. enumerable: true,
  22327. configurable: true
  22328. });
  22329. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22330. /**
  22331. * Gets the layer id use to find what meshes are impacted by the light.
  22332. * Inactive if 0
  22333. */
  22334. get: function () {
  22335. return this._includeOnlyWithLayerMask;
  22336. },
  22337. /**
  22338. * Sets the layer id use to find what meshes are impacted by the light.
  22339. * Inactive if 0
  22340. */
  22341. set: function (value) {
  22342. this._includeOnlyWithLayerMask = value;
  22343. this._resyncMeshes();
  22344. },
  22345. enumerable: true,
  22346. configurable: true
  22347. });
  22348. Object.defineProperty(Light.prototype, "lightmapMode", {
  22349. /**
  22350. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22351. */
  22352. get: function () {
  22353. return this._lightmapMode;
  22354. },
  22355. /**
  22356. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22357. */
  22358. set: function (value) {
  22359. if (this._lightmapMode === value) {
  22360. return;
  22361. }
  22362. this._lightmapMode = value;
  22363. this._markMeshesAsLightDirty();
  22364. },
  22365. enumerable: true,
  22366. configurable: true
  22367. });
  22368. /**
  22369. * Returns the string "Light".
  22370. * @returns the class name
  22371. */
  22372. Light.prototype.getClassName = function () {
  22373. return "Light";
  22374. };
  22375. /**
  22376. * Converts the light information to a readable string for debug purpose.
  22377. * @param fullDetails Supports for multiple levels of logging within scene loading
  22378. * @returns the human readable light info
  22379. */
  22380. Light.prototype.toString = function (fullDetails) {
  22381. var ret = "Name: " + this.name;
  22382. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22383. if (this.animations) {
  22384. for (var i = 0; i < this.animations.length; i++) {
  22385. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22386. }
  22387. }
  22388. if (fullDetails) {
  22389. }
  22390. return ret;
  22391. };
  22392. /** @hidden */
  22393. Light.prototype._syncParentEnabledState = function () {
  22394. _super.prototype._syncParentEnabledState.call(this);
  22395. this._resyncMeshes();
  22396. };
  22397. /**
  22398. * Set the enabled state of this node.
  22399. * @param value - the new enabled state
  22400. */
  22401. Light.prototype.setEnabled = function (value) {
  22402. _super.prototype.setEnabled.call(this, value);
  22403. this._resyncMeshes();
  22404. };
  22405. /**
  22406. * Returns the Light associated shadow generator if any.
  22407. * @return the associated shadow generator.
  22408. */
  22409. Light.prototype.getShadowGenerator = function () {
  22410. return this._shadowGenerator;
  22411. };
  22412. /**
  22413. * Returns a Vector3, the absolute light position in the World.
  22414. * @returns the world space position of the light
  22415. */
  22416. Light.prototype.getAbsolutePosition = function () {
  22417. return BABYLON.Vector3.Zero();
  22418. };
  22419. /**
  22420. * Specifies if the light will affect the passed mesh.
  22421. * @param mesh The mesh to test against the light
  22422. * @return true the mesh is affected otherwise, false.
  22423. */
  22424. Light.prototype.canAffectMesh = function (mesh) {
  22425. if (!mesh) {
  22426. return true;
  22427. }
  22428. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22429. return false;
  22430. }
  22431. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22432. return false;
  22433. }
  22434. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22435. return false;
  22436. }
  22437. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22438. return false;
  22439. }
  22440. return true;
  22441. };
  22442. /**
  22443. * Sort function to order lights for rendering.
  22444. * @param a First Light object to compare to second.
  22445. * @param b Second Light object to compare first.
  22446. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22447. */
  22448. Light.CompareLightsPriority = function (a, b) {
  22449. //shadow-casting lights have priority over non-shadow-casting lights
  22450. //the renderPrioirty is a secondary sort criterion
  22451. if (a.shadowEnabled !== b.shadowEnabled) {
  22452. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22453. }
  22454. return b.renderPriority - a.renderPriority;
  22455. };
  22456. /**
  22457. * Releases resources associated with this node.
  22458. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22459. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22460. */
  22461. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22462. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22463. if (this._shadowGenerator) {
  22464. this._shadowGenerator.dispose();
  22465. this._shadowGenerator = null;
  22466. }
  22467. // Animations
  22468. this.getScene().stopAnimation(this);
  22469. // Remove from meshes
  22470. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22471. var mesh = _a[_i];
  22472. mesh._removeLightSource(this);
  22473. }
  22474. this._uniformBuffer.dispose();
  22475. // Remove from scene
  22476. this.getScene().removeLight(this);
  22477. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22478. };
  22479. /**
  22480. * Returns the light type ID (integer).
  22481. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22482. */
  22483. Light.prototype.getTypeID = function () {
  22484. return 0;
  22485. };
  22486. /**
  22487. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22488. * @returns the scaled intensity in intensity mode unit
  22489. */
  22490. Light.prototype.getScaledIntensity = function () {
  22491. return this._photometricScale * this.intensity;
  22492. };
  22493. /**
  22494. * Returns a new Light object, named "name", from the current one.
  22495. * @param name The name of the cloned light
  22496. * @returns the new created light
  22497. */
  22498. Light.prototype.clone = function (name) {
  22499. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22500. if (!constructor) {
  22501. return null;
  22502. }
  22503. return BABYLON.SerializationHelper.Clone(constructor, this);
  22504. };
  22505. /**
  22506. * Serializes the current light into a Serialization object.
  22507. * @returns the serialized object.
  22508. */
  22509. Light.prototype.serialize = function () {
  22510. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22511. // Type
  22512. serializationObject.type = this.getTypeID();
  22513. // Parent
  22514. if (this.parent) {
  22515. serializationObject.parentId = this.parent.id;
  22516. }
  22517. // Inclusion / exclusions
  22518. if (this.excludedMeshes.length > 0) {
  22519. serializationObject.excludedMeshesIds = [];
  22520. this.excludedMeshes.forEach(function (mesh) {
  22521. serializationObject.excludedMeshesIds.push(mesh.id);
  22522. });
  22523. }
  22524. if (this.includedOnlyMeshes.length > 0) {
  22525. serializationObject.includedOnlyMeshesIds = [];
  22526. this.includedOnlyMeshes.forEach(function (mesh) {
  22527. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22528. });
  22529. }
  22530. // Animations
  22531. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22532. serializationObject.ranges = this.serializeAnimationRanges();
  22533. return serializationObject;
  22534. };
  22535. /**
  22536. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22537. * This new light is named "name" and added to the passed scene.
  22538. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22539. * @param name The friendly name of the light
  22540. * @param scene The scene the new light will belong to
  22541. * @returns the constructor function
  22542. */
  22543. Light.GetConstructorFromName = function (type, name, scene) {
  22544. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22545. if (constructorFunc) {
  22546. return constructorFunc;
  22547. }
  22548. // Default to no light for none present once.
  22549. return null;
  22550. };
  22551. /**
  22552. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22553. * @param parsedLight The JSON representation of the light
  22554. * @param scene The scene to create the parsed light in
  22555. * @returns the created light after parsing
  22556. */
  22557. Light.Parse = function (parsedLight, scene) {
  22558. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22559. if (!constructor) {
  22560. return null;
  22561. }
  22562. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22563. // Inclusion / exclusions
  22564. if (parsedLight.excludedMeshesIds) {
  22565. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22566. }
  22567. if (parsedLight.includedOnlyMeshesIds) {
  22568. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22569. }
  22570. // Parent
  22571. if (parsedLight.parentId) {
  22572. light._waitingParentId = parsedLight.parentId;
  22573. }
  22574. // Animations
  22575. if (parsedLight.animations) {
  22576. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22577. var parsedAnimation = parsedLight.animations[animationIndex];
  22578. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22579. }
  22580. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22581. }
  22582. if (parsedLight.autoAnimate) {
  22583. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22584. }
  22585. return light;
  22586. };
  22587. Light.prototype._hookArrayForExcluded = function (array) {
  22588. var _this = this;
  22589. var oldPush = array.push;
  22590. array.push = function () {
  22591. var items = [];
  22592. for (var _i = 0; _i < arguments.length; _i++) {
  22593. items[_i] = arguments[_i];
  22594. }
  22595. var result = oldPush.apply(array, items);
  22596. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22597. var item = items_1[_a];
  22598. item._resyncLighSource(_this);
  22599. }
  22600. return result;
  22601. };
  22602. var oldSplice = array.splice;
  22603. array.splice = function (index, deleteCount) {
  22604. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22605. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22606. var item = deleted_1[_i];
  22607. item._resyncLighSource(_this);
  22608. }
  22609. return deleted;
  22610. };
  22611. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22612. var item = array_1[_i];
  22613. item._resyncLighSource(this);
  22614. }
  22615. };
  22616. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22617. var _this = this;
  22618. var oldPush = array.push;
  22619. array.push = function () {
  22620. var items = [];
  22621. for (var _i = 0; _i < arguments.length; _i++) {
  22622. items[_i] = arguments[_i];
  22623. }
  22624. var result = oldPush.apply(array, items);
  22625. _this._resyncMeshes();
  22626. return result;
  22627. };
  22628. var oldSplice = array.splice;
  22629. array.splice = function (index, deleteCount) {
  22630. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22631. _this._resyncMeshes();
  22632. return deleted;
  22633. };
  22634. this._resyncMeshes();
  22635. };
  22636. Light.prototype._resyncMeshes = function () {
  22637. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22638. var mesh = _a[_i];
  22639. mesh._resyncLighSource(this);
  22640. }
  22641. };
  22642. /**
  22643. * Forces the meshes to update their light related information in their rendering used effects
  22644. * @hidden Internal Use Only
  22645. */
  22646. Light.prototype._markMeshesAsLightDirty = function () {
  22647. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22648. var mesh = _a[_i];
  22649. if (mesh._lightSources.indexOf(this) !== -1) {
  22650. mesh._markSubMeshesAsLightDirty();
  22651. }
  22652. }
  22653. };
  22654. /**
  22655. * Recomputes the cached photometric scale if needed.
  22656. */
  22657. Light.prototype._computePhotometricScale = function () {
  22658. this._photometricScale = this._getPhotometricScale();
  22659. this.getScene().resetCachedMaterial();
  22660. };
  22661. /**
  22662. * Returns the Photometric Scale according to the light type and intensity mode.
  22663. */
  22664. Light.prototype._getPhotometricScale = function () {
  22665. var photometricScale = 0.0;
  22666. var lightTypeID = this.getTypeID();
  22667. //get photometric mode
  22668. var photometricMode = this.intensityMode;
  22669. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22670. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22671. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22672. }
  22673. else {
  22674. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22675. }
  22676. }
  22677. //compute photometric scale
  22678. switch (lightTypeID) {
  22679. case Light.LIGHTTYPEID_POINTLIGHT:
  22680. case Light.LIGHTTYPEID_SPOTLIGHT:
  22681. switch (photometricMode) {
  22682. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22683. photometricScale = 1.0 / (4.0 * Math.PI);
  22684. break;
  22685. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22686. photometricScale = 1.0;
  22687. break;
  22688. case Light.INTENSITYMODE_LUMINANCE:
  22689. photometricScale = this.radius * this.radius;
  22690. break;
  22691. }
  22692. break;
  22693. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22694. switch (photometricMode) {
  22695. case Light.INTENSITYMODE_ILLUMINANCE:
  22696. photometricScale = 1.0;
  22697. break;
  22698. case Light.INTENSITYMODE_LUMINANCE:
  22699. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22700. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22701. var apexAngleRadians = this.radius;
  22702. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22703. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22704. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22705. photometricScale = solidAngle;
  22706. break;
  22707. }
  22708. break;
  22709. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22710. // No fall off in hemisperic light.
  22711. photometricScale = 1.0;
  22712. break;
  22713. }
  22714. return photometricScale;
  22715. };
  22716. /**
  22717. * Reorder the light in the scene according to their defined priority.
  22718. * @hidden Internal Use Only
  22719. */
  22720. Light.prototype._reorderLightsInScene = function () {
  22721. var scene = this.getScene();
  22722. if (this._renderPriority != 0) {
  22723. scene.requireLightSorting = true;
  22724. }
  22725. this.getScene().sortLightsByPriority();
  22726. };
  22727. /**
  22728. * Falloff Default: light is falling off following the material specification:
  22729. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22730. */
  22731. Light.FALLOFF_DEFAULT = 0;
  22732. /**
  22733. * Falloff Physical: light is falling off following the inverse squared distance law.
  22734. */
  22735. Light.FALLOFF_PHYSICAL = 1;
  22736. /**
  22737. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22738. * to enhance interoperability with other engines.
  22739. */
  22740. Light.FALLOFF_GLTF = 2;
  22741. /**
  22742. * Falloff Standard: light is falling off like in the standard material
  22743. * to enhance interoperability with other materials.
  22744. */
  22745. Light.FALLOFF_STANDARD = 3;
  22746. //lightmapMode Consts
  22747. /**
  22748. * If every light affecting the material is in this lightmapMode,
  22749. * material.lightmapTexture adds or multiplies
  22750. * (depends on material.useLightmapAsShadowmap)
  22751. * after every other light calculations.
  22752. */
  22753. Light.LIGHTMAP_DEFAULT = 0;
  22754. /**
  22755. * material.lightmapTexture as only diffuse lighting from this light
  22756. * adds only specular lighting from this light
  22757. * adds dynamic shadows
  22758. */
  22759. Light.LIGHTMAP_SPECULAR = 1;
  22760. /**
  22761. * material.lightmapTexture as only lighting
  22762. * no light calculation from this light
  22763. * only adds dynamic shadows from this light
  22764. */
  22765. Light.LIGHTMAP_SHADOWSONLY = 2;
  22766. // Intensity Mode Consts
  22767. /**
  22768. * Each light type uses the default quantity according to its type:
  22769. * point/spot lights use luminous intensity
  22770. * directional lights use illuminance
  22771. */
  22772. Light.INTENSITYMODE_AUTOMATIC = 0;
  22773. /**
  22774. * lumen (lm)
  22775. */
  22776. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22777. /**
  22778. * candela (lm/sr)
  22779. */
  22780. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22781. /**
  22782. * lux (lm/m^2)
  22783. */
  22784. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22785. /**
  22786. * nit (cd/m^2)
  22787. */
  22788. Light.INTENSITYMODE_LUMINANCE = 4;
  22789. // Light types ids const.
  22790. /**
  22791. * Light type const id of the point light.
  22792. */
  22793. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22794. /**
  22795. * Light type const id of the directional light.
  22796. */
  22797. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22798. /**
  22799. * Light type const id of the spot light.
  22800. */
  22801. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22802. /**
  22803. * Light type const id of the hemispheric light.
  22804. */
  22805. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22806. __decorate([
  22807. BABYLON.serializeAsColor3()
  22808. ], Light.prototype, "diffuse", void 0);
  22809. __decorate([
  22810. BABYLON.serializeAsColor3()
  22811. ], Light.prototype, "specular", void 0);
  22812. __decorate([
  22813. BABYLON.serialize()
  22814. ], Light.prototype, "falloffType", void 0);
  22815. __decorate([
  22816. BABYLON.serialize()
  22817. ], Light.prototype, "intensity", void 0);
  22818. __decorate([
  22819. BABYLON.serialize()
  22820. ], Light.prototype, "range", null);
  22821. __decorate([
  22822. BABYLON.serialize()
  22823. ], Light.prototype, "intensityMode", null);
  22824. __decorate([
  22825. BABYLON.serialize()
  22826. ], Light.prototype, "radius", null);
  22827. __decorate([
  22828. BABYLON.serialize()
  22829. ], Light.prototype, "_renderPriority", void 0);
  22830. __decorate([
  22831. BABYLON.expandToProperty("_reorderLightsInScene")
  22832. ], Light.prototype, "renderPriority", void 0);
  22833. __decorate([
  22834. BABYLON.serialize("shadowEnabled")
  22835. ], Light.prototype, "_shadowEnabled", void 0);
  22836. __decorate([
  22837. BABYLON.serialize("excludeWithLayerMask")
  22838. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22839. __decorate([
  22840. BABYLON.serialize("includeOnlyWithLayerMask")
  22841. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22842. __decorate([
  22843. BABYLON.serialize("lightmapMode")
  22844. ], Light.prototype, "_lightmapMode", void 0);
  22845. return Light;
  22846. }(BABYLON.Node));
  22847. BABYLON.Light = Light;
  22848. })(BABYLON || (BABYLON = {}));
  22849. //# sourceMappingURL=babylon.light.js.map
  22850. var BABYLON;
  22851. (function (BABYLON) {
  22852. /**
  22853. * This is the base class of all the camera used in the application.
  22854. * @see http://doc.babylonjs.com/features/cameras
  22855. */
  22856. var Camera = /** @class */ (function (_super) {
  22857. __extends(Camera, _super);
  22858. /**
  22859. * Instantiates a new camera object.
  22860. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22861. * @see http://doc.babylonjs.com/features/cameras
  22862. * @param name Defines the name of the camera in the scene
  22863. * @param position Defines the position of the camera
  22864. * @param scene Defines the scene the camera belongs too
  22865. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22866. */
  22867. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22868. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22869. var _this = _super.call(this, name, scene) || this;
  22870. /**
  22871. * The vector the camera should consider as up.
  22872. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22873. */
  22874. _this.upVector = BABYLON.Vector3.Up();
  22875. /**
  22876. * Define the current limit on the left side for an orthographic camera
  22877. * In scene unit
  22878. */
  22879. _this.orthoLeft = null;
  22880. /**
  22881. * Define the current limit on the right side for an orthographic camera
  22882. * In scene unit
  22883. */
  22884. _this.orthoRight = null;
  22885. /**
  22886. * Define the current limit on the bottom side for an orthographic camera
  22887. * In scene unit
  22888. */
  22889. _this.orthoBottom = null;
  22890. /**
  22891. * Define the current limit on the top side for an orthographic camera
  22892. * In scene unit
  22893. */
  22894. _this.orthoTop = null;
  22895. /**
  22896. * Field Of View is set in Radians. (default is 0.8)
  22897. */
  22898. _this.fov = 0.8;
  22899. /**
  22900. * Define the minimum distance the camera can see from.
  22901. * This is important to note that the depth buffer are not infinite and the closer it starts
  22902. * the more your scene might encounter depth fighting issue.
  22903. */
  22904. _this.minZ = 1;
  22905. /**
  22906. * Define the maximum distance the camera can see to.
  22907. * This is important to note that the depth buffer are not infinite and the further it end
  22908. * the more your scene might encounter depth fighting issue.
  22909. */
  22910. _this.maxZ = 10000.0;
  22911. /**
  22912. * Define the default inertia of the camera.
  22913. * This helps giving a smooth feeling to the camera movement.
  22914. */
  22915. _this.inertia = 0.9;
  22916. /**
  22917. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22918. */
  22919. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22920. /**
  22921. * Define wether the camera is intermediate.
  22922. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22923. */
  22924. _this.isIntermediate = false;
  22925. /**
  22926. * Define the viewport of the camera.
  22927. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22928. */
  22929. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22930. /**
  22931. * Restricts the camera to viewing objects with the same layerMask.
  22932. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22933. */
  22934. _this.layerMask = 0x0FFFFFFF;
  22935. /**
  22936. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22937. */
  22938. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22939. /**
  22940. * Rig mode of the camera.
  22941. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22942. * This is normally controlled byt the camera themselves as internal use.
  22943. */
  22944. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22945. /**
  22946. * Defines the list of custom render target the camera should render to.
  22947. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22948. * else in the scene.
  22949. */
  22950. _this.customRenderTargets = new Array();
  22951. /**
  22952. * Observable triggered when the camera view matrix has changed.
  22953. */
  22954. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22955. /**
  22956. * Observable triggered when the camera Projection matrix has changed.
  22957. */
  22958. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22959. /**
  22960. * Observable triggered when the inputs have been processed.
  22961. */
  22962. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22963. /**
  22964. * Observable triggered when reset has been called and applied to the camera.
  22965. */
  22966. _this.onRestoreStateObservable = new BABYLON.Observable();
  22967. /** @hidden */
  22968. _this._rigCameras = new Array();
  22969. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22970. /** @hidden */
  22971. _this._skipRendering = false;
  22972. /** @hidden */
  22973. _this._projectionMatrix = new BABYLON.Matrix();
  22974. /** @hidden */
  22975. _this._postProcesses = new Array();
  22976. /** @hidden */
  22977. _this._activeMeshes = new BABYLON.SmartArray(256);
  22978. _this._globalPosition = BABYLON.Vector3.Zero();
  22979. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22980. _this._doNotComputeProjectionMatrix = false;
  22981. _this._transformMatrix = BABYLON.Matrix.Zero();
  22982. _this._refreshFrustumPlanes = true;
  22983. _this.getScene().addCamera(_this);
  22984. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22985. _this.getScene().activeCamera = _this;
  22986. }
  22987. _this.position = position;
  22988. return _this;
  22989. }
  22990. /**
  22991. * Store current camera state (fov, position, etc..)
  22992. * @returns the camera
  22993. */
  22994. Camera.prototype.storeState = function () {
  22995. this._stateStored = true;
  22996. this._storedFov = this.fov;
  22997. return this;
  22998. };
  22999. /**
  23000. * Restores the camera state values if it has been stored. You must call storeState() first
  23001. */
  23002. Camera.prototype._restoreStateValues = function () {
  23003. if (!this._stateStored) {
  23004. return false;
  23005. }
  23006. this.fov = this._storedFov;
  23007. return true;
  23008. };
  23009. /**
  23010. * Restored camera state. You must call storeState() first.
  23011. * @returns true if restored and false otherwise
  23012. */
  23013. Camera.prototype.restoreState = function () {
  23014. if (this._restoreStateValues()) {
  23015. this.onRestoreStateObservable.notifyObservers(this);
  23016. return true;
  23017. }
  23018. return false;
  23019. };
  23020. /**
  23021. * Gets the class name of the camera.
  23022. * @returns the class name
  23023. */
  23024. Camera.prototype.getClassName = function () {
  23025. return "Camera";
  23026. };
  23027. /**
  23028. * Gets a string representation of the camera usefull for debug purpose.
  23029. * @param fullDetails Defines that a more verboe level of logging is required
  23030. * @returns the string representation
  23031. */
  23032. Camera.prototype.toString = function (fullDetails) {
  23033. var ret = "Name: " + this.name;
  23034. ret += ", type: " + this.getClassName();
  23035. if (this.animations) {
  23036. for (var i = 0; i < this.animations.length; i++) {
  23037. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23038. }
  23039. }
  23040. if (fullDetails) {
  23041. }
  23042. return ret;
  23043. };
  23044. Object.defineProperty(Camera.prototype, "globalPosition", {
  23045. /**
  23046. * Gets the current world space position of the camera.
  23047. */
  23048. get: function () {
  23049. return this._globalPosition;
  23050. },
  23051. enumerable: true,
  23052. configurable: true
  23053. });
  23054. /**
  23055. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23056. * @returns the active meshe list
  23057. */
  23058. Camera.prototype.getActiveMeshes = function () {
  23059. return this._activeMeshes;
  23060. };
  23061. /**
  23062. * Check wether a mesh is part of the current active mesh list of the camera
  23063. * @param mesh Defines the mesh to check
  23064. * @returns true if active, false otherwise
  23065. */
  23066. Camera.prototype.isActiveMesh = function (mesh) {
  23067. return (this._activeMeshes.indexOf(mesh) !== -1);
  23068. };
  23069. /**
  23070. * Is this camera ready to be used/rendered
  23071. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23072. * @return true if the camera is ready
  23073. */
  23074. Camera.prototype.isReady = function (completeCheck) {
  23075. if (completeCheck === void 0) { completeCheck = false; }
  23076. if (completeCheck) {
  23077. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23078. var pp = _a[_i];
  23079. if (pp && !pp.isReady()) {
  23080. return false;
  23081. }
  23082. }
  23083. }
  23084. return _super.prototype.isReady.call(this, completeCheck);
  23085. };
  23086. /** @hidden */
  23087. Camera.prototype._initCache = function () {
  23088. _super.prototype._initCache.call(this);
  23089. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23090. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23091. this._cache.mode = undefined;
  23092. this._cache.minZ = undefined;
  23093. this._cache.maxZ = undefined;
  23094. this._cache.fov = undefined;
  23095. this._cache.fovMode = undefined;
  23096. this._cache.aspectRatio = undefined;
  23097. this._cache.orthoLeft = undefined;
  23098. this._cache.orthoRight = undefined;
  23099. this._cache.orthoBottom = undefined;
  23100. this._cache.orthoTop = undefined;
  23101. this._cache.renderWidth = undefined;
  23102. this._cache.renderHeight = undefined;
  23103. };
  23104. /** @hidden */
  23105. Camera.prototype._updateCache = function (ignoreParentClass) {
  23106. if (!ignoreParentClass) {
  23107. _super.prototype._updateCache.call(this);
  23108. }
  23109. this._cache.position.copyFrom(this.position);
  23110. this._cache.upVector.copyFrom(this.upVector);
  23111. };
  23112. /** @hidden */
  23113. Camera.prototype._isSynchronized = function () {
  23114. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23115. };
  23116. /** @hidden */
  23117. Camera.prototype._isSynchronizedViewMatrix = function () {
  23118. if (!_super.prototype._isSynchronized.call(this))
  23119. return false;
  23120. return this._cache.position.equals(this.position)
  23121. && this._cache.upVector.equals(this.upVector)
  23122. && this.isSynchronizedWithParent();
  23123. };
  23124. /** @hidden */
  23125. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23126. var check = this._cache.mode === this.mode
  23127. && this._cache.minZ === this.minZ
  23128. && this._cache.maxZ === this.maxZ;
  23129. if (!check) {
  23130. return false;
  23131. }
  23132. var engine = this.getEngine();
  23133. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23134. check = this._cache.fov === this.fov
  23135. && this._cache.fovMode === this.fovMode
  23136. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23137. }
  23138. else {
  23139. check = this._cache.orthoLeft === this.orthoLeft
  23140. && this._cache.orthoRight === this.orthoRight
  23141. && this._cache.orthoBottom === this.orthoBottom
  23142. && this._cache.orthoTop === this.orthoTop
  23143. && this._cache.renderWidth === engine.getRenderWidth()
  23144. && this._cache.renderHeight === engine.getRenderHeight();
  23145. }
  23146. return check;
  23147. };
  23148. /**
  23149. * Attach the input controls to a specific dom element to get the input from.
  23150. * @param element Defines the element the controls should be listened from
  23151. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23152. */
  23153. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23154. };
  23155. /**
  23156. * Detach the current controls from the specified dom element.
  23157. * @param element Defines the element to stop listening the inputs from
  23158. */
  23159. Camera.prototype.detachControl = function (element) {
  23160. };
  23161. /**
  23162. * Update the camera state according to the different inputs gathered during the frame.
  23163. */
  23164. Camera.prototype.update = function () {
  23165. this._checkInputs();
  23166. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23167. this._updateRigCameras();
  23168. }
  23169. };
  23170. /** @hidden */
  23171. Camera.prototype._checkInputs = function () {
  23172. this.onAfterCheckInputsObservable.notifyObservers(this);
  23173. };
  23174. Object.defineProperty(Camera.prototype, "rigCameras", {
  23175. /** @hidden */
  23176. get: function () {
  23177. return this._rigCameras;
  23178. },
  23179. enumerable: true,
  23180. configurable: true
  23181. });
  23182. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23183. /**
  23184. * Gets the post process used by the rig cameras
  23185. */
  23186. get: function () {
  23187. return this._rigPostProcess;
  23188. },
  23189. enumerable: true,
  23190. configurable: true
  23191. });
  23192. /**
  23193. * Internal, gets the first post proces.
  23194. * @returns the first post process to be run on this camera.
  23195. */
  23196. Camera.prototype._getFirstPostProcess = function () {
  23197. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23198. if (this._postProcesses[ppIndex] !== null) {
  23199. return this._postProcesses[ppIndex];
  23200. }
  23201. }
  23202. return null;
  23203. };
  23204. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23205. // invalidate framebuffer
  23206. var firstPostProcess = this._getFirstPostProcess();
  23207. if (firstPostProcess) {
  23208. firstPostProcess.markTextureDirty();
  23209. }
  23210. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23211. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23212. var cam = this._rigCameras[i];
  23213. var rigPostProcess = cam._rigPostProcess;
  23214. // for VR rig, there does not have to be a post process
  23215. if (rigPostProcess) {
  23216. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23217. if (isPass) {
  23218. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23219. cam.isIntermediate = this._postProcesses.length === 0;
  23220. }
  23221. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23222. rigPostProcess.markTextureDirty();
  23223. }
  23224. else {
  23225. cam._postProcesses = this._postProcesses.slice(0);
  23226. }
  23227. }
  23228. };
  23229. /**
  23230. * Attach a post process to the camera.
  23231. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23232. * @param postProcess The post process to attach to the camera
  23233. * @param insertAt The position of the post process in case several of them are in use in the scene
  23234. * @returns the position the post process has been inserted at
  23235. */
  23236. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23237. if (insertAt === void 0) { insertAt = null; }
  23238. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23239. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23240. return 0;
  23241. }
  23242. if (insertAt == null || insertAt < 0) {
  23243. this._postProcesses.push(postProcess);
  23244. }
  23245. else if (this._postProcesses[insertAt] === null) {
  23246. this._postProcesses[insertAt] = postProcess;
  23247. }
  23248. else {
  23249. this._postProcesses.splice(insertAt, 0, postProcess);
  23250. }
  23251. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23252. return this._postProcesses.indexOf(postProcess);
  23253. };
  23254. /**
  23255. * Detach a post process to the camera.
  23256. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23257. * @param postProcess The post process to detach from the camera
  23258. */
  23259. Camera.prototype.detachPostProcess = function (postProcess) {
  23260. var idx = this._postProcesses.indexOf(postProcess);
  23261. if (idx !== -1) {
  23262. this._postProcesses[idx] = null;
  23263. }
  23264. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23265. };
  23266. /**
  23267. * Gets the current world matrix of the camera
  23268. */
  23269. Camera.prototype.getWorldMatrix = function () {
  23270. if (this._isSynchronizedViewMatrix()) {
  23271. return this._worldMatrix;
  23272. }
  23273. // Getting the the view matrix will also compute the world matrix.
  23274. this.getViewMatrix();
  23275. return this._worldMatrix;
  23276. };
  23277. /** @hidden */
  23278. Camera.prototype._getViewMatrix = function () {
  23279. return BABYLON.Matrix.Identity();
  23280. };
  23281. /**
  23282. * Gets the current view matrix of the camera.
  23283. * @param force forces the camera to recompute the matrix without looking at the cached state
  23284. * @returns the view matrix
  23285. */
  23286. Camera.prototype.getViewMatrix = function (force) {
  23287. if (!force && this._isSynchronizedViewMatrix()) {
  23288. return this._computedViewMatrix;
  23289. }
  23290. this.updateCache();
  23291. this._computedViewMatrix = this._getViewMatrix();
  23292. this._currentRenderId = this.getScene().getRenderId();
  23293. this._childRenderId = this._currentRenderId;
  23294. this._refreshFrustumPlanes = true;
  23295. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23296. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23297. }
  23298. this.onViewMatrixChangedObservable.notifyObservers(this);
  23299. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23300. return this._computedViewMatrix;
  23301. };
  23302. /**
  23303. * Freeze the projection matrix.
  23304. * It will prevent the cache check of the camera projection compute and can speed up perf
  23305. * if no parameter of the camera are meant to change
  23306. * @param projection Defines manually a projection if necessary
  23307. */
  23308. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23309. this._doNotComputeProjectionMatrix = true;
  23310. if (projection !== undefined) {
  23311. this._projectionMatrix = projection;
  23312. }
  23313. };
  23314. ;
  23315. /**
  23316. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23317. */
  23318. Camera.prototype.unfreezeProjectionMatrix = function () {
  23319. this._doNotComputeProjectionMatrix = false;
  23320. };
  23321. ;
  23322. /**
  23323. * Gets the current projection matrix of the camera.
  23324. * @param force forces the camera to recompute the matrix without looking at the cached state
  23325. * @returns the projection matrix
  23326. */
  23327. Camera.prototype.getProjectionMatrix = function (force) {
  23328. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23329. return this._projectionMatrix;
  23330. }
  23331. // Cache
  23332. this._cache.mode = this.mode;
  23333. this._cache.minZ = this.minZ;
  23334. this._cache.maxZ = this.maxZ;
  23335. // Matrix
  23336. this._refreshFrustumPlanes = true;
  23337. var engine = this.getEngine();
  23338. var scene = this.getScene();
  23339. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23340. this._cache.fov = this.fov;
  23341. this._cache.fovMode = this.fovMode;
  23342. this._cache.aspectRatio = engine.getAspectRatio(this);
  23343. if (this.minZ <= 0) {
  23344. this.minZ = 0.1;
  23345. }
  23346. if (scene.useRightHandedSystem) {
  23347. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23348. }
  23349. else {
  23350. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23351. }
  23352. }
  23353. else {
  23354. var halfWidth = engine.getRenderWidth() / 2.0;
  23355. var halfHeight = engine.getRenderHeight() / 2.0;
  23356. if (scene.useRightHandedSystem) {
  23357. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23358. }
  23359. else {
  23360. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23361. }
  23362. this._cache.orthoLeft = this.orthoLeft;
  23363. this._cache.orthoRight = this.orthoRight;
  23364. this._cache.orthoBottom = this.orthoBottom;
  23365. this._cache.orthoTop = this.orthoTop;
  23366. this._cache.renderWidth = engine.getRenderWidth();
  23367. this._cache.renderHeight = engine.getRenderHeight();
  23368. }
  23369. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23370. return this._projectionMatrix;
  23371. };
  23372. /**
  23373. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23374. * @returns a Matrix
  23375. */
  23376. Camera.prototype.getTransformationMatrix = function () {
  23377. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23378. return this._transformMatrix;
  23379. };
  23380. Camera.prototype._updateFrustumPlanes = function () {
  23381. if (!this._refreshFrustumPlanes) {
  23382. return;
  23383. }
  23384. this.getTransformationMatrix();
  23385. if (!this._frustumPlanes) {
  23386. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23387. }
  23388. else {
  23389. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23390. }
  23391. this._refreshFrustumPlanes = false;
  23392. };
  23393. /**
  23394. * Checks if a cullable object (mesh...) is in the camera frustum
  23395. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23396. * @param target The object to check
  23397. * @returns true if the object is in frustum otherwise false
  23398. */
  23399. Camera.prototype.isInFrustum = function (target) {
  23400. this._updateFrustumPlanes();
  23401. return target.isInFrustum(this._frustumPlanes);
  23402. };
  23403. /**
  23404. * Checks if a cullable object (mesh...) is in the camera frustum
  23405. * Unlike isInFrustum this cheks the full bounding box
  23406. * @param target The object to check
  23407. * @returns true if the object is in frustum otherwise false
  23408. */
  23409. Camera.prototype.isCompletelyInFrustum = function (target) {
  23410. this._updateFrustumPlanes();
  23411. return target.isCompletelyInFrustum(this._frustumPlanes);
  23412. };
  23413. /**
  23414. * Gets a ray in the forward direction from the camera.
  23415. * @param length Defines the length of the ray to create
  23416. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23417. * @param origin Defines the start point of the ray which defaults to the camera position
  23418. * @returns the forward ray
  23419. */
  23420. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23421. if (length === void 0) { length = 100; }
  23422. if (!transform) {
  23423. transform = this.getWorldMatrix();
  23424. }
  23425. if (!origin) {
  23426. origin = this.position;
  23427. }
  23428. var forward = new BABYLON.Vector3(0, 0, 1);
  23429. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23430. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23431. return new BABYLON.Ray(origin, direction, length);
  23432. };
  23433. /**
  23434. * Releases resources associated with this node.
  23435. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23436. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23437. */
  23438. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23439. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23440. // Observables
  23441. this.onViewMatrixChangedObservable.clear();
  23442. this.onProjectionMatrixChangedObservable.clear();
  23443. this.onAfterCheckInputsObservable.clear();
  23444. this.onRestoreStateObservable.clear();
  23445. // Inputs
  23446. if (this.inputs) {
  23447. this.inputs.clear();
  23448. }
  23449. // Animations
  23450. this.getScene().stopAnimation(this);
  23451. // Remove from scene
  23452. this.getScene().removeCamera(this);
  23453. while (this._rigCameras.length > 0) {
  23454. var camera = this._rigCameras.pop();
  23455. if (camera) {
  23456. camera.dispose();
  23457. }
  23458. }
  23459. // Postprocesses
  23460. if (this._rigPostProcess) {
  23461. this._rigPostProcess.dispose(this);
  23462. this._rigPostProcess = null;
  23463. this._postProcesses = [];
  23464. }
  23465. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23466. this._rigPostProcess = null;
  23467. this._postProcesses = [];
  23468. }
  23469. else {
  23470. var i = this._postProcesses.length;
  23471. while (--i >= 0) {
  23472. var postProcess = this._postProcesses[i];
  23473. if (postProcess) {
  23474. postProcess.dispose(this);
  23475. }
  23476. }
  23477. }
  23478. // Render targets
  23479. var i = this.customRenderTargets.length;
  23480. while (--i >= 0) {
  23481. this.customRenderTargets[i].dispose();
  23482. }
  23483. this.customRenderTargets = [];
  23484. // Active Meshes
  23485. this._activeMeshes.dispose();
  23486. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23487. };
  23488. Object.defineProperty(Camera.prototype, "leftCamera", {
  23489. /**
  23490. * Gets the left camera of a rig setup in case of Rigged Camera
  23491. */
  23492. get: function () {
  23493. if (this._rigCameras.length < 1) {
  23494. return null;
  23495. }
  23496. return this._rigCameras[0];
  23497. },
  23498. enumerable: true,
  23499. configurable: true
  23500. });
  23501. Object.defineProperty(Camera.prototype, "rightCamera", {
  23502. /**
  23503. * Gets the right camera of a rig setup in case of Rigged Camera
  23504. */
  23505. get: function () {
  23506. if (this._rigCameras.length < 2) {
  23507. return null;
  23508. }
  23509. return this._rigCameras[1];
  23510. },
  23511. enumerable: true,
  23512. configurable: true
  23513. });
  23514. /**
  23515. * Gets the left camera target of a rig setup in case of Rigged Camera
  23516. * @returns the target position
  23517. */
  23518. Camera.prototype.getLeftTarget = function () {
  23519. if (this._rigCameras.length < 1) {
  23520. return null;
  23521. }
  23522. return this._rigCameras[0].getTarget();
  23523. };
  23524. /**
  23525. * Gets the right camera target of a rig setup in case of Rigged Camera
  23526. * @returns the target position
  23527. */
  23528. Camera.prototype.getRightTarget = function () {
  23529. if (this._rigCameras.length < 2) {
  23530. return null;
  23531. }
  23532. return this._rigCameras[1].getTarget();
  23533. };
  23534. /**
  23535. * @hidden
  23536. */
  23537. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23538. if (this.cameraRigMode === mode) {
  23539. return;
  23540. }
  23541. while (this._rigCameras.length > 0) {
  23542. var camera = this._rigCameras.pop();
  23543. if (camera) {
  23544. camera.dispose();
  23545. }
  23546. }
  23547. this.cameraRigMode = mode;
  23548. this._cameraRigParams = {};
  23549. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23550. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23551. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23552. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23553. // create the rig cameras, unless none
  23554. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23555. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23556. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23557. if (leftCamera && rightCamera) {
  23558. this._rigCameras.push(leftCamera);
  23559. this._rigCameras.push(rightCamera);
  23560. }
  23561. }
  23562. switch (this.cameraRigMode) {
  23563. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23564. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23565. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23566. break;
  23567. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23568. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23569. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23570. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23571. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23572. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23573. break;
  23574. case Camera.RIG_MODE_VR:
  23575. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23576. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23577. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23578. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23579. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23580. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23581. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23582. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23583. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23584. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23585. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23586. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23587. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23588. if (metrics.compensateDistortion) {
  23589. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23590. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23591. }
  23592. break;
  23593. case Camera.RIG_MODE_WEBVR:
  23594. if (rigParams.vrDisplay) {
  23595. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23596. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23597. //Left eye
  23598. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23599. this._rigCameras[0].setCameraRigParameter("left", true);
  23600. //leaving this for future reference
  23601. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23602. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23603. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23604. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23605. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23606. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23607. this._rigCameras[0].parent = this;
  23608. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23609. //Right eye
  23610. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23611. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23612. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23613. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23614. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23615. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23616. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23617. this._rigCameras[1].parent = this;
  23618. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23619. if (Camera.UseAlternateWebVRRendering) {
  23620. this._rigCameras[1]._skipRendering = true;
  23621. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23622. }
  23623. }
  23624. break;
  23625. }
  23626. this._cascadePostProcessesToRigCams();
  23627. this.update();
  23628. };
  23629. Camera.prototype._getVRProjectionMatrix = function () {
  23630. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23631. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23632. return this._projectionMatrix;
  23633. };
  23634. Camera.prototype._updateCameraRotationMatrix = function () {
  23635. //Here for WebVR
  23636. };
  23637. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23638. //Here for WebVR
  23639. };
  23640. /**
  23641. * This function MUST be overwritten by the different WebVR cameras available.
  23642. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23643. */
  23644. Camera.prototype._getWebVRProjectionMatrix = function () {
  23645. return BABYLON.Matrix.Identity();
  23646. };
  23647. /**
  23648. * This function MUST be overwritten by the different WebVR cameras available.
  23649. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23650. */
  23651. Camera.prototype._getWebVRViewMatrix = function () {
  23652. return BABYLON.Matrix.Identity();
  23653. };
  23654. /** @hidden */
  23655. Camera.prototype.setCameraRigParameter = function (name, value) {
  23656. if (!this._cameraRigParams) {
  23657. this._cameraRigParams = {};
  23658. }
  23659. this._cameraRigParams[name] = value;
  23660. //provisionnally:
  23661. if (name === "interaxialDistance") {
  23662. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23663. }
  23664. };
  23665. /**
  23666. * needs to be overridden by children so sub has required properties to be copied
  23667. * @hidden
  23668. */
  23669. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23670. return null;
  23671. };
  23672. /**
  23673. * May need to be overridden by children
  23674. * @hidden
  23675. */
  23676. Camera.prototype._updateRigCameras = function () {
  23677. for (var i = 0; i < this._rigCameras.length; i++) {
  23678. this._rigCameras[i].minZ = this.minZ;
  23679. this._rigCameras[i].maxZ = this.maxZ;
  23680. this._rigCameras[i].fov = this.fov;
  23681. }
  23682. // only update viewport when ANAGLYPH
  23683. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23684. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23685. }
  23686. };
  23687. /** @hidden */
  23688. Camera.prototype._setupInputs = function () {
  23689. };
  23690. /**
  23691. * Serialiaze the camera setup to a json represention
  23692. * @returns the JSON representation
  23693. */
  23694. Camera.prototype.serialize = function () {
  23695. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23696. // Type
  23697. serializationObject.type = this.getClassName();
  23698. // Parent
  23699. if (this.parent) {
  23700. serializationObject.parentId = this.parent.id;
  23701. }
  23702. if (this.inputs) {
  23703. this.inputs.serialize(serializationObject);
  23704. }
  23705. // Animations
  23706. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23707. serializationObject.ranges = this.serializeAnimationRanges();
  23708. return serializationObject;
  23709. };
  23710. /**
  23711. * Clones the current camera.
  23712. * @param name The cloned camera name
  23713. * @returns the cloned camera
  23714. */
  23715. Camera.prototype.clone = function (name) {
  23716. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23717. };
  23718. /**
  23719. * Gets the direction of the camera relative to a given local axis.
  23720. * @param localAxis Defines the reference axis to provide a relative direction.
  23721. * @return the direction
  23722. */
  23723. Camera.prototype.getDirection = function (localAxis) {
  23724. var result = BABYLON.Vector3.Zero();
  23725. this.getDirectionToRef(localAxis, result);
  23726. return result;
  23727. };
  23728. /**
  23729. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23730. * @param localAxis Defines the reference axis to provide a relative direction.
  23731. * @param result Defines the vector to store the result in
  23732. */
  23733. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23734. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23735. };
  23736. /**
  23737. * Gets a camera constructor for a given camera type
  23738. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23739. * @param name The name of the camera the result will be able to instantiate
  23740. * @param scene The scene the result will construct the camera in
  23741. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23742. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23743. * @returns a factory method to construc the camera
  23744. */
  23745. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23746. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23747. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23748. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23749. interaxial_distance: interaxial_distance,
  23750. isStereoscopicSideBySide: isStereoscopicSideBySide
  23751. });
  23752. if (constructorFunc) {
  23753. return constructorFunc;
  23754. }
  23755. // Default to universal camera
  23756. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23757. };
  23758. /**
  23759. * Compute the world matrix of the camera.
  23760. * @returns the camera workd matrix
  23761. */
  23762. Camera.prototype.computeWorldMatrix = function () {
  23763. return this.getWorldMatrix();
  23764. };
  23765. /**
  23766. * Parse a JSON and creates the camera from the parsed information
  23767. * @param parsedCamera The JSON to parse
  23768. * @param scene The scene to instantiate the camera in
  23769. * @returns the newly constructed camera
  23770. */
  23771. Camera.Parse = function (parsedCamera, scene) {
  23772. var type = parsedCamera.type;
  23773. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23774. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23775. // Parent
  23776. if (parsedCamera.parentId) {
  23777. camera._waitingParentId = parsedCamera.parentId;
  23778. }
  23779. //If camera has an input manager, let it parse inputs settings
  23780. if (camera.inputs) {
  23781. camera.inputs.parse(parsedCamera);
  23782. camera._setupInputs();
  23783. }
  23784. if (camera.setPosition) { // need to force position
  23785. camera.position.copyFromFloats(0, 0, 0);
  23786. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23787. }
  23788. // Target
  23789. if (parsedCamera.target) {
  23790. if (camera.setTarget) {
  23791. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23792. }
  23793. }
  23794. // Apply 3d rig, when found
  23795. if (parsedCamera.cameraRigMode) {
  23796. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23797. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23798. }
  23799. // Animations
  23800. if (parsedCamera.animations) {
  23801. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23802. var parsedAnimation = parsedCamera.animations[animationIndex];
  23803. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23804. }
  23805. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23806. }
  23807. if (parsedCamera.autoAnimate) {
  23808. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23809. }
  23810. return camera;
  23811. };
  23812. /**
  23813. * This is the default projection mode used by the cameras.
  23814. * It helps recreating a feeling of perspective and better appreciate depth.
  23815. * This is the best way to simulate real life cameras.
  23816. */
  23817. Camera.PERSPECTIVE_CAMERA = 0;
  23818. /**
  23819. * This helps creating camera with an orthographic mode.
  23820. * 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.
  23821. */
  23822. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23823. /**
  23824. * This is the default FOV mode for perspective cameras.
  23825. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23826. */
  23827. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23828. /**
  23829. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23830. */
  23831. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23832. /**
  23833. * This specifies ther is no need for a camera rig.
  23834. * Basically only one eye is rendered corresponding to the camera.
  23835. */
  23836. Camera.RIG_MODE_NONE = 0;
  23837. /**
  23838. * Simulates a camera Rig with one blue eye and one red eye.
  23839. * This can be use with 3d blue and red glasses.
  23840. */
  23841. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23842. /**
  23843. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23844. */
  23845. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23846. /**
  23847. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23848. */
  23849. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23850. /**
  23851. * Defines that both eyes of the camera will be rendered over under each other.
  23852. */
  23853. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23854. /**
  23855. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23856. */
  23857. Camera.RIG_MODE_VR = 20;
  23858. /**
  23859. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23860. */
  23861. Camera.RIG_MODE_WEBVR = 21;
  23862. /**
  23863. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23864. */
  23865. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23866. /**
  23867. * @hidden
  23868. * Might be removed once multiview will be a thing
  23869. */
  23870. Camera.UseAlternateWebVRRendering = false;
  23871. __decorate([
  23872. BABYLON.serializeAsVector3()
  23873. ], Camera.prototype, "position", void 0);
  23874. __decorate([
  23875. BABYLON.serializeAsVector3()
  23876. ], Camera.prototype, "upVector", void 0);
  23877. __decorate([
  23878. BABYLON.serialize()
  23879. ], Camera.prototype, "orthoLeft", void 0);
  23880. __decorate([
  23881. BABYLON.serialize()
  23882. ], Camera.prototype, "orthoRight", void 0);
  23883. __decorate([
  23884. BABYLON.serialize()
  23885. ], Camera.prototype, "orthoBottom", void 0);
  23886. __decorate([
  23887. BABYLON.serialize()
  23888. ], Camera.prototype, "orthoTop", void 0);
  23889. __decorate([
  23890. BABYLON.serialize()
  23891. ], Camera.prototype, "fov", void 0);
  23892. __decorate([
  23893. BABYLON.serialize()
  23894. ], Camera.prototype, "minZ", void 0);
  23895. __decorate([
  23896. BABYLON.serialize()
  23897. ], Camera.prototype, "maxZ", void 0);
  23898. __decorate([
  23899. BABYLON.serialize()
  23900. ], Camera.prototype, "inertia", void 0);
  23901. __decorate([
  23902. BABYLON.serialize()
  23903. ], Camera.prototype, "mode", void 0);
  23904. __decorate([
  23905. BABYLON.serialize()
  23906. ], Camera.prototype, "layerMask", void 0);
  23907. __decorate([
  23908. BABYLON.serialize()
  23909. ], Camera.prototype, "fovMode", void 0);
  23910. __decorate([
  23911. BABYLON.serialize()
  23912. ], Camera.prototype, "cameraRigMode", void 0);
  23913. __decorate([
  23914. BABYLON.serialize()
  23915. ], Camera.prototype, "interaxialDistance", void 0);
  23916. __decorate([
  23917. BABYLON.serialize()
  23918. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23919. return Camera;
  23920. }(BABYLON.Node));
  23921. BABYLON.Camera = Camera;
  23922. })(BABYLON || (BABYLON = {}));
  23923. //# sourceMappingURL=babylon.camera.js.map
  23924. var BABYLON;
  23925. (function (BABYLON) {
  23926. /**
  23927. * This is the manager responsible of all the rendering for meshes sprites and particles.
  23928. * It is enable to manage the different groups as well as the different necessary sort functions.
  23929. * This should not be used directly aside of the few static configurations
  23930. */
  23931. var RenderingManager = /** @class */ (function () {
  23932. /**
  23933. * Instantiates a new rendering group for a particular scene
  23934. * @param scene Defines the scene the groups belongs to
  23935. */
  23936. function RenderingManager(scene) {
  23937. /**
  23938. * @hidden
  23939. */
  23940. this._useSceneAutoClearSetup = false;
  23941. this._renderingGroups = new Array();
  23942. this._autoClearDepthStencil = {};
  23943. this._customOpaqueSortCompareFn = {};
  23944. this._customAlphaTestSortCompareFn = {};
  23945. this._customTransparentSortCompareFn = {};
  23946. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23947. this._scene = scene;
  23948. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23949. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23950. }
  23951. }
  23952. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23953. if (depth === void 0) { depth = true; }
  23954. if (stencil === void 0) { stencil = true; }
  23955. if (this._depthStencilBufferAlreadyCleaned) {
  23956. return;
  23957. }
  23958. this._scene.getEngine().clear(null, false, depth, stencil);
  23959. this._depthStencilBufferAlreadyCleaned = true;
  23960. };
  23961. /**
  23962. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  23963. * @hidden
  23964. */
  23965. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23966. // Update the observable context (not null as it only goes away on dispose)
  23967. var info = this._renderingGroupInfo;
  23968. info.scene = this._scene;
  23969. info.camera = this._scene.activeCamera;
  23970. // Dispatch sprites
  23971. if (this._scene.spriteManagers && renderSprites) {
  23972. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23973. var manager = this._scene.spriteManagers[index];
  23974. this.dispatchSprites(manager);
  23975. }
  23976. }
  23977. // Render
  23978. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23979. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23980. var renderingGroup = this._renderingGroups[index];
  23981. if (!renderingGroup)
  23982. continue;
  23983. var renderingGroupMask = Math.pow(2, index);
  23984. info.renderingGroupId = index;
  23985. // Before Observable
  23986. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23987. // Clear depth/stencil if needed
  23988. if (RenderingManager.AUTOCLEAR) {
  23989. var autoClear = this._useSceneAutoClearSetup ?
  23990. this._scene.getAutoClearDepthStencilSetup(index) :
  23991. this._autoClearDepthStencil[index];
  23992. if (autoClear && autoClear.autoClear) {
  23993. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23994. }
  23995. }
  23996. // Render
  23997. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23998. var step = _a[_i];
  23999. step.action(index);
  24000. }
  24001. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24002. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24003. var step = _c[_b];
  24004. step.action(index);
  24005. }
  24006. // After Observable
  24007. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24008. }
  24009. };
  24010. /**
  24011. * Resets the different information of the group to prepare a new frame
  24012. * @hidden
  24013. */
  24014. RenderingManager.prototype.reset = function () {
  24015. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24016. var renderingGroup = this._renderingGroups[index];
  24017. if (renderingGroup) {
  24018. renderingGroup.prepare();
  24019. }
  24020. }
  24021. };
  24022. /**
  24023. * Dispose and release the group and its associated resources.
  24024. * @hidden
  24025. */
  24026. RenderingManager.prototype.dispose = function () {
  24027. this.freeRenderingGroups();
  24028. this._renderingGroups.length = 0;
  24029. this._renderingGroupInfo = null;
  24030. };
  24031. /**
  24032. * Clear the info related to rendering groups preventing retention points during dispose.
  24033. */
  24034. RenderingManager.prototype.freeRenderingGroups = function () {
  24035. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24036. var renderingGroup = this._renderingGroups[index];
  24037. if (renderingGroup) {
  24038. renderingGroup.dispose();
  24039. }
  24040. }
  24041. };
  24042. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24043. if (this._renderingGroups[renderingGroupId] === undefined) {
  24044. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24045. }
  24046. };
  24047. /**
  24048. * Add a sprite manager to the rendering manager in order to render it this frame.
  24049. * @param spriteManager Define the sprite manager to render
  24050. */
  24051. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24052. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24053. this._prepareRenderingGroup(renderingGroupId);
  24054. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24055. };
  24056. /**
  24057. * Add a particle system to the rendering manager in order to render it this frame.
  24058. * @param particleSystem Define the particle system to render
  24059. */
  24060. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24061. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24062. this._prepareRenderingGroup(renderingGroupId);
  24063. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24064. };
  24065. /**
  24066. * Add a submesh to the manager in order to render it this frame
  24067. * @param subMesh The submesh to dispatch
  24068. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24069. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24070. */
  24071. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24072. if (mesh === undefined) {
  24073. mesh = subMesh.getMesh();
  24074. }
  24075. var renderingGroupId = mesh.renderingGroupId || 0;
  24076. this._prepareRenderingGroup(renderingGroupId);
  24077. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24078. };
  24079. /**
  24080. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24081. * This allowed control for front to back rendering or reversly depending of the special needs.
  24082. *
  24083. * @param renderingGroupId The rendering group id corresponding to its index
  24084. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24085. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24086. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24087. */
  24088. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24089. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24090. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24091. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24092. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24093. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24094. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24095. if (this._renderingGroups[renderingGroupId]) {
  24096. var group = this._renderingGroups[renderingGroupId];
  24097. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24098. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24099. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24100. }
  24101. };
  24102. /**
  24103. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24104. *
  24105. * @param renderingGroupId The rendering group id corresponding to its index
  24106. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24107. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24108. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24109. */
  24110. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24111. if (depth === void 0) { depth = true; }
  24112. if (stencil === void 0) { stencil = true; }
  24113. this._autoClearDepthStencil[renderingGroupId] = {
  24114. autoClear: autoClearDepthStencil,
  24115. depth: depth,
  24116. stencil: stencil
  24117. };
  24118. };
  24119. /**
  24120. * Gets the current auto clear configuration for one rendering group of the rendering
  24121. * manager.
  24122. * @param index the rendering group index to get the information for
  24123. * @returns The auto clear setup for the requested rendering group
  24124. */
  24125. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24126. return this._autoClearDepthStencil[index];
  24127. };
  24128. /**
  24129. * The max id used for rendering groups (not included)
  24130. */
  24131. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24132. /**
  24133. * The min id used for rendering groups (included)
  24134. */
  24135. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24136. /**
  24137. * Used to globally prevent autoclearing scenes.
  24138. */
  24139. RenderingManager.AUTOCLEAR = true;
  24140. return RenderingManager;
  24141. }());
  24142. BABYLON.RenderingManager = RenderingManager;
  24143. })(BABYLON || (BABYLON = {}));
  24144. //# sourceMappingURL=babylon.renderingManager.js.map
  24145. var BABYLON;
  24146. (function (BABYLON) {
  24147. /**
  24148. * This represents the object necessary to create a rendering group.
  24149. * This is exclusively used and created by the rendering manager.
  24150. * To modify the behavior, you use the available helpers in your scene or meshes.
  24151. * @hidden
  24152. */
  24153. var RenderingGroup = /** @class */ (function () {
  24154. /**
  24155. * Creates a new rendering group.
  24156. * @param index The rendering group index
  24157. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24158. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24159. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24160. */
  24161. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24162. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24163. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24164. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24165. this.index = index;
  24166. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24167. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24168. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24169. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24170. this._particleSystems = new BABYLON.SmartArray(256);
  24171. this._spriteManagers = new BABYLON.SmartArray(256);
  24172. this._edgesRenderers = new BABYLON.SmartArray(16);
  24173. this._scene = scene;
  24174. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24175. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24176. this.transparentSortCompareFn = transparentSortCompareFn;
  24177. }
  24178. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24179. /**
  24180. * Set the opaque sort comparison function.
  24181. * If null the sub meshes will be render in the order they were created
  24182. */
  24183. set: function (value) {
  24184. this._opaqueSortCompareFn = value;
  24185. if (value) {
  24186. this._renderOpaque = this.renderOpaqueSorted;
  24187. }
  24188. else {
  24189. this._renderOpaque = RenderingGroup.renderUnsorted;
  24190. }
  24191. },
  24192. enumerable: true,
  24193. configurable: true
  24194. });
  24195. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24196. /**
  24197. * Set the alpha test sort comparison function.
  24198. * If null the sub meshes will be render in the order they were created
  24199. */
  24200. set: function (value) {
  24201. this._alphaTestSortCompareFn = value;
  24202. if (value) {
  24203. this._renderAlphaTest = this.renderAlphaTestSorted;
  24204. }
  24205. else {
  24206. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24207. }
  24208. },
  24209. enumerable: true,
  24210. configurable: true
  24211. });
  24212. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24213. /**
  24214. * Set the transparent sort comparison function.
  24215. * If null the sub meshes will be render in the order they were created
  24216. */
  24217. set: function (value) {
  24218. if (value) {
  24219. this._transparentSortCompareFn = value;
  24220. }
  24221. else {
  24222. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24223. }
  24224. this._renderTransparent = this.renderTransparentSorted;
  24225. },
  24226. enumerable: true,
  24227. configurable: true
  24228. });
  24229. /**
  24230. * Render all the sub meshes contained in the group.
  24231. * @param customRenderFunction Used to override the default render behaviour of the group.
  24232. * @returns true if rendered some submeshes.
  24233. */
  24234. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24235. if (customRenderFunction) {
  24236. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24237. return;
  24238. }
  24239. var engine = this._scene.getEngine();
  24240. // Depth only
  24241. if (this._depthOnlySubMeshes.length !== 0) {
  24242. engine.setColorWrite(false);
  24243. this._renderAlphaTest(this._depthOnlySubMeshes);
  24244. engine.setColorWrite(true);
  24245. }
  24246. // Opaque
  24247. if (this._opaqueSubMeshes.length !== 0) {
  24248. this._renderOpaque(this._opaqueSubMeshes);
  24249. }
  24250. // Alpha test
  24251. if (this._alphaTestSubMeshes.length !== 0) {
  24252. this._renderAlphaTest(this._alphaTestSubMeshes);
  24253. }
  24254. var stencilState = engine.getStencilBuffer();
  24255. engine.setStencilBuffer(false);
  24256. // Sprites
  24257. if (renderSprites) {
  24258. this._renderSprites();
  24259. }
  24260. // Particles
  24261. if (renderParticles) {
  24262. this._renderParticles(activeMeshes);
  24263. }
  24264. if (this.onBeforeTransparentRendering) {
  24265. this.onBeforeTransparentRendering();
  24266. }
  24267. // Transparent
  24268. if (this._transparentSubMeshes.length !== 0) {
  24269. this._renderTransparent(this._transparentSubMeshes);
  24270. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24271. }
  24272. // Set back stencil to false in case it changes before the edge renderer.
  24273. engine.setStencilBuffer(false);
  24274. // Edges
  24275. if (this._edgesRenderers.length) {
  24276. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24277. this._edgesRenderers.data[edgesRendererIndex].render();
  24278. }
  24279. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24280. }
  24281. // Restore Stencil state.
  24282. engine.setStencilBuffer(stencilState);
  24283. };
  24284. /**
  24285. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24286. * @param subMeshes The submeshes to render
  24287. */
  24288. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24289. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24290. };
  24291. /**
  24292. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24293. * @param subMeshes The submeshes to render
  24294. */
  24295. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24296. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24297. };
  24298. /**
  24299. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24300. * @param subMeshes The submeshes to render
  24301. */
  24302. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24303. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24304. };
  24305. /**
  24306. * Renders the submeshes in a specified order.
  24307. * @param subMeshes The submeshes to sort before render
  24308. * @param sortCompareFn The comparison function use to sort
  24309. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24310. * @param transparent Specifies to activate blending if true
  24311. */
  24312. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24313. var subIndex = 0;
  24314. var subMesh;
  24315. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24316. for (; subIndex < subMeshes.length; subIndex++) {
  24317. subMesh = subMeshes.data[subIndex];
  24318. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24319. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24320. }
  24321. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24322. if (sortCompareFn) {
  24323. sortedArray.sort(sortCompareFn);
  24324. }
  24325. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24326. subMesh = sortedArray[subIndex];
  24327. if (transparent) {
  24328. var material = subMesh.getMaterial();
  24329. if (material && material.needDepthPrePass) {
  24330. var engine = material.getScene().getEngine();
  24331. engine.setColorWrite(false);
  24332. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24333. subMesh.render(false);
  24334. engine.setColorWrite(true);
  24335. }
  24336. }
  24337. subMesh.render(transparent);
  24338. }
  24339. };
  24340. /**
  24341. * Renders the submeshes in the order they were dispatched (no sort applied).
  24342. * @param subMeshes The submeshes to render
  24343. */
  24344. RenderingGroup.renderUnsorted = function (subMeshes) {
  24345. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24346. var submesh = subMeshes.data[subIndex];
  24347. submesh.render(false);
  24348. }
  24349. };
  24350. /**
  24351. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24352. * are rendered back to front if in the same alpha index.
  24353. *
  24354. * @param a The first submesh
  24355. * @param b The second submesh
  24356. * @returns The result of the comparison
  24357. */
  24358. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24359. // Alpha index first
  24360. if (a._alphaIndex > b._alphaIndex) {
  24361. return 1;
  24362. }
  24363. if (a._alphaIndex < b._alphaIndex) {
  24364. return -1;
  24365. }
  24366. // Then distance to camera
  24367. return RenderingGroup.backToFrontSortCompare(a, b);
  24368. };
  24369. /**
  24370. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24371. * are rendered back to front.
  24372. *
  24373. * @param a The first submesh
  24374. * @param b The second submesh
  24375. * @returns The result of the comparison
  24376. */
  24377. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24378. // Then distance to camera
  24379. if (a._distanceToCamera < b._distanceToCamera) {
  24380. return 1;
  24381. }
  24382. if (a._distanceToCamera > b._distanceToCamera) {
  24383. return -1;
  24384. }
  24385. return 0;
  24386. };
  24387. /**
  24388. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24389. * are rendered front to back (prevent overdraw).
  24390. *
  24391. * @param a The first submesh
  24392. * @param b The second submesh
  24393. * @returns The result of the comparison
  24394. */
  24395. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24396. // Then distance to camera
  24397. if (a._distanceToCamera < b._distanceToCamera) {
  24398. return -1;
  24399. }
  24400. if (a._distanceToCamera > b._distanceToCamera) {
  24401. return 1;
  24402. }
  24403. return 0;
  24404. };
  24405. /**
  24406. * Resets the different lists of submeshes to prepare a new frame.
  24407. */
  24408. RenderingGroup.prototype.prepare = function () {
  24409. this._opaqueSubMeshes.reset();
  24410. this._transparentSubMeshes.reset();
  24411. this._alphaTestSubMeshes.reset();
  24412. this._depthOnlySubMeshes.reset();
  24413. this._particleSystems.reset();
  24414. this._spriteManagers.reset();
  24415. this._edgesRenderers.reset();
  24416. };
  24417. RenderingGroup.prototype.dispose = function () {
  24418. this._opaqueSubMeshes.dispose();
  24419. this._transparentSubMeshes.dispose();
  24420. this._alphaTestSubMeshes.dispose();
  24421. this._depthOnlySubMeshes.dispose();
  24422. this._particleSystems.dispose();
  24423. this._spriteManagers.dispose();
  24424. this._edgesRenderers.dispose();
  24425. };
  24426. /**
  24427. * Inserts the submesh in its correct queue depending on its material.
  24428. * @param subMesh The submesh to dispatch
  24429. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24430. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24431. */
  24432. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24433. // Get mesh and materials if not provided
  24434. if (mesh === undefined) {
  24435. mesh = subMesh.getMesh();
  24436. }
  24437. if (material === undefined) {
  24438. material = subMesh.getMaterial();
  24439. }
  24440. if (material === null || material === undefined) {
  24441. return;
  24442. }
  24443. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24444. this._transparentSubMeshes.push(subMesh);
  24445. }
  24446. else if (material.needAlphaTesting()) { // Alpha test
  24447. if (material.needDepthPrePass) {
  24448. this._depthOnlySubMeshes.push(subMesh);
  24449. }
  24450. this._alphaTestSubMeshes.push(subMesh);
  24451. }
  24452. else {
  24453. if (material.needDepthPrePass) {
  24454. this._depthOnlySubMeshes.push(subMesh);
  24455. }
  24456. this._opaqueSubMeshes.push(subMesh); // Opaque
  24457. }
  24458. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24459. this._edgesRenderers.push(mesh._edgesRenderer);
  24460. }
  24461. };
  24462. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24463. this._spriteManagers.push(spriteManager);
  24464. };
  24465. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24466. this._particleSystems.push(particleSystem);
  24467. };
  24468. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24469. if (this._particleSystems.length === 0) {
  24470. return;
  24471. }
  24472. // Particles
  24473. var activeCamera = this._scene.activeCamera;
  24474. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24475. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24476. var particleSystem = this._particleSystems.data[particleIndex];
  24477. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24478. continue;
  24479. }
  24480. var emitter = particleSystem.emitter;
  24481. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24482. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24483. }
  24484. }
  24485. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24486. };
  24487. RenderingGroup.prototype._renderSprites = function () {
  24488. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24489. return;
  24490. }
  24491. // Sprites
  24492. var activeCamera = this._scene.activeCamera;
  24493. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24494. for (var id = 0; id < this._spriteManagers.length; id++) {
  24495. var spriteManager = this._spriteManagers.data[id];
  24496. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24497. spriteManager.render();
  24498. }
  24499. }
  24500. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24501. };
  24502. return RenderingGroup;
  24503. }());
  24504. BABYLON.RenderingGroup = RenderingGroup;
  24505. })(BABYLON || (BABYLON = {}));
  24506. //# sourceMappingURL=babylon.renderingGroup.js.map
  24507. var BABYLON;
  24508. (function (BABYLON) {
  24509. /**
  24510. * Groups all the scene component constants in one place to ease maintenance.
  24511. * @hidden
  24512. */
  24513. var SceneComponentConstants = /** @class */ (function () {
  24514. function SceneComponentConstants() {
  24515. }
  24516. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24517. SceneComponentConstants.NAME_LAYER = "Layer";
  24518. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24519. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24520. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24521. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24522. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24523. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24524. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24525. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24526. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24527. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24528. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24529. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24530. SceneComponentConstants.NAME_OCTREE = "Octree";
  24531. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24532. SceneComponentConstants.NAME_AUDIO = "Audio";
  24533. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24534. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24535. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24536. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24537. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24538. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24539. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24540. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24541. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24542. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24543. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24544. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24545. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24546. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24547. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24548. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24549. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24550. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24551. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24552. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24553. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24554. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24555. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24556. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24557. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24558. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24559. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24560. return SceneComponentConstants;
  24561. }());
  24562. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24563. /**
  24564. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24565. * @hidden
  24566. */
  24567. var Stage = /** @class */ (function (_super) {
  24568. __extends(Stage, _super);
  24569. /**
  24570. * Hide ctor from the rest of the world.
  24571. * @param items The items to add.
  24572. */
  24573. function Stage(items) {
  24574. return _super.apply(this, items) || this;
  24575. }
  24576. /**
  24577. * Creates a new Stage.
  24578. * @returns A new instance of a Stage
  24579. */
  24580. Stage.Create = function () {
  24581. return Object.create(Stage.prototype);
  24582. };
  24583. /**
  24584. * Registers a step in an ordered way in the targeted stage.
  24585. * @param index Defines the position to register the step in
  24586. * @param component Defines the component attached to the step
  24587. * @param action Defines the action to launch during the step
  24588. */
  24589. Stage.prototype.registerStep = function (index, component, action) {
  24590. var i = 0;
  24591. var maxIndex = Number.MAX_VALUE;
  24592. for (; i < this.length && i < maxIndex; i++) {
  24593. var step = this[i];
  24594. maxIndex = step.index;
  24595. }
  24596. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24597. };
  24598. /**
  24599. * Clears all the steps from the stage.
  24600. */
  24601. Stage.prototype.clear = function () {
  24602. this.length = 0;
  24603. };
  24604. return Stage;
  24605. }(Array));
  24606. BABYLON.Stage = Stage;
  24607. })(BABYLON || (BABYLON = {}));
  24608. //# sourceMappingURL=babylon.sceneComponent.js.map
  24609. var BABYLON;
  24610. (function (BABYLON) {
  24611. /**
  24612. * Base class of the scene acting as a container for the different elements composing a scene.
  24613. * This class is dynamically extended by the different components of the scene increasing
  24614. * flexibility and reducing coupling
  24615. */
  24616. var AbstractScene = /** @class */ (function () {
  24617. function AbstractScene() {
  24618. /**
  24619. * Gets the list of root nodes (ie. nodes with no parent)
  24620. */
  24621. this.rootNodes = new Array();
  24622. /** All of the cameras added to this scene
  24623. * @see http://doc.babylonjs.com/babylon101/cameras
  24624. */
  24625. this.cameras = new Array();
  24626. /**
  24627. * All of the lights added to this scene
  24628. * @see http://doc.babylonjs.com/babylon101/lights
  24629. */
  24630. this.lights = new Array();
  24631. /**
  24632. * All of the (abstract) meshes added to this scene
  24633. */
  24634. this.meshes = new Array();
  24635. /**
  24636. * The list of skeletons added to the scene
  24637. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24638. */
  24639. this.skeletons = new Array();
  24640. /**
  24641. * All of the particle systems added to this scene
  24642. * @see http://doc.babylonjs.com/babylon101/particles
  24643. */
  24644. this.particleSystems = new Array();
  24645. /**
  24646. * Gets a list of Animations associated with the scene
  24647. */
  24648. this.animations = [];
  24649. /**
  24650. * All of the animation groups added to this scene
  24651. * @see http://doc.babylonjs.com/how_to/group
  24652. */
  24653. this.animationGroups = new Array();
  24654. /**
  24655. * All of the multi-materials added to this scene
  24656. * @see http://doc.babylonjs.com/how_to/multi_materials
  24657. */
  24658. this.multiMaterials = new Array();
  24659. /**
  24660. * All of the materials added to this scene
  24661. * @see http://doc.babylonjs.com/babylon101/materials
  24662. */
  24663. this.materials = new Array();
  24664. /**
  24665. * The list of morph target managers added to the scene
  24666. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24667. */
  24668. this.morphTargetManagers = new Array();
  24669. /**
  24670. * The list of geometries used in the scene.
  24671. */
  24672. this.geometries = new Array();
  24673. /**
  24674. * All of the tranform nodes added to this scene
  24675. * @see http://doc.babylonjs.com/how_to/transformnode
  24676. */
  24677. this.transformNodes = new Array();
  24678. /**
  24679. * ActionManagers available on the scene.
  24680. */
  24681. this.actionManagers = new Array();
  24682. /**
  24683. * Textures to keep.
  24684. */
  24685. this.textures = new Array();
  24686. }
  24687. /**
  24688. * Adds a parser in the list of available ones
  24689. * @param name Defines the name of the parser
  24690. * @param parser Defines the parser to add
  24691. */
  24692. AbstractScene.AddParser = function (name, parser) {
  24693. this._BabylonFileParsers[name] = parser;
  24694. };
  24695. /**
  24696. * Gets a general parser from the list of avaialble ones
  24697. * @param name Defines the name of the parser
  24698. * @returns the requested parser or null
  24699. */
  24700. AbstractScene.GetParser = function (name) {
  24701. if (this._BabylonFileParsers[name]) {
  24702. return this._BabylonFileParsers[name];
  24703. }
  24704. return null;
  24705. };
  24706. /**
  24707. * Adds n individual parser in the list of available ones
  24708. * @param name Defines the name of the parser
  24709. * @param parser Defines the parser to add
  24710. */
  24711. AbstractScene.AddIndividualParser = function (name, parser) {
  24712. this._IndividualBabylonFileParsers[name] = parser;
  24713. };
  24714. /**
  24715. * Gets an individual parser from the list of avaialble ones
  24716. * @param name Defines the name of the parser
  24717. * @returns the requested parser or null
  24718. */
  24719. AbstractScene.GetIndividualParser = function (name) {
  24720. if (this._IndividualBabylonFileParsers[name]) {
  24721. return this._IndividualBabylonFileParsers[name];
  24722. }
  24723. return null;
  24724. };
  24725. /**
  24726. * Parser json data and populate both a scene and its associated container object
  24727. * @param jsonData Defines the data to parse
  24728. * @param scene Defines the scene to parse the data for
  24729. * @param container Defines the container attached to the parsing sequence
  24730. * @param rootUrl Defines the root url of the data
  24731. */
  24732. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24733. for (var parserName in this._BabylonFileParsers) {
  24734. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24735. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24736. }
  24737. }
  24738. };
  24739. /**
  24740. * Stores the list of available parsers in the application.
  24741. */
  24742. AbstractScene._BabylonFileParsers = {};
  24743. /**
  24744. * Stores the list of available individual parsers in the application.
  24745. */
  24746. AbstractScene._IndividualBabylonFileParsers = {};
  24747. return AbstractScene;
  24748. }());
  24749. BABYLON.AbstractScene = AbstractScene;
  24750. })(BABYLON || (BABYLON = {}));
  24751. //# sourceMappingURL=babylon.abstractScene.js.map
  24752. var BABYLON;
  24753. (function (BABYLON) {
  24754. /** @hidden */
  24755. var ClickInfo = /** @class */ (function () {
  24756. function ClickInfo() {
  24757. this._singleClick = false;
  24758. this._doubleClick = false;
  24759. this._hasSwiped = false;
  24760. this._ignore = false;
  24761. }
  24762. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24763. get: function () {
  24764. return this._singleClick;
  24765. },
  24766. set: function (b) {
  24767. this._singleClick = b;
  24768. },
  24769. enumerable: true,
  24770. configurable: true
  24771. });
  24772. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24773. get: function () {
  24774. return this._doubleClick;
  24775. },
  24776. set: function (b) {
  24777. this._doubleClick = b;
  24778. },
  24779. enumerable: true,
  24780. configurable: true
  24781. });
  24782. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24783. get: function () {
  24784. return this._hasSwiped;
  24785. },
  24786. set: function (b) {
  24787. this._hasSwiped = b;
  24788. },
  24789. enumerable: true,
  24790. configurable: true
  24791. });
  24792. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24793. get: function () {
  24794. return this._ignore;
  24795. },
  24796. set: function (b) {
  24797. this._ignore = b;
  24798. },
  24799. enumerable: true,
  24800. configurable: true
  24801. });
  24802. return ClickInfo;
  24803. }());
  24804. /**
  24805. * This class is used by the onRenderingGroupObservable
  24806. */
  24807. var RenderingGroupInfo = /** @class */ (function () {
  24808. function RenderingGroupInfo() {
  24809. }
  24810. return RenderingGroupInfo;
  24811. }());
  24812. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24813. /**
  24814. * Represents a scene to be rendered by the engine.
  24815. * @see http://doc.babylonjs.com/features/scene
  24816. */
  24817. var Scene = /** @class */ (function (_super) {
  24818. __extends(Scene, _super);
  24819. /**
  24820. * Creates a new Scene
  24821. * @param engine defines the engine to use to render this scene
  24822. */
  24823. function Scene(engine) {
  24824. var _this = _super.call(this) || this;
  24825. // Members
  24826. /**
  24827. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24828. */
  24829. _this.autoClear = true;
  24830. /**
  24831. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24832. */
  24833. _this.autoClearDepthAndStencil = true;
  24834. /**
  24835. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24836. */
  24837. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24838. /**
  24839. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24840. */
  24841. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24842. _this._forceWireframe = false;
  24843. _this._forcePointsCloud = false;
  24844. /**
  24845. * Gets or sets a boolean indicating if animations are enabled
  24846. */
  24847. _this.animationsEnabled = true;
  24848. _this._animationPropertiesOverride = null;
  24849. /**
  24850. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24851. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24852. */
  24853. _this.useConstantAnimationDeltaTime = false;
  24854. /**
  24855. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24856. * Please note that it requires to run a ray cast through the scene on every frame
  24857. */
  24858. _this.constantlyUpdateMeshUnderPointer = false;
  24859. /**
  24860. * Defines the HTML cursor to use when hovering over interactive elements
  24861. */
  24862. _this.hoverCursor = "pointer";
  24863. /**
  24864. * Defines the HTML default cursor to use (empty by default)
  24865. */
  24866. _this.defaultCursor = "";
  24867. /**
  24868. * This is used to call preventDefault() on pointer down
  24869. * in order to block unwanted artifacts like system double clicks
  24870. */
  24871. _this.preventDefaultOnPointerDown = true;
  24872. // Metadata
  24873. /**
  24874. * Gets or sets user defined metadata
  24875. */
  24876. _this.metadata = null;
  24877. /**
  24878. * Use this array to add regular expressions used to disable offline support for specific urls
  24879. */
  24880. _this.disableOfflineSupportExceptionRules = new Array();
  24881. /**
  24882. * An event triggered when the scene is disposed.
  24883. */
  24884. _this.onDisposeObservable = new BABYLON.Observable();
  24885. _this._onDisposeObserver = null;
  24886. /**
  24887. * An event triggered before rendering the scene (right after animations and physics)
  24888. */
  24889. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24890. _this._onBeforeRenderObserver = null;
  24891. /**
  24892. * An event triggered after rendering the scene
  24893. */
  24894. _this.onAfterRenderObservable = new BABYLON.Observable();
  24895. _this._onAfterRenderObserver = null;
  24896. /**
  24897. * An event triggered before animating the scene
  24898. */
  24899. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24900. /**
  24901. * An event triggered after animations processing
  24902. */
  24903. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24904. /**
  24905. * An event triggered before draw calls are ready to be sent
  24906. */
  24907. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24908. /**
  24909. * An event triggered after draw calls have been sent
  24910. */
  24911. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24912. /**
  24913. * An event triggered when the scene is ready
  24914. */
  24915. _this.onReadyObservable = new BABYLON.Observable();
  24916. /**
  24917. * An event triggered before rendering a camera
  24918. */
  24919. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24920. _this._onBeforeCameraRenderObserver = null;
  24921. /**
  24922. * An event triggered after rendering a camera
  24923. */
  24924. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24925. _this._onAfterCameraRenderObserver = null;
  24926. /**
  24927. * An event triggered when active meshes evaluation is about to start
  24928. */
  24929. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24930. /**
  24931. * An event triggered when active meshes evaluation is done
  24932. */
  24933. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24934. /**
  24935. * An event triggered when particles rendering is about to start
  24936. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24937. */
  24938. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24939. /**
  24940. * An event triggered when particles rendering is done
  24941. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24942. */
  24943. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24944. /**
  24945. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24946. */
  24947. _this.onDataLoadedObservable = new BABYLON.Observable();
  24948. /**
  24949. * An event triggered when a camera is created
  24950. */
  24951. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24952. /**
  24953. * An event triggered when a camera is removed
  24954. */
  24955. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24956. /**
  24957. * An event triggered when a light is created
  24958. */
  24959. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24960. /**
  24961. * An event triggered when a light is removed
  24962. */
  24963. _this.onLightRemovedObservable = new BABYLON.Observable();
  24964. /**
  24965. * An event triggered when a geometry is created
  24966. */
  24967. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24968. /**
  24969. * An event triggered when a geometry is removed
  24970. */
  24971. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24972. /**
  24973. * An event triggered when a transform node is created
  24974. */
  24975. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24976. /**
  24977. * An event triggered when a transform node is removed
  24978. */
  24979. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24980. /**
  24981. * An event triggered when a mesh is created
  24982. */
  24983. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24984. /**
  24985. * An event triggered when a mesh is removed
  24986. */
  24987. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24988. /**
  24989. * An event triggered when a material is created
  24990. */
  24991. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  24992. /**
  24993. * An event triggered when a material is removed
  24994. */
  24995. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  24996. /**
  24997. * An event triggered when a texture is created
  24998. */
  24999. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25000. /**
  25001. * An event triggered when a texture is removed
  25002. */
  25003. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25004. /**
  25005. * An event triggered when render targets are about to be rendered
  25006. * Can happen multiple times per frame.
  25007. */
  25008. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25009. /**
  25010. * An event triggered when render targets were rendered.
  25011. * Can happen multiple times per frame.
  25012. */
  25013. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25014. /**
  25015. * An event triggered before calculating deterministic simulation step
  25016. */
  25017. _this.onBeforeStepObservable = new BABYLON.Observable();
  25018. /**
  25019. * An event triggered after calculating deterministic simulation step
  25020. */
  25021. _this.onAfterStepObservable = new BABYLON.Observable();
  25022. /**
  25023. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25024. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25025. * 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)
  25026. */
  25027. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25028. /**
  25029. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25030. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25031. * 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)
  25032. */
  25033. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25034. /**
  25035. * This Observable will when a mesh has been imported into the scene.
  25036. */
  25037. _this.onMeshImportedObservable = new BABYLON.Observable();
  25038. // Animations
  25039. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25040. /**
  25041. * 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).
  25042. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25043. */
  25044. _this.onPrePointerObservable = new BABYLON.Observable();
  25045. /**
  25046. * Observable event triggered each time an input event is received from the rendering canvas
  25047. */
  25048. _this.onPointerObservable = new BABYLON.Observable();
  25049. _this._meshPickProceed = false;
  25050. _this._currentPickResult = null;
  25051. _this._previousPickResult = null;
  25052. _this._totalPointersPressed = 0;
  25053. _this._doubleClickOccured = false;
  25054. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25055. _this.cameraToUseForPointers = null;
  25056. _this._pointerX = 0;
  25057. _this._pointerY = 0;
  25058. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25059. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25060. _this._startingPointerTime = 0;
  25061. _this._previousStartingPointerTime = 0;
  25062. _this._pointerCaptures = {};
  25063. // Deterministic lockstep
  25064. _this._timeAccumulator = 0;
  25065. _this._currentStepId = 0;
  25066. _this._currentInternalStep = 0;
  25067. // Keyboard
  25068. /**
  25069. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25070. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25071. */
  25072. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25073. /**
  25074. * Observable event triggered each time an keyboard event is received from the hosting window
  25075. */
  25076. _this.onKeyboardObservable = new BABYLON.Observable();
  25077. // Coordinates system
  25078. _this._useRightHandedSystem = false;
  25079. // Fog
  25080. _this._fogEnabled = true;
  25081. _this._fogMode = Scene.FOGMODE_NONE;
  25082. /**
  25083. * Gets or sets the fog color to use
  25084. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25085. * (Default is Color3(0.2, 0.2, 0.3))
  25086. */
  25087. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25088. /**
  25089. * Gets or sets the fog density to use
  25090. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25091. * (Default is 0.1)
  25092. */
  25093. _this.fogDensity = 0.1;
  25094. /**
  25095. * Gets or sets the fog start distance to use
  25096. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25097. * (Default is 0)
  25098. */
  25099. _this.fogStart = 0;
  25100. /**
  25101. * Gets or sets the fog end distance to use
  25102. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25103. * (Default is 1000)
  25104. */
  25105. _this.fogEnd = 1000.0;
  25106. // Lights
  25107. _this._shadowsEnabled = true;
  25108. _this._lightsEnabled = true;
  25109. /** All of the active cameras added to this scene. */
  25110. _this.activeCameras = new Array();
  25111. // Textures
  25112. _this._texturesEnabled = true;
  25113. // Particles
  25114. /**
  25115. * Gets or sets a boolean indicating if particles are enabled on this scene
  25116. */
  25117. _this.particlesEnabled = true;
  25118. // Sprites
  25119. /**
  25120. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25121. */
  25122. _this.spritesEnabled = true;
  25123. // Skeletons
  25124. _this._skeletonsEnabled = true;
  25125. // Lens flares
  25126. /**
  25127. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25128. */
  25129. _this.lensFlaresEnabled = true;
  25130. // Collisions
  25131. /**
  25132. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25133. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25134. */
  25135. _this.collisionsEnabled = true;
  25136. /**
  25137. * Defines the gravity applied to this scene (used only for collisions)
  25138. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25139. */
  25140. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25141. // Postprocesses
  25142. /**
  25143. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25144. */
  25145. _this.postProcessesEnabled = true;
  25146. /**
  25147. * The list of postprocesses added to the scene
  25148. */
  25149. _this.postProcesses = new Array();
  25150. // Customs render targets
  25151. /**
  25152. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25153. */
  25154. _this.renderTargetsEnabled = true;
  25155. /**
  25156. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25157. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25158. */
  25159. _this.dumpNextRenderTargets = false;
  25160. /**
  25161. * The list of user defined render targets added to the scene
  25162. */
  25163. _this.customRenderTargets = new Array();
  25164. /**
  25165. * Gets the list of meshes imported to the scene through SceneLoader
  25166. */
  25167. _this.importedMeshesFiles = new Array();
  25168. // Probes
  25169. /**
  25170. * Gets or sets a boolean indicating if probes are enabled on this scene
  25171. */
  25172. _this.probesEnabled = true;
  25173. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25174. // Procedural textures
  25175. /**
  25176. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25177. */
  25178. _this.proceduralTexturesEnabled = true;
  25179. // Performance counters
  25180. _this._totalVertices = new BABYLON.PerfCounter();
  25181. /** @hidden */
  25182. _this._activeIndices = new BABYLON.PerfCounter();
  25183. /** @hidden */
  25184. _this._activeParticles = new BABYLON.PerfCounter();
  25185. /** @hidden */
  25186. _this._activeBones = new BABYLON.PerfCounter();
  25187. _this._animationTime = 0;
  25188. /**
  25189. * Gets or sets a general scale for animation speed
  25190. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25191. */
  25192. _this.animationTimeScale = 1;
  25193. _this._renderId = 0;
  25194. _this._frameId = 0;
  25195. _this._executeWhenReadyTimeoutId = -1;
  25196. _this._intermediateRendering = false;
  25197. _this._viewUpdateFlag = -1;
  25198. _this._projectionUpdateFlag = -1;
  25199. _this._alternateViewUpdateFlag = -1;
  25200. _this._alternateProjectionUpdateFlag = -1;
  25201. /** @hidden */
  25202. _this._toBeDisposed = new Array(256);
  25203. _this._activeRequests = new Array();
  25204. _this._pendingData = new Array();
  25205. _this._isDisposed = false;
  25206. /**
  25207. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25208. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25209. */
  25210. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25211. _this._activeMeshes = new BABYLON.SmartArray(256);
  25212. _this._processedMaterials = new BABYLON.SmartArray(256);
  25213. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25214. /** @hidden */
  25215. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25216. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25217. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25218. /** @hidden */
  25219. _this._activeAnimatables = new Array();
  25220. _this._transformMatrix = BABYLON.Matrix.Zero();
  25221. _this._useAlternateCameraConfiguration = false;
  25222. _this._alternateRendering = false;
  25223. /**
  25224. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25225. * This is useful if there are more lights that the maximum simulteanous authorized
  25226. */
  25227. _this.requireLightSorting = false;
  25228. /**
  25229. * @hidden
  25230. * Backing store of defined scene components.
  25231. */
  25232. _this._components = [];
  25233. /**
  25234. * @hidden
  25235. * Backing store of defined scene components.
  25236. */
  25237. _this._serializableComponents = [];
  25238. /**
  25239. * List of components to register on the next registration step.
  25240. */
  25241. _this._transientComponents = [];
  25242. /**
  25243. * @hidden
  25244. * Defines the actions happening before camera updates.
  25245. */
  25246. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25247. /**
  25248. * @hidden
  25249. * Defines the actions happening before clear the canvas.
  25250. */
  25251. _this._beforeClearStage = BABYLON.Stage.Create();
  25252. /**
  25253. * @hidden
  25254. * Defines the actions when collecting render targets for the frame.
  25255. */
  25256. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25257. /**
  25258. * @hidden
  25259. * Defines the actions happening for one camera in the frame.
  25260. */
  25261. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25262. /**
  25263. * @hidden
  25264. * Defines the actions happening during the per mesh ready checks.
  25265. */
  25266. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25267. /**
  25268. * @hidden
  25269. * Defines the actions happening before evaluate active mesh checks.
  25270. */
  25271. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25272. /**
  25273. * @hidden
  25274. * Defines the actions happening during the evaluate sub mesh checks.
  25275. */
  25276. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25277. /**
  25278. * @hidden
  25279. * Defines the actions happening during the active mesh stage.
  25280. */
  25281. _this._activeMeshStage = BABYLON.Stage.Create();
  25282. /**
  25283. * @hidden
  25284. * Defines the actions happening during the per camera render target step.
  25285. */
  25286. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25287. /**
  25288. * @hidden
  25289. * Defines the actions happening just before the active camera is drawing.
  25290. */
  25291. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25292. /**
  25293. * @hidden
  25294. * Defines the actions happening just before a rendering group is drawing.
  25295. */
  25296. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25297. /**
  25298. * @hidden
  25299. * Defines the actions happening just before a mesh is drawing.
  25300. */
  25301. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25302. /**
  25303. * @hidden
  25304. * Defines the actions happening just after a mesh has been drawn.
  25305. */
  25306. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25307. /**
  25308. * @hidden
  25309. * Defines the actions happening just after a rendering group has been drawn.
  25310. */
  25311. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25312. /**
  25313. * @hidden
  25314. * Defines the actions happening just after the active camera has been drawn.
  25315. */
  25316. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25317. /**
  25318. * @hidden
  25319. * Defines the actions happening just after rendering all cameras and computing intersections.
  25320. */
  25321. _this._afterRenderStage = BABYLON.Stage.Create();
  25322. /**
  25323. * @hidden
  25324. * Defines the actions happening when a pointer move event happens.
  25325. */
  25326. _this._pointerMoveStage = BABYLON.Stage.Create();
  25327. /**
  25328. * @hidden
  25329. * Defines the actions happening when a pointer down event happens.
  25330. */
  25331. _this._pointerDownStage = BABYLON.Stage.Create();
  25332. /**
  25333. * @hidden
  25334. * Defines the actions happening when a pointer up event happens.
  25335. */
  25336. _this._pointerUpStage = BABYLON.Stage.Create();
  25337. _this._defaultMeshCandidates = {
  25338. data: [],
  25339. length: 0
  25340. };
  25341. _this._defaultSubMeshCandidates = {
  25342. data: [],
  25343. length: 0
  25344. };
  25345. _this._activeMeshesFrozen = false;
  25346. /** @hidden */
  25347. _this._allowPostProcessClearColor = true;
  25348. /**
  25349. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25350. */
  25351. _this.getDeterministicFrameTime = function () {
  25352. return 1000.0 / 60.0; // frame time in ms
  25353. };
  25354. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25355. _this._blockMaterialDirtyMechanism = false;
  25356. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25357. _this._engine.scenes.push(_this);
  25358. _this._uid = null;
  25359. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25360. if (BABYLON.PostProcessManager) {
  25361. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25362. }
  25363. if (BABYLON.Tools.IsWindowObjectExist()) {
  25364. _this.attachControl();
  25365. }
  25366. //collision coordinator initialization. For now legacy per default.
  25367. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25368. // Uniform Buffer
  25369. _this._createUbo();
  25370. // Default Image processing definition
  25371. if (BABYLON.ImageProcessingConfiguration) {
  25372. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25373. }
  25374. _this.setDefaultCandidateProviders();
  25375. return _this;
  25376. }
  25377. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25378. /**
  25379. * Texture used in all pbr material as the reflection texture.
  25380. * As in the majority of the scene they are the same (exception for multi room and so on),
  25381. * this is easier to reference from here than from all the materials.
  25382. */
  25383. get: function () {
  25384. return this._environmentTexture;
  25385. },
  25386. /**
  25387. * Texture used in all pbr material as the reflection texture.
  25388. * As in the majority of the scene they are the same (exception for multi room and so on),
  25389. * this is easier to set here than in all the materials.
  25390. */
  25391. set: function (value) {
  25392. if (this._environmentTexture === value) {
  25393. return;
  25394. }
  25395. this._environmentTexture = value;
  25396. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25397. },
  25398. enumerable: true,
  25399. configurable: true
  25400. });
  25401. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25402. /**
  25403. * Default image processing configuration used either in the rendering
  25404. * Forward main pass or through the imageProcessingPostProcess if present.
  25405. * As in the majority of the scene they are the same (exception for multi camera),
  25406. * this is easier to reference from here than from all the materials and post process.
  25407. *
  25408. * No setter as we it is a shared configuration, you can set the values instead.
  25409. */
  25410. get: function () {
  25411. return this._imageProcessingConfiguration;
  25412. },
  25413. enumerable: true,
  25414. configurable: true
  25415. });
  25416. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25417. get: function () {
  25418. return this._forceWireframe;
  25419. },
  25420. /**
  25421. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25422. */
  25423. set: function (value) {
  25424. if (this._forceWireframe === value) {
  25425. return;
  25426. }
  25427. this._forceWireframe = value;
  25428. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25429. },
  25430. enumerable: true,
  25431. configurable: true
  25432. });
  25433. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25434. get: function () {
  25435. return this._forcePointsCloud;
  25436. },
  25437. /**
  25438. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25439. */
  25440. set: function (value) {
  25441. if (this._forcePointsCloud === value) {
  25442. return;
  25443. }
  25444. this._forcePointsCloud = value;
  25445. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25446. },
  25447. enumerable: true,
  25448. configurable: true
  25449. });
  25450. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25451. /**
  25452. * Gets or sets the animation properties override
  25453. */
  25454. get: function () {
  25455. return this._animationPropertiesOverride;
  25456. },
  25457. set: function (value) {
  25458. this._animationPropertiesOverride = value;
  25459. },
  25460. enumerable: true,
  25461. configurable: true
  25462. });
  25463. Object.defineProperty(Scene.prototype, "onDispose", {
  25464. /** Sets a function to be executed when this scene is disposed. */
  25465. set: function (callback) {
  25466. if (this._onDisposeObserver) {
  25467. this.onDisposeObservable.remove(this._onDisposeObserver);
  25468. }
  25469. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25470. },
  25471. enumerable: true,
  25472. configurable: true
  25473. });
  25474. Object.defineProperty(Scene.prototype, "beforeRender", {
  25475. /** Sets a function to be executed before rendering this scene */
  25476. set: function (callback) {
  25477. if (this._onBeforeRenderObserver) {
  25478. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25479. }
  25480. if (callback) {
  25481. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25482. }
  25483. },
  25484. enumerable: true,
  25485. configurable: true
  25486. });
  25487. Object.defineProperty(Scene.prototype, "afterRender", {
  25488. /** Sets a function to be executed after rendering this scene */
  25489. set: function (callback) {
  25490. if (this._onAfterRenderObserver) {
  25491. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25492. }
  25493. if (callback) {
  25494. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25495. }
  25496. },
  25497. enumerable: true,
  25498. configurable: true
  25499. });
  25500. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25501. /** Sets a function to be executed before rendering a camera*/
  25502. set: function (callback) {
  25503. if (this._onBeforeCameraRenderObserver) {
  25504. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25505. }
  25506. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25507. },
  25508. enumerable: true,
  25509. configurable: true
  25510. });
  25511. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25512. /** Sets a function to be executed after rendering a camera*/
  25513. set: function (callback) {
  25514. if (this._onAfterCameraRenderObserver) {
  25515. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25516. }
  25517. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25518. },
  25519. enumerable: true,
  25520. configurable: true
  25521. });
  25522. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25523. /**
  25524. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25525. */
  25526. get: function () {
  25527. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25528. },
  25529. enumerable: true,
  25530. configurable: true
  25531. });
  25532. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25533. get: function () {
  25534. return this._useRightHandedSystem;
  25535. },
  25536. /**
  25537. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25538. */
  25539. set: function (value) {
  25540. if (this._useRightHandedSystem === value) {
  25541. return;
  25542. }
  25543. this._useRightHandedSystem = value;
  25544. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25545. },
  25546. enumerable: true,
  25547. configurable: true
  25548. });
  25549. /**
  25550. * Sets the step Id used by deterministic lock step
  25551. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25552. * @param newStepId defines the step Id
  25553. */
  25554. Scene.prototype.setStepId = function (newStepId) {
  25555. this._currentStepId = newStepId;
  25556. };
  25557. ;
  25558. /**
  25559. * Gets the step Id used by deterministic lock step
  25560. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25561. * @returns the step Id
  25562. */
  25563. Scene.prototype.getStepId = function () {
  25564. return this._currentStepId;
  25565. };
  25566. ;
  25567. /**
  25568. * Gets the internal step used by deterministic lock step
  25569. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25570. * @returns the internal step
  25571. */
  25572. Scene.prototype.getInternalStep = function () {
  25573. return this._currentInternalStep;
  25574. };
  25575. ;
  25576. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25577. get: function () {
  25578. return this._fogEnabled;
  25579. },
  25580. /**
  25581. * Gets or sets a boolean indicating if fog is enabled on this scene
  25582. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25583. * (Default is true)
  25584. */
  25585. set: function (value) {
  25586. if (this._fogEnabled === value) {
  25587. return;
  25588. }
  25589. this._fogEnabled = value;
  25590. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25591. },
  25592. enumerable: true,
  25593. configurable: true
  25594. });
  25595. Object.defineProperty(Scene.prototype, "fogMode", {
  25596. get: function () {
  25597. return this._fogMode;
  25598. },
  25599. /**
  25600. * Gets or sets the fog mode to use
  25601. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25602. * | mode | value |
  25603. * | --- | --- |
  25604. * | FOGMODE_NONE | 0 |
  25605. * | FOGMODE_EXP | 1 |
  25606. * | FOGMODE_EXP2 | 2 |
  25607. * | FOGMODE_LINEAR | 3 |
  25608. */
  25609. set: function (value) {
  25610. if (this._fogMode === value) {
  25611. return;
  25612. }
  25613. this._fogMode = value;
  25614. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25615. },
  25616. enumerable: true,
  25617. configurable: true
  25618. });
  25619. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25620. get: function () {
  25621. return this._shadowsEnabled;
  25622. },
  25623. /**
  25624. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25625. */
  25626. set: function (value) {
  25627. if (this._shadowsEnabled === value) {
  25628. return;
  25629. }
  25630. this._shadowsEnabled = value;
  25631. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25632. },
  25633. enumerable: true,
  25634. configurable: true
  25635. });
  25636. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25637. get: function () {
  25638. return this._lightsEnabled;
  25639. },
  25640. /**
  25641. * Gets or sets a boolean indicating if lights are enabled on this scene
  25642. */
  25643. set: function (value) {
  25644. if (this._lightsEnabled === value) {
  25645. return;
  25646. }
  25647. this._lightsEnabled = value;
  25648. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25649. },
  25650. enumerable: true,
  25651. configurable: true
  25652. });
  25653. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25654. /** The default material used on meshes when no material is affected */
  25655. get: function () {
  25656. if (!this._defaultMaterial) {
  25657. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25658. }
  25659. return this._defaultMaterial;
  25660. },
  25661. /** The default material used on meshes when no material is affected */
  25662. set: function (value) {
  25663. this._defaultMaterial = value;
  25664. },
  25665. enumerable: true,
  25666. configurable: true
  25667. });
  25668. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25669. get: function () {
  25670. return this._texturesEnabled;
  25671. },
  25672. /**
  25673. * Gets or sets a boolean indicating if textures are enabled on this scene
  25674. */
  25675. set: function (value) {
  25676. if (this._texturesEnabled === value) {
  25677. return;
  25678. }
  25679. this._texturesEnabled = value;
  25680. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25681. },
  25682. enumerable: true,
  25683. configurable: true
  25684. });
  25685. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25686. get: function () {
  25687. return this._skeletonsEnabled;
  25688. },
  25689. /**
  25690. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25691. */
  25692. set: function (value) {
  25693. if (this._skeletonsEnabled === value) {
  25694. return;
  25695. }
  25696. this._skeletonsEnabled = value;
  25697. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25698. },
  25699. enumerable: true,
  25700. configurable: true
  25701. });
  25702. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25703. /** @hidden */
  25704. get: function () {
  25705. return this._alternateRendering;
  25706. },
  25707. enumerable: true,
  25708. configurable: true
  25709. });
  25710. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25711. /**
  25712. * Gets the list of frustum planes (built from the active camera)
  25713. */
  25714. get: function () {
  25715. return this._frustumPlanes;
  25716. },
  25717. enumerable: true,
  25718. configurable: true
  25719. });
  25720. /**
  25721. * Registers the transient components if needed.
  25722. */
  25723. Scene.prototype._registerTransientComponents = function () {
  25724. // Register components that have been associated lately to the scene.
  25725. if (this._transientComponents.length > 0) {
  25726. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25727. var component = _a[_i];
  25728. component.register();
  25729. }
  25730. this._transientComponents = [];
  25731. }
  25732. };
  25733. /**
  25734. * @hidden
  25735. * Add a component to the scene.
  25736. * Note that the ccomponent could be registered on th next frame if this is called after
  25737. * the register component stage.
  25738. * @param component Defines the component to add to the scene
  25739. */
  25740. Scene.prototype._addComponent = function (component) {
  25741. this._components.push(component);
  25742. this._transientComponents.push(component);
  25743. var serializableComponent = component;
  25744. if (serializableComponent.addFromContainer) {
  25745. this._serializableComponents.push(serializableComponent);
  25746. }
  25747. };
  25748. /**
  25749. * @hidden
  25750. * Gets a component from the scene.
  25751. * @param name defines the name of the component to retrieve
  25752. * @returns the component or null if not present
  25753. */
  25754. Scene.prototype._getComponent = function (name) {
  25755. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25756. var component = _a[_i];
  25757. if (component.name === name) {
  25758. return component;
  25759. }
  25760. }
  25761. return null;
  25762. };
  25763. /**
  25764. * @hidden
  25765. */
  25766. Scene.prototype._getDefaultMeshCandidates = function () {
  25767. this._defaultMeshCandidates.data = this.meshes;
  25768. this._defaultMeshCandidates.length = this.meshes.length;
  25769. return this._defaultMeshCandidates;
  25770. };
  25771. /**
  25772. * @hidden
  25773. */
  25774. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25775. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25776. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25777. return this._defaultSubMeshCandidates;
  25778. };
  25779. /**
  25780. * Sets the default candidate providers for the scene.
  25781. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25782. * and getCollidingSubMeshCandidates to their default function
  25783. */
  25784. Scene.prototype.setDefaultCandidateProviders = function () {
  25785. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25786. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25787. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25788. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25789. };
  25790. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25791. /**
  25792. * Gets a boolean indicating if collisions are processed on a web worker
  25793. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25794. */
  25795. get: function () {
  25796. return this._workerCollisions;
  25797. },
  25798. set: function (enabled) {
  25799. if (!BABYLON.CollisionCoordinatorLegacy) {
  25800. return;
  25801. }
  25802. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25803. this._workerCollisions = enabled;
  25804. if (this.collisionCoordinator) {
  25805. this.collisionCoordinator.destroy();
  25806. }
  25807. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25808. this.collisionCoordinator.init(this);
  25809. },
  25810. enumerable: true,
  25811. configurable: true
  25812. });
  25813. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25814. /**
  25815. * Gets the mesh that is currently under the pointer
  25816. */
  25817. get: function () {
  25818. return this._pointerOverMesh;
  25819. },
  25820. enumerable: true,
  25821. configurable: true
  25822. });
  25823. Object.defineProperty(Scene.prototype, "pointerX", {
  25824. /**
  25825. * Gets the current on-screen X position of the pointer
  25826. */
  25827. get: function () {
  25828. return this._pointerX;
  25829. },
  25830. enumerable: true,
  25831. configurable: true
  25832. });
  25833. Object.defineProperty(Scene.prototype, "pointerY", {
  25834. /**
  25835. * Gets the current on-screen Y position of the pointer
  25836. */
  25837. get: function () {
  25838. return this._pointerY;
  25839. },
  25840. enumerable: true,
  25841. configurable: true
  25842. });
  25843. /**
  25844. * Gets the cached material (ie. the latest rendered one)
  25845. * @returns the cached material
  25846. */
  25847. Scene.prototype.getCachedMaterial = function () {
  25848. return this._cachedMaterial;
  25849. };
  25850. /**
  25851. * Gets the cached effect (ie. the latest rendered one)
  25852. * @returns the cached effect
  25853. */
  25854. Scene.prototype.getCachedEffect = function () {
  25855. return this._cachedEffect;
  25856. };
  25857. /**
  25858. * Gets the cached visibility state (ie. the latest rendered one)
  25859. * @returns the cached visibility state
  25860. */
  25861. Scene.prototype.getCachedVisibility = function () {
  25862. return this._cachedVisibility;
  25863. };
  25864. /**
  25865. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25866. * @param material defines the current material
  25867. * @param effect defines the current effect
  25868. * @param visibility defines the current visibility state
  25869. * @returns true if one parameter is not cached
  25870. */
  25871. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25872. if (visibility === void 0) { visibility = 1; }
  25873. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25874. };
  25875. /**
  25876. * Gets the engine associated with the scene
  25877. * @returns an Engine
  25878. */
  25879. Scene.prototype.getEngine = function () {
  25880. return this._engine;
  25881. };
  25882. /**
  25883. * Gets the total number of vertices rendered per frame
  25884. * @returns the total number of vertices rendered per frame
  25885. */
  25886. Scene.prototype.getTotalVertices = function () {
  25887. return this._totalVertices.current;
  25888. };
  25889. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25890. /**
  25891. * Gets the performance counter for total vertices
  25892. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25893. */
  25894. get: function () {
  25895. return this._totalVertices;
  25896. },
  25897. enumerable: true,
  25898. configurable: true
  25899. });
  25900. /**
  25901. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25902. * @returns the total number of active indices rendered per frame
  25903. */
  25904. Scene.prototype.getActiveIndices = function () {
  25905. return this._activeIndices.current;
  25906. };
  25907. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25908. /**
  25909. * Gets the performance counter for active indices
  25910. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25911. */
  25912. get: function () {
  25913. return this._activeIndices;
  25914. },
  25915. enumerable: true,
  25916. configurable: true
  25917. });
  25918. /**
  25919. * Gets the total number of active particles rendered per frame
  25920. * @returns the total number of active particles rendered per frame
  25921. */
  25922. Scene.prototype.getActiveParticles = function () {
  25923. return this._activeParticles.current;
  25924. };
  25925. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25926. /**
  25927. * Gets the performance counter for active particles
  25928. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25929. */
  25930. get: function () {
  25931. return this._activeParticles;
  25932. },
  25933. enumerable: true,
  25934. configurable: true
  25935. });
  25936. /**
  25937. * Gets the total number of active bones rendered per frame
  25938. * @returns the total number of active bones rendered per frame
  25939. */
  25940. Scene.prototype.getActiveBones = function () {
  25941. return this._activeBones.current;
  25942. };
  25943. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25944. /**
  25945. * Gets the performance counter for active bones
  25946. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25947. */
  25948. get: function () {
  25949. return this._activeBones;
  25950. },
  25951. enumerable: true,
  25952. configurable: true
  25953. });
  25954. /** @hidden */
  25955. Scene.prototype.getInterFramePerfCounter = function () {
  25956. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25957. return 0;
  25958. };
  25959. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25960. /** @hidden */
  25961. get: function () {
  25962. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25963. return null;
  25964. },
  25965. enumerable: true,
  25966. configurable: true
  25967. });
  25968. /** @hidden */
  25969. Scene.prototype.getLastFrameDuration = function () {
  25970. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25971. return 0;
  25972. };
  25973. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25974. /** @hidden */
  25975. get: function () {
  25976. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25977. return null;
  25978. },
  25979. enumerable: true,
  25980. configurable: true
  25981. });
  25982. /** @hidden */
  25983. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25984. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25985. return 0;
  25986. };
  25987. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25988. /** @hidden */
  25989. get: function () {
  25990. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25991. return null;
  25992. },
  25993. enumerable: true,
  25994. configurable: true
  25995. });
  25996. /**
  25997. * Gets the array of active meshes
  25998. * @returns an array of AbstractMesh
  25999. */
  26000. Scene.prototype.getActiveMeshes = function () {
  26001. return this._activeMeshes;
  26002. };
  26003. /** @hidden */
  26004. Scene.prototype.getRenderTargetsDuration = function () {
  26005. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26006. return 0;
  26007. };
  26008. /** @hidden */
  26009. Scene.prototype.getRenderDuration = function () {
  26010. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26011. return 0;
  26012. };
  26013. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26014. /** @hidden */
  26015. get: function () {
  26016. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26017. return null;
  26018. },
  26019. enumerable: true,
  26020. configurable: true
  26021. });
  26022. /** @hidden */
  26023. Scene.prototype.getParticlesDuration = function () {
  26024. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26025. return 0;
  26026. };
  26027. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26028. /** @hidden */
  26029. get: function () {
  26030. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26031. return null;
  26032. },
  26033. enumerable: true,
  26034. configurable: true
  26035. });
  26036. /** @hidden */
  26037. Scene.prototype.getSpritesDuration = function () {
  26038. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26039. return 0;
  26040. };
  26041. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26042. /** @hidden */
  26043. get: function () {
  26044. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26045. return null;
  26046. },
  26047. enumerable: true,
  26048. configurable: true
  26049. });
  26050. /**
  26051. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26052. * @returns a number
  26053. */
  26054. Scene.prototype.getAnimationRatio = function () {
  26055. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26056. };
  26057. /**
  26058. * Gets an unique Id for the current render phase
  26059. * @returns a number
  26060. */
  26061. Scene.prototype.getRenderId = function () {
  26062. return this._renderId;
  26063. };
  26064. /**
  26065. * Gets an unique Id for the current frame
  26066. * @returns a number
  26067. */
  26068. Scene.prototype.getFrameId = function () {
  26069. return this._frameId;
  26070. };
  26071. /** Call this function if you want to manually increment the render Id*/
  26072. Scene.prototype.incrementRenderId = function () {
  26073. this._renderId++;
  26074. };
  26075. Scene.prototype._updatePointerPosition = function (evt) {
  26076. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26077. if (!canvasRect) {
  26078. return;
  26079. }
  26080. this._pointerX = evt.clientX - canvasRect.left;
  26081. this._pointerY = evt.clientY - canvasRect.top;
  26082. this._unTranslatedPointerX = this._pointerX;
  26083. this._unTranslatedPointerY = this._pointerY;
  26084. };
  26085. Scene.prototype._createUbo = function () {
  26086. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26087. this._sceneUbo.addUniform("viewProjection", 16);
  26088. this._sceneUbo.addUniform("view", 16);
  26089. };
  26090. Scene.prototype._createAlternateUbo = function () {
  26091. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26092. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26093. this._alternateSceneUbo.addUniform("view", 16);
  26094. };
  26095. // Pointers handling
  26096. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26097. if (pointerInfo.pickInfo) {
  26098. if (!pointerInfo.pickInfo.ray) {
  26099. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26100. }
  26101. }
  26102. };
  26103. /**
  26104. * Use this method to simulate a pointer move on a mesh
  26105. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26106. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26107. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26108. * @returns the current scene
  26109. */
  26110. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26111. var evt = new PointerEvent("pointermove", pointerEventInit);
  26112. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26113. return this;
  26114. }
  26115. return this._processPointerMove(pickResult, evt);
  26116. };
  26117. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26118. var canvas = this._engine.getRenderingCanvas();
  26119. if (!canvas) {
  26120. return this;
  26121. }
  26122. // Restore pointer
  26123. canvas.style.cursor = this.defaultCursor;
  26124. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26125. if (isMeshPicked) {
  26126. this.setPointerOverMesh(pickResult.pickedMesh);
  26127. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26128. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26129. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26130. }
  26131. else {
  26132. canvas.style.cursor = this.hoverCursor;
  26133. }
  26134. }
  26135. }
  26136. else {
  26137. this.setPointerOverMesh(null);
  26138. }
  26139. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26140. var step = _a[_i];
  26141. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26142. }
  26143. if (pickResult) {
  26144. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26145. if (this.onPointerMove) {
  26146. this.onPointerMove(evt, pickResult, type);
  26147. }
  26148. if (this.onPointerObservable.hasObservers()) {
  26149. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26150. this._setRayOnPointerInfo(pi);
  26151. this.onPointerObservable.notifyObservers(pi, type);
  26152. }
  26153. }
  26154. return this;
  26155. };
  26156. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26157. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26158. if (pickResult) {
  26159. pi.ray = pickResult.ray;
  26160. }
  26161. this.onPrePointerObservable.notifyObservers(pi, type);
  26162. if (pi.skipOnPointerObservable) {
  26163. return true;
  26164. }
  26165. else {
  26166. return false;
  26167. }
  26168. };
  26169. /**
  26170. * Use this method to simulate a pointer down on a mesh
  26171. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26172. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26173. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26174. * @returns the current scene
  26175. */
  26176. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26177. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26178. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26179. return this;
  26180. }
  26181. return this._processPointerDown(pickResult, evt);
  26182. };
  26183. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26184. var _this = this;
  26185. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26186. this._pickedDownMesh = pickResult.pickedMesh;
  26187. var actionManager = pickResult.pickedMesh.actionManager;
  26188. if (actionManager) {
  26189. if (actionManager.hasPickTriggers) {
  26190. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26191. switch (evt.button) {
  26192. case 0:
  26193. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26194. break;
  26195. case 1:
  26196. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26197. break;
  26198. case 2:
  26199. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26200. break;
  26201. }
  26202. }
  26203. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26204. window.setTimeout(function () {
  26205. 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);
  26206. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26207. if (_this._totalPointersPressed !== 0 &&
  26208. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26209. !_this._isPointerSwiping()) {
  26210. _this._startingPointerTime = 0;
  26211. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26212. }
  26213. }
  26214. }, Scene.LongPressDelay);
  26215. }
  26216. }
  26217. }
  26218. else {
  26219. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26220. var step = _a[_i];
  26221. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26222. }
  26223. }
  26224. if (pickResult) {
  26225. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26226. if (this.onPointerDown) {
  26227. this.onPointerDown(evt, pickResult, type);
  26228. }
  26229. if (this.onPointerObservable.hasObservers()) {
  26230. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26231. this._setRayOnPointerInfo(pi);
  26232. this.onPointerObservable.notifyObservers(pi, type);
  26233. }
  26234. }
  26235. return this;
  26236. };
  26237. /**
  26238. * Use this method to simulate a pointer up on a mesh
  26239. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26240. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26241. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26242. * @returns the current scene
  26243. */
  26244. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26245. var evt = new PointerEvent("pointerup", pointerEventInit);
  26246. var clickInfo = new ClickInfo();
  26247. clickInfo.singleClick = true;
  26248. clickInfo.ignore = true;
  26249. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26250. return this;
  26251. }
  26252. return this._processPointerUp(pickResult, evt, clickInfo);
  26253. };
  26254. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26255. if (pickResult && pickResult && pickResult.pickedMesh) {
  26256. this._pickedUpMesh = pickResult.pickedMesh;
  26257. if (this._pickedDownMesh === this._pickedUpMesh) {
  26258. if (this.onPointerPick) {
  26259. this.onPointerPick(evt, pickResult);
  26260. }
  26261. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26262. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26263. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26264. this._setRayOnPointerInfo(pi);
  26265. this.onPointerObservable.notifyObservers(pi, type_1);
  26266. }
  26267. }
  26268. if (pickResult.pickedMesh.actionManager) {
  26269. if (clickInfo.ignore) {
  26270. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26271. }
  26272. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26273. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26274. }
  26275. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26276. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26277. }
  26278. }
  26279. }
  26280. else {
  26281. if (!clickInfo.ignore) {
  26282. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26283. var step = _a[_i];
  26284. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26285. }
  26286. }
  26287. }
  26288. if (this._pickedDownMesh &&
  26289. this._pickedDownMesh.actionManager &&
  26290. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26291. this._pickedDownMesh !== this._pickedUpMesh) {
  26292. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26293. }
  26294. var type = BABYLON.PointerEventTypes.POINTERUP;
  26295. if (this.onPointerObservable.hasObservers()) {
  26296. if (!clickInfo.ignore) {
  26297. if (!clickInfo.hasSwiped) {
  26298. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26299. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26300. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26301. this._setRayOnPointerInfo(pi);
  26302. this.onPointerObservable.notifyObservers(pi, type_2);
  26303. }
  26304. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26305. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26306. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26307. this._setRayOnPointerInfo(pi);
  26308. this.onPointerObservable.notifyObservers(pi, type_3);
  26309. }
  26310. }
  26311. }
  26312. else {
  26313. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26314. this._setRayOnPointerInfo(pi);
  26315. this.onPointerObservable.notifyObservers(pi, type);
  26316. }
  26317. }
  26318. if (this.onPointerUp) {
  26319. this.onPointerUp(evt, pickResult, type);
  26320. }
  26321. return this;
  26322. };
  26323. /**
  26324. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26325. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26326. * @returns true if the pointer was captured
  26327. */
  26328. Scene.prototype.isPointerCaptured = function (pointerId) {
  26329. if (pointerId === void 0) { pointerId = 0; }
  26330. return this._pointerCaptures[pointerId];
  26331. };
  26332. /** @hidden */
  26333. Scene.prototype._isPointerSwiping = function () {
  26334. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26335. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26336. };
  26337. /**
  26338. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26339. * @param attachUp defines if you want to attach events to pointerup
  26340. * @param attachDown defines if you want to attach events to pointerdown
  26341. * @param attachMove defines if you want to attach events to pointermove
  26342. */
  26343. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26344. var _this = this;
  26345. if (attachUp === void 0) { attachUp = true; }
  26346. if (attachDown === void 0) { attachDown = true; }
  26347. if (attachMove === void 0) { attachMove = true; }
  26348. this._initActionManager = function (act, clickInfo) {
  26349. if (!_this._meshPickProceed) {
  26350. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26351. _this._currentPickResult = pickResult;
  26352. if (pickResult) {
  26353. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26354. }
  26355. _this._meshPickProceed = true;
  26356. }
  26357. return act;
  26358. };
  26359. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26360. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26361. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26362. btn !== _this._previousButtonPressed) {
  26363. _this._doubleClickOccured = false;
  26364. clickInfo.singleClick = true;
  26365. clickInfo.ignore = false;
  26366. cb(clickInfo, _this._currentPickResult);
  26367. }
  26368. };
  26369. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26370. var clickInfo = new ClickInfo();
  26371. _this._currentPickResult = null;
  26372. var act = null;
  26373. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26374. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26375. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26376. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26377. act = _this._initActionManager(act, clickInfo);
  26378. if (act)
  26379. checkPicking = act.hasPickTriggers;
  26380. }
  26381. if (checkPicking) {
  26382. var btn = evt.button;
  26383. clickInfo.hasSwiped = _this._isPointerSwiping();
  26384. if (!clickInfo.hasSwiped) {
  26385. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26386. if (!checkSingleClickImmediately) {
  26387. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26388. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26389. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26390. act = _this._initActionManager(act, clickInfo);
  26391. if (act)
  26392. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26393. }
  26394. }
  26395. if (checkSingleClickImmediately) {
  26396. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26397. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26398. btn !== _this._previousButtonPressed) {
  26399. clickInfo.singleClick = true;
  26400. cb(clickInfo, _this._currentPickResult);
  26401. }
  26402. }
  26403. // at least one double click is required to be check and exclusive double click is enabled
  26404. else {
  26405. // wait that no double click has been raised during the double click delay
  26406. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26407. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26408. }
  26409. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26410. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26411. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26412. act = _this._initActionManager(act, clickInfo);
  26413. if (act)
  26414. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26415. }
  26416. if (checkDoubleClick) {
  26417. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26418. if (btn === _this._previousButtonPressed &&
  26419. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26420. !_this._doubleClickOccured) {
  26421. // pointer has not moved for 2 clicks, it's a double click
  26422. if (!clickInfo.hasSwiped &&
  26423. !_this._isPointerSwiping()) {
  26424. _this._previousStartingPointerTime = 0;
  26425. _this._doubleClickOccured = true;
  26426. clickInfo.doubleClick = true;
  26427. clickInfo.ignore = false;
  26428. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26429. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26430. }
  26431. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26432. cb(clickInfo, _this._currentPickResult);
  26433. }
  26434. // if the two successive clicks are too far, it's just two simple clicks
  26435. else {
  26436. _this._doubleClickOccured = false;
  26437. _this._previousStartingPointerTime = _this._startingPointerTime;
  26438. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26439. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26440. _this._previousButtonPressed = btn;
  26441. if (Scene.ExclusiveDoubleClickMode) {
  26442. if (_this._previousDelayedSimpleClickTimeout) {
  26443. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26444. }
  26445. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26446. cb(clickInfo, _this._previousPickResult);
  26447. }
  26448. else {
  26449. cb(clickInfo, _this._currentPickResult);
  26450. }
  26451. }
  26452. }
  26453. // just the first click of the double has been raised
  26454. else {
  26455. _this._doubleClickOccured = false;
  26456. _this._previousStartingPointerTime = _this._startingPointerTime;
  26457. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26458. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26459. _this._previousButtonPressed = btn;
  26460. }
  26461. }
  26462. }
  26463. }
  26464. clickInfo.ignore = true;
  26465. cb(clickInfo, _this._currentPickResult);
  26466. };
  26467. this._onPointerMove = function (evt) {
  26468. _this._updatePointerPosition(evt);
  26469. // PreObservable support
  26470. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26471. return;
  26472. }
  26473. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26474. return;
  26475. }
  26476. if (!_this.pointerMovePredicate) {
  26477. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26478. }
  26479. // Meshes
  26480. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26481. _this._processPointerMove(pickResult, evt);
  26482. };
  26483. this._onPointerDown = function (evt) {
  26484. _this._totalPointersPressed++;
  26485. _this._pickedDownMesh = null;
  26486. _this._meshPickProceed = false;
  26487. _this._updatePointerPosition(evt);
  26488. if (_this.preventDefaultOnPointerDown && canvas) {
  26489. evt.preventDefault();
  26490. canvas.focus();
  26491. }
  26492. // PreObservable support
  26493. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26494. return;
  26495. }
  26496. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26497. return;
  26498. }
  26499. _this._pointerCaptures[evt.pointerId] = true;
  26500. _this._startingPointerPosition.x = _this._pointerX;
  26501. _this._startingPointerPosition.y = _this._pointerY;
  26502. _this._startingPointerTime = Date.now();
  26503. if (!_this.pointerDownPredicate) {
  26504. _this.pointerDownPredicate = function (mesh) {
  26505. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26506. };
  26507. }
  26508. // Meshes
  26509. _this._pickedDownMesh = null;
  26510. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26511. _this._processPointerDown(pickResult, evt);
  26512. };
  26513. this._onPointerUp = function (evt) {
  26514. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26515. return; // So we need to test it the pointer down was pressed before.
  26516. }
  26517. _this._totalPointersPressed--;
  26518. _this._pickedUpMesh = null;
  26519. _this._meshPickProceed = false;
  26520. _this._updatePointerPosition(evt);
  26521. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26522. // PreObservable support
  26523. if (_this.onPrePointerObservable.hasObservers()) {
  26524. if (!clickInfo.ignore) {
  26525. if (!clickInfo.hasSwiped) {
  26526. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26527. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26528. return;
  26529. }
  26530. }
  26531. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26532. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26533. return;
  26534. }
  26535. }
  26536. }
  26537. }
  26538. else {
  26539. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26540. return;
  26541. }
  26542. }
  26543. }
  26544. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26545. return;
  26546. }
  26547. _this._pointerCaptures[evt.pointerId] = false;
  26548. if (!_this.pointerUpPredicate) {
  26549. _this.pointerUpPredicate = function (mesh) {
  26550. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26551. };
  26552. }
  26553. // Meshes
  26554. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26555. _this._initActionManager(null, clickInfo);
  26556. }
  26557. if (!pickResult) {
  26558. pickResult = _this._currentPickResult;
  26559. }
  26560. _this._processPointerUp(pickResult, evt, clickInfo);
  26561. _this._previousPickResult = _this._currentPickResult;
  26562. });
  26563. };
  26564. this._onKeyDown = function (evt) {
  26565. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26566. if (_this.onPreKeyboardObservable.hasObservers()) {
  26567. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26568. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26569. if (pi.skipOnPointerObservable) {
  26570. return;
  26571. }
  26572. }
  26573. if (_this.onKeyboardObservable.hasObservers()) {
  26574. var pi = new BABYLON.KeyboardInfo(type, evt);
  26575. _this.onKeyboardObservable.notifyObservers(pi, type);
  26576. }
  26577. if (_this.actionManager) {
  26578. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26579. }
  26580. };
  26581. this._onKeyUp = function (evt) {
  26582. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26583. if (_this.onPreKeyboardObservable.hasObservers()) {
  26584. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26585. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26586. if (pi.skipOnPointerObservable) {
  26587. return;
  26588. }
  26589. }
  26590. if (_this.onKeyboardObservable.hasObservers()) {
  26591. var pi = new BABYLON.KeyboardInfo(type, evt);
  26592. _this.onKeyboardObservable.notifyObservers(pi, type);
  26593. }
  26594. if (_this.actionManager) {
  26595. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26596. }
  26597. };
  26598. var engine = this.getEngine();
  26599. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26600. if (!canvas) {
  26601. return;
  26602. }
  26603. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26604. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26605. });
  26606. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26607. if (!canvas) {
  26608. return;
  26609. }
  26610. canvas.removeEventListener("keydown", _this._onKeyDown);
  26611. canvas.removeEventListener("keyup", _this._onKeyUp);
  26612. });
  26613. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26614. var canvas = this._engine.getRenderingCanvas();
  26615. if (!canvas) {
  26616. return;
  26617. }
  26618. if (attachMove) {
  26619. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26620. // Wheel
  26621. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26622. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26623. }
  26624. if (attachDown) {
  26625. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26626. }
  26627. if (attachUp) {
  26628. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26629. }
  26630. canvas.tabIndex = 1;
  26631. };
  26632. /** Detaches all event handlers*/
  26633. Scene.prototype.detachControl = function () {
  26634. var engine = this.getEngine();
  26635. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26636. var canvas = engine.getRenderingCanvas();
  26637. if (!canvas) {
  26638. return;
  26639. }
  26640. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26641. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26642. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26643. if (this._onCanvasBlurObserver) {
  26644. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26645. }
  26646. if (this._onCanvasFocusObserver) {
  26647. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26648. }
  26649. // Wheel
  26650. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26651. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26652. // Keyboard
  26653. canvas.removeEventListener("keydown", this._onKeyDown);
  26654. canvas.removeEventListener("keyup", this._onKeyUp);
  26655. // Observables
  26656. this.onKeyboardObservable.clear();
  26657. this.onPreKeyboardObservable.clear();
  26658. this.onPointerObservable.clear();
  26659. this.onPrePointerObservable.clear();
  26660. };
  26661. /**
  26662. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26663. * Delay loaded resources are not taking in account
  26664. * @return true if all required resources are ready
  26665. */
  26666. Scene.prototype.isReady = function () {
  26667. if (this._isDisposed) {
  26668. return false;
  26669. }
  26670. if (this._pendingData.length > 0) {
  26671. return false;
  26672. }
  26673. var index;
  26674. var engine = this.getEngine();
  26675. // Geometries
  26676. for (index = 0; index < this.geometries.length; index++) {
  26677. var geometry = this.geometries[index];
  26678. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26679. return false;
  26680. }
  26681. }
  26682. // Meshes
  26683. for (index = 0; index < this.meshes.length; index++) {
  26684. var mesh = this.meshes[index];
  26685. if (!mesh.isEnabled()) {
  26686. continue;
  26687. }
  26688. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26689. continue;
  26690. }
  26691. if (!mesh.isReady(true)) {
  26692. return false;
  26693. }
  26694. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26695. // Is Ready For Mesh
  26696. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26697. var step = _a[_i];
  26698. if (!step.action(mesh, hardwareInstancedRendering)) {
  26699. return false;
  26700. }
  26701. }
  26702. }
  26703. // Post-processes
  26704. if (this.activeCameras && this.activeCameras.length > 0) {
  26705. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26706. var camera = _c[_b];
  26707. if (!camera.isReady(true)) {
  26708. return false;
  26709. }
  26710. }
  26711. }
  26712. else if (this.activeCamera) {
  26713. if (!this.activeCamera.isReady(true)) {
  26714. return false;
  26715. }
  26716. }
  26717. // Particles
  26718. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26719. var particleSystem = _e[_d];
  26720. if (!particleSystem.isReady()) {
  26721. return false;
  26722. }
  26723. }
  26724. return true;
  26725. };
  26726. /** Resets all cached information relative to material (including effect and visibility) */
  26727. Scene.prototype.resetCachedMaterial = function () {
  26728. this._cachedMaterial = null;
  26729. this._cachedEffect = null;
  26730. this._cachedVisibility = null;
  26731. };
  26732. /**
  26733. * Registers a function to be called before every frame render
  26734. * @param func defines the function to register
  26735. */
  26736. Scene.prototype.registerBeforeRender = function (func) {
  26737. this.onBeforeRenderObservable.add(func);
  26738. };
  26739. /**
  26740. * Unregisters a function called before every frame render
  26741. * @param func defines the function to unregister
  26742. */
  26743. Scene.prototype.unregisterBeforeRender = function (func) {
  26744. this.onBeforeRenderObservable.removeCallback(func);
  26745. };
  26746. /**
  26747. * Registers a function to be called after every frame render
  26748. * @param func defines the function to register
  26749. */
  26750. Scene.prototype.registerAfterRender = function (func) {
  26751. this.onAfterRenderObservable.add(func);
  26752. };
  26753. /**
  26754. * Unregisters a function called after every frame render
  26755. * @param func defines the function to unregister
  26756. */
  26757. Scene.prototype.unregisterAfterRender = function (func) {
  26758. this.onAfterRenderObservable.removeCallback(func);
  26759. };
  26760. Scene.prototype._executeOnceBeforeRender = function (func) {
  26761. var _this = this;
  26762. var execFunc = function () {
  26763. func();
  26764. setTimeout(function () {
  26765. _this.unregisterBeforeRender(execFunc);
  26766. });
  26767. };
  26768. this.registerBeforeRender(execFunc);
  26769. };
  26770. /**
  26771. * The provided function will run before render once and will be disposed afterwards.
  26772. * A timeout delay can be provided so that the function will be executed in N ms.
  26773. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26774. * @param func The function to be executed.
  26775. * @param timeout optional delay in ms
  26776. */
  26777. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26778. var _this = this;
  26779. if (timeout !== undefined) {
  26780. setTimeout(function () {
  26781. _this._executeOnceBeforeRender(func);
  26782. }, timeout);
  26783. }
  26784. else {
  26785. this._executeOnceBeforeRender(func);
  26786. }
  26787. };
  26788. /** @hidden */
  26789. Scene.prototype._addPendingData = function (data) {
  26790. this._pendingData.push(data);
  26791. };
  26792. /** @hidden */
  26793. Scene.prototype._removePendingData = function (data) {
  26794. var wasLoading = this.isLoading;
  26795. var index = this._pendingData.indexOf(data);
  26796. if (index !== -1) {
  26797. this._pendingData.splice(index, 1);
  26798. }
  26799. if (wasLoading && !this.isLoading) {
  26800. this.onDataLoadedObservable.notifyObservers(this);
  26801. }
  26802. };
  26803. /**
  26804. * Returns the number of items waiting to be loaded
  26805. * @returns the number of items waiting to be loaded
  26806. */
  26807. Scene.prototype.getWaitingItemsCount = function () {
  26808. return this._pendingData.length;
  26809. };
  26810. Object.defineProperty(Scene.prototype, "isLoading", {
  26811. /**
  26812. * Returns a boolean indicating if the scene is still loading data
  26813. */
  26814. get: function () {
  26815. return this._pendingData.length > 0;
  26816. },
  26817. enumerable: true,
  26818. configurable: true
  26819. });
  26820. /**
  26821. * Registers a function to be executed when the scene is ready
  26822. * @param {Function} func - the function to be executed
  26823. */
  26824. Scene.prototype.executeWhenReady = function (func) {
  26825. var _this = this;
  26826. this.onReadyObservable.add(func);
  26827. if (this._executeWhenReadyTimeoutId !== -1) {
  26828. return;
  26829. }
  26830. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26831. _this._checkIsReady();
  26832. }, 150);
  26833. };
  26834. /**
  26835. * Returns a promise that resolves when the scene is ready
  26836. * @returns A promise that resolves when the scene is ready
  26837. */
  26838. Scene.prototype.whenReadyAsync = function () {
  26839. var _this = this;
  26840. return new Promise(function (resolve) {
  26841. _this.executeWhenReady(function () {
  26842. resolve();
  26843. });
  26844. });
  26845. };
  26846. /** @hidden */
  26847. Scene.prototype._checkIsReady = function () {
  26848. var _this = this;
  26849. this._registerTransientComponents();
  26850. if (this.isReady()) {
  26851. this.onReadyObservable.notifyObservers(this);
  26852. this.onReadyObservable.clear();
  26853. this._executeWhenReadyTimeoutId = -1;
  26854. return;
  26855. }
  26856. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26857. _this._checkIsReady();
  26858. }, 150);
  26859. };
  26860. // Animations
  26861. /**
  26862. * Will start the animation sequence of a given target
  26863. * @param target defines the target
  26864. * @param from defines from which frame should animation start
  26865. * @param to defines until which frame should animation run.
  26866. * @param weight defines the weight to apply to the animation (1.0 by default)
  26867. * @param loop defines if the animation loops
  26868. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26869. * @param onAnimationEnd defines the function to be executed when the animation ends
  26870. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26871. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26872. * @returns the animatable object created for this animation
  26873. */
  26874. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26875. if (weight === void 0) { weight = 1.0; }
  26876. if (speedRatio === void 0) { speedRatio = 1.0; }
  26877. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26878. returnedAnimatable.weight = weight;
  26879. return returnedAnimatable;
  26880. };
  26881. /**
  26882. * Will start the animation sequence of a given target
  26883. * @param target defines the target
  26884. * @param from defines from which frame should animation start
  26885. * @param to defines until which frame should animation run.
  26886. * @param loop defines if the animation loops
  26887. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26888. * @param onAnimationEnd defines the function to be executed when the animation ends
  26889. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26890. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26891. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26892. * @returns the animatable object created for this animation
  26893. */
  26894. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26895. if (speedRatio === void 0) { speedRatio = 1.0; }
  26896. if (stopCurrent === void 0) { stopCurrent = true; }
  26897. if (from > to && speedRatio > 0) {
  26898. speedRatio *= -1;
  26899. }
  26900. if (stopCurrent) {
  26901. this.stopAnimation(target, undefined, targetMask);
  26902. }
  26903. if (!animatable) {
  26904. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26905. }
  26906. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26907. // Local animations
  26908. if (target.animations && shouldRunTargetAnimations) {
  26909. animatable.appendAnimations(target, target.animations);
  26910. }
  26911. // Children animations
  26912. if (target.getAnimatables) {
  26913. var animatables = target.getAnimatables();
  26914. for (var index = 0; index < animatables.length; index++) {
  26915. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26916. }
  26917. }
  26918. animatable.reset();
  26919. return animatable;
  26920. };
  26921. /**
  26922. * Begin a new animation on a given node
  26923. * @param target defines the target where the animation will take place
  26924. * @param animations defines the list of animations to start
  26925. * @param from defines the initial value
  26926. * @param to defines the final value
  26927. * @param loop defines if you want animation to loop (off by default)
  26928. * @param speedRatio defines the speed ratio to apply to all animations
  26929. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26930. * @returns the list of created animatables
  26931. */
  26932. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26933. if (speedRatio === undefined) {
  26934. speedRatio = 1.0;
  26935. }
  26936. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26937. return animatable;
  26938. };
  26939. /**
  26940. * Begin a new animation on a given node and its hierarchy
  26941. * @param target defines the root node where the animation will take place
  26942. * @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.
  26943. * @param animations defines the list of animations to start
  26944. * @param from defines the initial value
  26945. * @param to defines the final value
  26946. * @param loop defines if you want animation to loop (off by default)
  26947. * @param speedRatio defines the speed ratio to apply to all animations
  26948. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26949. * @returns the list of animatables created for all nodes
  26950. */
  26951. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26952. var children = target.getDescendants(directDescendantsOnly);
  26953. var result = [];
  26954. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26955. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26956. var child = children_1[_i];
  26957. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26958. }
  26959. return result;
  26960. };
  26961. /**
  26962. * Gets the animatable associated with a specific target
  26963. * @param target defines the target of the animatable
  26964. * @returns the required animatable if found
  26965. */
  26966. Scene.prototype.getAnimatableByTarget = function (target) {
  26967. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26968. if (this._activeAnimatables[index].target === target) {
  26969. return this._activeAnimatables[index];
  26970. }
  26971. }
  26972. return null;
  26973. };
  26974. /**
  26975. * Gets all animatables associated with a given target
  26976. * @param target defines the target to look animatables for
  26977. * @returns an array of Animatables
  26978. */
  26979. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26980. var result = [];
  26981. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26982. if (this._activeAnimatables[index].target === target) {
  26983. result.push(this._activeAnimatables[index]);
  26984. }
  26985. }
  26986. return result;
  26987. };
  26988. Object.defineProperty(Scene.prototype, "animatables", {
  26989. /**
  26990. * Gets all animatable attached to the scene
  26991. */
  26992. get: function () {
  26993. return this._activeAnimatables;
  26994. },
  26995. enumerable: true,
  26996. configurable: true
  26997. });
  26998. /**
  26999. * Will stop the animation of the given target
  27000. * @param target - the target
  27001. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27002. * @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)
  27003. */
  27004. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27005. var animatables = this.getAllAnimatablesByTarget(target);
  27006. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27007. var animatable = animatables_1[_i];
  27008. animatable.stop(animationName, targetMask);
  27009. }
  27010. };
  27011. /**
  27012. * Stops and removes all animations that have been applied to the scene
  27013. */
  27014. Scene.prototype.stopAllAnimations = function () {
  27015. if (this._activeAnimatables) {
  27016. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27017. this._activeAnimatables[i].stop();
  27018. }
  27019. this._activeAnimatables = [];
  27020. }
  27021. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27022. var group = _a[_i];
  27023. group.stop();
  27024. }
  27025. };
  27026. Scene.prototype._animate = function () {
  27027. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27028. return;
  27029. }
  27030. // Getting time
  27031. var now = BABYLON.Tools.Now;
  27032. if (!this._animationTimeLast) {
  27033. if (this._pendingData.length > 0) {
  27034. return;
  27035. }
  27036. this._animationTimeLast = now;
  27037. }
  27038. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27039. this._animationTime += deltaTime;
  27040. this._animationTimeLast = now;
  27041. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27042. this._activeAnimatables[index]._animate(this._animationTime);
  27043. }
  27044. // Late animation bindings
  27045. this._processLateAnimationBindings();
  27046. };
  27047. /** @hidden */
  27048. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27049. var target = runtimeAnimation.target;
  27050. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27051. if (!target._lateAnimationHolders) {
  27052. target._lateAnimationHolders = {};
  27053. }
  27054. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27055. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27056. totalWeight: 0,
  27057. animations: [],
  27058. originalValue: originalValue
  27059. };
  27060. }
  27061. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27062. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27063. };
  27064. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27065. var normalizer = 1.0;
  27066. var finalPosition = BABYLON.Tmp.Vector3[0];
  27067. var finalScaling = BABYLON.Tmp.Vector3[1];
  27068. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27069. var startIndex = 0;
  27070. var originalAnimation = holder.animations[0];
  27071. var originalValue = holder.originalValue;
  27072. var scale = 1;
  27073. if (holder.totalWeight < 1.0) {
  27074. // We need to mix the original value in
  27075. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27076. scale = 1.0 - holder.totalWeight;
  27077. }
  27078. else {
  27079. startIndex = 1;
  27080. // We need to normalize the weights
  27081. normalizer = holder.totalWeight;
  27082. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27083. scale = originalAnimation.weight / normalizer;
  27084. if (scale == 1) {
  27085. return originalAnimation.currentValue;
  27086. }
  27087. }
  27088. finalScaling.scaleInPlace(scale);
  27089. finalPosition.scaleInPlace(scale);
  27090. finalQuaternion.scaleInPlace(scale);
  27091. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27092. var runtimeAnimation = holder.animations[animIndex];
  27093. var scale = runtimeAnimation.weight / normalizer;
  27094. var currentPosition = BABYLON.Tmp.Vector3[2];
  27095. var currentScaling = BABYLON.Tmp.Vector3[3];
  27096. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27097. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27098. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27099. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27100. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27101. }
  27102. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27103. return originalAnimation._workValue;
  27104. };
  27105. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27106. var originalAnimation = holder.animations[0];
  27107. var originalValue = holder.originalValue;
  27108. if (holder.animations.length === 1) {
  27109. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27110. return refQuaternion;
  27111. }
  27112. var normalizer = 1.0;
  27113. var quaternions;
  27114. var weights;
  27115. if (holder.totalWeight < 1.0) {
  27116. var scale = 1.0 - holder.totalWeight;
  27117. quaternions = [];
  27118. weights = [];
  27119. quaternions.push(originalValue);
  27120. weights.push(scale);
  27121. }
  27122. else {
  27123. if (holder.animations.length === 2) { // Slerp as soon as we can
  27124. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27125. return refQuaternion;
  27126. }
  27127. quaternions = [];
  27128. weights = [];
  27129. normalizer = holder.totalWeight;
  27130. }
  27131. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27132. var runtimeAnimation = holder.animations[animIndex];
  27133. quaternions.push(runtimeAnimation.currentValue);
  27134. weights.push(runtimeAnimation.weight / normalizer);
  27135. }
  27136. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27137. var cumulativeAmount = 0;
  27138. var cumulativeQuaternion = null;
  27139. for (var index = 0; index < quaternions.length;) {
  27140. if (!cumulativeQuaternion) {
  27141. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27142. cumulativeQuaternion = refQuaternion;
  27143. cumulativeAmount = weights[index] + weights[index + 1];
  27144. index += 2;
  27145. continue;
  27146. }
  27147. cumulativeAmount += weights[index];
  27148. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27149. index++;
  27150. }
  27151. return cumulativeQuaternion;
  27152. };
  27153. Scene.prototype._processLateAnimationBindings = function () {
  27154. if (!this._registeredForLateAnimationBindings.length) {
  27155. return;
  27156. }
  27157. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27158. var target = this._registeredForLateAnimationBindings.data[index];
  27159. for (var path in target._lateAnimationHolders) {
  27160. var holder = target._lateAnimationHolders[path];
  27161. var originalAnimation = holder.animations[0];
  27162. var originalValue = holder.originalValue;
  27163. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27164. var finalValue = target[path];
  27165. if (matrixDecomposeMode) {
  27166. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27167. }
  27168. else {
  27169. var quaternionMode = originalValue.w !== undefined;
  27170. if (quaternionMode) {
  27171. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27172. }
  27173. else {
  27174. var startIndex = 0;
  27175. var normalizer = 1.0;
  27176. if (holder.totalWeight < 1.0) {
  27177. // We need to mix the original value in
  27178. if (originalValue.scale) {
  27179. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27180. }
  27181. else {
  27182. finalValue = originalValue * (1.0 - holder.totalWeight);
  27183. }
  27184. }
  27185. else {
  27186. // We need to normalize the weights
  27187. normalizer = holder.totalWeight;
  27188. var scale_1 = originalAnimation.weight / normalizer;
  27189. if (scale_1 !== 1) {
  27190. if (originalAnimation.currentValue.scale) {
  27191. finalValue = originalAnimation.currentValue.scale(scale_1);
  27192. }
  27193. else {
  27194. finalValue = originalAnimation.currentValue * scale_1;
  27195. }
  27196. }
  27197. else {
  27198. finalValue = originalAnimation.currentValue;
  27199. }
  27200. startIndex = 1;
  27201. }
  27202. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27203. var runtimeAnimation = holder.animations[animIndex];
  27204. var scale = runtimeAnimation.weight / normalizer;
  27205. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27206. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27207. }
  27208. else {
  27209. finalValue += runtimeAnimation.currentValue * scale;
  27210. }
  27211. }
  27212. }
  27213. }
  27214. target[path] = finalValue;
  27215. }
  27216. target._lateAnimationHolders = {};
  27217. }
  27218. this._registeredForLateAnimationBindings.reset();
  27219. };
  27220. // Matrix
  27221. /** @hidden */
  27222. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27223. this._useAlternateCameraConfiguration = active;
  27224. };
  27225. /**
  27226. * Gets the current view matrix
  27227. * @returns a Matrix
  27228. */
  27229. Scene.prototype.getViewMatrix = function () {
  27230. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27231. };
  27232. /**
  27233. * Gets the current projection matrix
  27234. * @returns a Matrix
  27235. */
  27236. Scene.prototype.getProjectionMatrix = function () {
  27237. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27238. };
  27239. /**
  27240. * Gets the current transform matrix
  27241. * @returns a Matrix made of View * Projection
  27242. */
  27243. Scene.prototype.getTransformMatrix = function () {
  27244. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27245. };
  27246. /**
  27247. * Sets the current transform matrix
  27248. * @param view defines the View matrix to use
  27249. * @param projection defines the Projection matrix to use
  27250. */
  27251. Scene.prototype.setTransformMatrix = function (view, projection) {
  27252. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27253. return;
  27254. }
  27255. this._viewUpdateFlag = view.updateFlag;
  27256. this._projectionUpdateFlag = projection.updateFlag;
  27257. this._viewMatrix = view;
  27258. this._projectionMatrix = projection;
  27259. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27260. // Update frustum
  27261. if (!this._frustumPlanes) {
  27262. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27263. }
  27264. else {
  27265. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27266. }
  27267. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27268. var otherCamera = this.activeCamera._alternateCamera;
  27269. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27270. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27271. }
  27272. if (this._sceneUbo.useUbo) {
  27273. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27274. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27275. this._sceneUbo.update();
  27276. }
  27277. };
  27278. /** @hidden */
  27279. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27280. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27281. return;
  27282. }
  27283. this._alternateViewUpdateFlag = view.updateFlag;
  27284. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27285. this._alternateViewMatrix = view;
  27286. this._alternateProjectionMatrix = projection;
  27287. if (!this._alternateTransformMatrix) {
  27288. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27289. }
  27290. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27291. if (!this._alternateSceneUbo) {
  27292. this._createAlternateUbo();
  27293. }
  27294. if (this._alternateSceneUbo.useUbo) {
  27295. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27296. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27297. this._alternateSceneUbo.update();
  27298. }
  27299. };
  27300. /**
  27301. * Gets the uniform buffer used to store scene data
  27302. * @returns a UniformBuffer
  27303. */
  27304. Scene.prototype.getSceneUniformBuffer = function () {
  27305. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27306. };
  27307. /**
  27308. * Gets an unique (relatively to the current scene) Id
  27309. * @returns an unique number for the scene
  27310. */
  27311. Scene.prototype.getUniqueId = function () {
  27312. var result = Scene._uniqueIdCounter;
  27313. Scene._uniqueIdCounter++;
  27314. return result;
  27315. };
  27316. /**
  27317. * Add a mesh to the list of scene's meshes
  27318. * @param newMesh defines the mesh to add
  27319. * @param recursive if all child meshes should also be added to the scene
  27320. */
  27321. Scene.prototype.addMesh = function (newMesh, recursive) {
  27322. var _this = this;
  27323. if (recursive === void 0) { recursive = false; }
  27324. this.meshes.push(newMesh);
  27325. //notify the collision coordinator
  27326. if (this.collisionCoordinator) {
  27327. this.collisionCoordinator.onMeshAdded(newMesh);
  27328. }
  27329. newMesh._resyncLightSources();
  27330. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27331. if (recursive) {
  27332. newMesh.getChildMeshes().forEach(function (m) {
  27333. _this.addMesh(m);
  27334. });
  27335. }
  27336. };
  27337. /**
  27338. * Remove a mesh for the list of scene's meshes
  27339. * @param toRemove defines the mesh to remove
  27340. * @param recursive if all child meshes should also be removed from the scene
  27341. * @returns the index where the mesh was in the mesh list
  27342. */
  27343. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27344. var _this = this;
  27345. if (recursive === void 0) { recursive = false; }
  27346. var index = this.meshes.indexOf(toRemove);
  27347. if (index !== -1) {
  27348. // Remove from the scene if mesh found
  27349. this.meshes.splice(index, 1);
  27350. }
  27351. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27352. if (recursive) {
  27353. toRemove.getChildMeshes().forEach(function (m) {
  27354. _this.removeMesh(m);
  27355. });
  27356. }
  27357. return index;
  27358. };
  27359. /**
  27360. * Add a transform node to the list of scene's transform nodes
  27361. * @param newTransformNode defines the transform node to add
  27362. */
  27363. Scene.prototype.addTransformNode = function (newTransformNode) {
  27364. this.transformNodes.push(newTransformNode);
  27365. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27366. };
  27367. /**
  27368. * Remove a transform node for the list of scene's transform nodes
  27369. * @param toRemove defines the transform node to remove
  27370. * @returns the index where the transform node was in the transform node list
  27371. */
  27372. Scene.prototype.removeTransformNode = function (toRemove) {
  27373. var index = this.transformNodes.indexOf(toRemove);
  27374. if (index !== -1) {
  27375. // Remove from the scene if found
  27376. this.transformNodes.splice(index, 1);
  27377. }
  27378. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27379. return index;
  27380. };
  27381. /**
  27382. * Remove a skeleton for the list of scene's skeletons
  27383. * @param toRemove defines the skeleton to remove
  27384. * @returns the index where the skeleton was in the skeleton list
  27385. */
  27386. Scene.prototype.removeSkeleton = function (toRemove) {
  27387. var index = this.skeletons.indexOf(toRemove);
  27388. if (index !== -1) {
  27389. // Remove from the scene if found
  27390. this.skeletons.splice(index, 1);
  27391. }
  27392. return index;
  27393. };
  27394. /**
  27395. * Remove a morph target for the list of scene's morph targets
  27396. * @param toRemove defines the morph target to remove
  27397. * @returns the index where the morph target was in the morph target list
  27398. */
  27399. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27400. var index = this.morphTargetManagers.indexOf(toRemove);
  27401. if (index !== -1) {
  27402. // Remove from the scene if found
  27403. this.morphTargetManagers.splice(index, 1);
  27404. }
  27405. return index;
  27406. };
  27407. /**
  27408. * Remove a light for the list of scene's lights
  27409. * @param toRemove defines the light to remove
  27410. * @returns the index where the light was in the light list
  27411. */
  27412. Scene.prototype.removeLight = function (toRemove) {
  27413. var index = this.lights.indexOf(toRemove);
  27414. if (index !== -1) {
  27415. // Remove from meshes
  27416. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27417. var mesh = _a[_i];
  27418. mesh._removeLightSource(toRemove);
  27419. }
  27420. // Remove from the scene if mesh found
  27421. this.lights.splice(index, 1);
  27422. this.sortLightsByPriority();
  27423. }
  27424. this.onLightRemovedObservable.notifyObservers(toRemove);
  27425. return index;
  27426. };
  27427. /**
  27428. * Remove a camera for the list of scene's cameras
  27429. * @param toRemove defines the camera to remove
  27430. * @returns the index where the camera was in the camera list
  27431. */
  27432. Scene.prototype.removeCamera = function (toRemove) {
  27433. var index = this.cameras.indexOf(toRemove);
  27434. if (index !== -1) {
  27435. // Remove from the scene if mesh found
  27436. this.cameras.splice(index, 1);
  27437. }
  27438. // Remove from activeCameras
  27439. var index2 = this.activeCameras.indexOf(toRemove);
  27440. if (index2 !== -1) {
  27441. // Remove from the scene if mesh found
  27442. this.activeCameras.splice(index2, 1);
  27443. }
  27444. // Reset the activeCamera
  27445. if (this.activeCamera === toRemove) {
  27446. if (this.cameras.length > 0) {
  27447. this.activeCamera = this.cameras[0];
  27448. }
  27449. else {
  27450. this.activeCamera = null;
  27451. }
  27452. }
  27453. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27454. return index;
  27455. };
  27456. /**
  27457. * Remove a particle system for the list of scene's particle systems
  27458. * @param toRemove defines the particle system to remove
  27459. * @returns the index where the particle system was in the particle system list
  27460. */
  27461. Scene.prototype.removeParticleSystem = function (toRemove) {
  27462. var index = this.particleSystems.indexOf(toRemove);
  27463. if (index !== -1) {
  27464. this.particleSystems.splice(index, 1);
  27465. }
  27466. return index;
  27467. };
  27468. /**
  27469. * Remove a animation for the list of scene's animations
  27470. * @param toRemove defines the animation to remove
  27471. * @returns the index where the animation was in the animation list
  27472. */
  27473. Scene.prototype.removeAnimation = function (toRemove) {
  27474. var index = this.animations.indexOf(toRemove);
  27475. if (index !== -1) {
  27476. this.animations.splice(index, 1);
  27477. }
  27478. return index;
  27479. };
  27480. /**
  27481. * Removes the given animation group from this scene.
  27482. * @param toRemove The animation group to remove
  27483. * @returns The index of the removed animation group
  27484. */
  27485. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27486. var index = this.animationGroups.indexOf(toRemove);
  27487. if (index !== -1) {
  27488. this.animationGroups.splice(index, 1);
  27489. }
  27490. return index;
  27491. };
  27492. /**
  27493. * Removes the given multi-material from this scene.
  27494. * @param toRemove The multi-material to remove
  27495. * @returns The index of the removed multi-material
  27496. */
  27497. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27498. var index = this.multiMaterials.indexOf(toRemove);
  27499. if (index !== -1) {
  27500. this.multiMaterials.splice(index, 1);
  27501. }
  27502. return index;
  27503. };
  27504. /**
  27505. * Removes the given material from this scene.
  27506. * @param toRemove The material to remove
  27507. * @returns The index of the removed material
  27508. */
  27509. Scene.prototype.removeMaterial = function (toRemove) {
  27510. var index = this.materials.indexOf(toRemove);
  27511. if (index !== -1) {
  27512. this.materials.splice(index, 1);
  27513. }
  27514. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27515. return index;
  27516. };
  27517. /**
  27518. * Removes the given action manager from this scene.
  27519. * @param toRemove The action manager to remove
  27520. * @returns The index of the removed action manager
  27521. */
  27522. Scene.prototype.removeActionManager = function (toRemove) {
  27523. var index = this.actionManagers.indexOf(toRemove);
  27524. if (index !== -1) {
  27525. this.actionManagers.splice(index, 1);
  27526. }
  27527. return index;
  27528. };
  27529. /**
  27530. * Removes the given texture from this scene.
  27531. * @param toRemove The texture to remove
  27532. * @returns The index of the removed texture
  27533. */
  27534. Scene.prototype.removeTexture = function (toRemove) {
  27535. var index = this.textures.indexOf(toRemove);
  27536. if (index !== -1) {
  27537. this.textures.splice(index, 1);
  27538. }
  27539. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27540. return index;
  27541. };
  27542. /**
  27543. * Adds the given light to this scene
  27544. * @param newLight The light to add
  27545. */
  27546. Scene.prototype.addLight = function (newLight) {
  27547. this.lights.push(newLight);
  27548. this.sortLightsByPriority();
  27549. // Add light to all meshes (To support if the light is removed and then readded)
  27550. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27551. var mesh = _a[_i];
  27552. if (mesh._lightSources.indexOf(newLight) === -1) {
  27553. mesh._lightSources.push(newLight);
  27554. mesh._resyncLightSources();
  27555. }
  27556. }
  27557. this.onNewLightAddedObservable.notifyObservers(newLight);
  27558. };
  27559. /**
  27560. * Sorts the list list based on light priorities
  27561. */
  27562. Scene.prototype.sortLightsByPriority = function () {
  27563. if (this.requireLightSorting) {
  27564. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27565. }
  27566. };
  27567. /**
  27568. * Adds the given camera to this scene
  27569. * @param newCamera The camera to add
  27570. */
  27571. Scene.prototype.addCamera = function (newCamera) {
  27572. this.cameras.push(newCamera);
  27573. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27574. };
  27575. /**
  27576. * Adds the given skeleton to this scene
  27577. * @param newSkeleton The skeleton to add
  27578. */
  27579. Scene.prototype.addSkeleton = function (newSkeleton) {
  27580. this.skeletons.push(newSkeleton);
  27581. };
  27582. /**
  27583. * Adds the given particle system to this scene
  27584. * @param newParticleSystem The particle system to add
  27585. */
  27586. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27587. this.particleSystems.push(newParticleSystem);
  27588. };
  27589. /**
  27590. * Adds the given animation to this scene
  27591. * @param newAnimation The animation to add
  27592. */
  27593. Scene.prototype.addAnimation = function (newAnimation) {
  27594. this.animations.push(newAnimation);
  27595. };
  27596. /**
  27597. * Adds the given animation group to this scene.
  27598. * @param newAnimationGroup The animation group to add
  27599. */
  27600. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27601. this.animationGroups.push(newAnimationGroup);
  27602. };
  27603. /**
  27604. * Adds the given multi-material to this scene
  27605. * @param newMultiMaterial The multi-material to add
  27606. */
  27607. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27608. this.multiMaterials.push(newMultiMaterial);
  27609. };
  27610. /**
  27611. * Adds the given material to this scene
  27612. * @param newMaterial The material to add
  27613. */
  27614. Scene.prototype.addMaterial = function (newMaterial) {
  27615. this.materials.push(newMaterial);
  27616. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27617. };
  27618. /**
  27619. * Adds the given morph target to this scene
  27620. * @param newMorphTargetManager The morph target to add
  27621. */
  27622. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27623. this.morphTargetManagers.push(newMorphTargetManager);
  27624. };
  27625. /**
  27626. * Adds the given geometry to this scene
  27627. * @param newGeometry The geometry to add
  27628. */
  27629. Scene.prototype.addGeometry = function (newGeometry) {
  27630. this.geometries.push(newGeometry);
  27631. };
  27632. /**
  27633. * Adds the given action manager to this scene
  27634. * @param newActionManager The action manager to add
  27635. */
  27636. Scene.prototype.addActionManager = function (newActionManager) {
  27637. this.actionManagers.push(newActionManager);
  27638. };
  27639. /**
  27640. * Adds the given texture to this scene.
  27641. * @param newTexture The texture to add
  27642. */
  27643. Scene.prototype.addTexture = function (newTexture) {
  27644. this.textures.push(newTexture);
  27645. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27646. };
  27647. /**
  27648. * Switch active camera
  27649. * @param newCamera defines the new active camera
  27650. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27651. */
  27652. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27653. if (attachControl === void 0) { attachControl = true; }
  27654. var canvas = this._engine.getRenderingCanvas();
  27655. if (!canvas) {
  27656. return;
  27657. }
  27658. if (this.activeCamera) {
  27659. this.activeCamera.detachControl(canvas);
  27660. }
  27661. this.activeCamera = newCamera;
  27662. if (attachControl) {
  27663. newCamera.attachControl(canvas);
  27664. }
  27665. };
  27666. /**
  27667. * sets the active camera of the scene using its ID
  27668. * @param id defines the camera's ID
  27669. * @return the new active camera or null if none found.
  27670. */
  27671. Scene.prototype.setActiveCameraByID = function (id) {
  27672. var camera = this.getCameraByID(id);
  27673. if (camera) {
  27674. this.activeCamera = camera;
  27675. return camera;
  27676. }
  27677. return null;
  27678. };
  27679. /**
  27680. * sets the active camera of the scene using its name
  27681. * @param name defines the camera's name
  27682. * @returns the new active camera or null if none found.
  27683. */
  27684. Scene.prototype.setActiveCameraByName = function (name) {
  27685. var camera = this.getCameraByName(name);
  27686. if (camera) {
  27687. this.activeCamera = camera;
  27688. return camera;
  27689. }
  27690. return null;
  27691. };
  27692. /**
  27693. * get an animation group using its name
  27694. * @param name defines the material's name
  27695. * @return the animation group or null if none found.
  27696. */
  27697. Scene.prototype.getAnimationGroupByName = function (name) {
  27698. for (var index = 0; index < this.animationGroups.length; index++) {
  27699. if (this.animationGroups[index].name === name) {
  27700. return this.animationGroups[index];
  27701. }
  27702. }
  27703. return null;
  27704. };
  27705. /**
  27706. * get a material using its id
  27707. * @param id defines the material's ID
  27708. * @return the material or null if none found.
  27709. */
  27710. Scene.prototype.getMaterialByID = function (id) {
  27711. for (var index = 0; index < this.materials.length; index++) {
  27712. if (this.materials[index].id === id) {
  27713. return this.materials[index];
  27714. }
  27715. }
  27716. return null;
  27717. };
  27718. /**
  27719. * Gets a material using its name
  27720. * @param name defines the material's name
  27721. * @return the material or null if none found.
  27722. */
  27723. Scene.prototype.getMaterialByName = function (name) {
  27724. for (var index = 0; index < this.materials.length; index++) {
  27725. if (this.materials[index].name === name) {
  27726. return this.materials[index];
  27727. }
  27728. }
  27729. return null;
  27730. };
  27731. /**
  27732. * Gets a camera using its id
  27733. * @param id defines the id to look for
  27734. * @returns the camera or null if not found
  27735. */
  27736. Scene.prototype.getCameraByID = function (id) {
  27737. for (var index = 0; index < this.cameras.length; index++) {
  27738. if (this.cameras[index].id === id) {
  27739. return this.cameras[index];
  27740. }
  27741. }
  27742. return null;
  27743. };
  27744. /**
  27745. * Gets a camera using its unique id
  27746. * @param uniqueId defines the unique id to look for
  27747. * @returns the camera or null if not found
  27748. */
  27749. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27750. for (var index = 0; index < this.cameras.length; index++) {
  27751. if (this.cameras[index].uniqueId === uniqueId) {
  27752. return this.cameras[index];
  27753. }
  27754. }
  27755. return null;
  27756. };
  27757. /**
  27758. * Gets a camera using its name
  27759. * @param name defines the camera's name
  27760. * @return the camera or null if none found.
  27761. */
  27762. Scene.prototype.getCameraByName = function (name) {
  27763. for (var index = 0; index < this.cameras.length; index++) {
  27764. if (this.cameras[index].name === name) {
  27765. return this.cameras[index];
  27766. }
  27767. }
  27768. return null;
  27769. };
  27770. /**
  27771. * Gets a bone using its id
  27772. * @param id defines the bone's id
  27773. * @return the bone or null if not found
  27774. */
  27775. Scene.prototype.getBoneByID = function (id) {
  27776. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27777. var skeleton = this.skeletons[skeletonIndex];
  27778. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27779. if (skeleton.bones[boneIndex].id === id) {
  27780. return skeleton.bones[boneIndex];
  27781. }
  27782. }
  27783. }
  27784. return null;
  27785. };
  27786. /**
  27787. * Gets a bone using its id
  27788. * @param name defines the bone's name
  27789. * @return the bone or null if not found
  27790. */
  27791. Scene.prototype.getBoneByName = function (name) {
  27792. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27793. var skeleton = this.skeletons[skeletonIndex];
  27794. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27795. if (skeleton.bones[boneIndex].name === name) {
  27796. return skeleton.bones[boneIndex];
  27797. }
  27798. }
  27799. }
  27800. return null;
  27801. };
  27802. /**
  27803. * Gets a light node using its name
  27804. * @param name defines the the light's name
  27805. * @return the light or null if none found.
  27806. */
  27807. Scene.prototype.getLightByName = function (name) {
  27808. for (var index = 0; index < this.lights.length; index++) {
  27809. if (this.lights[index].name === name) {
  27810. return this.lights[index];
  27811. }
  27812. }
  27813. return null;
  27814. };
  27815. /**
  27816. * Gets a light node using its id
  27817. * @param id defines the light's id
  27818. * @return the light or null if none found.
  27819. */
  27820. Scene.prototype.getLightByID = function (id) {
  27821. for (var index = 0; index < this.lights.length; index++) {
  27822. if (this.lights[index].id === id) {
  27823. return this.lights[index];
  27824. }
  27825. }
  27826. return null;
  27827. };
  27828. /**
  27829. * Gets a light node using its scene-generated unique ID
  27830. * @param uniqueId defines the light's unique id
  27831. * @return the light or null if none found.
  27832. */
  27833. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27834. for (var index = 0; index < this.lights.length; index++) {
  27835. if (this.lights[index].uniqueId === uniqueId) {
  27836. return this.lights[index];
  27837. }
  27838. }
  27839. return null;
  27840. };
  27841. /**
  27842. * Gets a particle system by id
  27843. * @param id defines the particle system id
  27844. * @return the corresponding system or null if none found
  27845. */
  27846. Scene.prototype.getParticleSystemByID = function (id) {
  27847. for (var index = 0; index < this.particleSystems.length; index++) {
  27848. if (this.particleSystems[index].id === id) {
  27849. return this.particleSystems[index];
  27850. }
  27851. }
  27852. return null;
  27853. };
  27854. /**
  27855. * Gets a geometry using its ID
  27856. * @param id defines the geometry's id
  27857. * @return the geometry or null if none found.
  27858. */
  27859. Scene.prototype.getGeometryByID = function (id) {
  27860. for (var index = 0; index < this.geometries.length; index++) {
  27861. if (this.geometries[index].id === id) {
  27862. return this.geometries[index];
  27863. }
  27864. }
  27865. return null;
  27866. };
  27867. /**
  27868. * Add a new geometry to this scene
  27869. * @param geometry defines the geometry to be added to the scene.
  27870. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27871. * @return a boolean defining if the geometry was added or not
  27872. */
  27873. Scene.prototype.pushGeometry = function (geometry, force) {
  27874. if (!force && this.getGeometryByID(geometry.id)) {
  27875. return false;
  27876. }
  27877. this.geometries.push(geometry);
  27878. //notify the collision coordinator
  27879. if (this.collisionCoordinator) {
  27880. this.collisionCoordinator.onGeometryAdded(geometry);
  27881. }
  27882. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27883. return true;
  27884. };
  27885. /**
  27886. * Removes an existing geometry
  27887. * @param geometry defines the geometry to be removed from the scene
  27888. * @return a boolean defining if the geometry was removed or not
  27889. */
  27890. Scene.prototype.removeGeometry = function (geometry) {
  27891. var index = this.geometries.indexOf(geometry);
  27892. if (index > -1) {
  27893. this.geometries.splice(index, 1);
  27894. //notify the collision coordinator
  27895. if (this.collisionCoordinator) {
  27896. this.collisionCoordinator.onGeometryDeleted(geometry);
  27897. }
  27898. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27899. return true;
  27900. }
  27901. return false;
  27902. };
  27903. /**
  27904. * Gets the list of geometries attached to the scene
  27905. * @returns an array of Geometry
  27906. */
  27907. Scene.prototype.getGeometries = function () {
  27908. return this.geometries;
  27909. };
  27910. /**
  27911. * Gets the first added mesh found of a given ID
  27912. * @param id defines the id to search for
  27913. * @return the mesh found or null if not found at all
  27914. */
  27915. Scene.prototype.getMeshByID = function (id) {
  27916. for (var index = 0; index < this.meshes.length; index++) {
  27917. if (this.meshes[index].id === id) {
  27918. return this.meshes[index];
  27919. }
  27920. }
  27921. return null;
  27922. };
  27923. /**
  27924. * Gets a list of meshes using their id
  27925. * @param id defines the id to search for
  27926. * @returns a list of meshes
  27927. */
  27928. Scene.prototype.getMeshesByID = function (id) {
  27929. return this.meshes.filter(function (m) {
  27930. return m.id === id;
  27931. });
  27932. };
  27933. /**
  27934. * Gets the first added transform node found of a given ID
  27935. * @param id defines the id to search for
  27936. * @return the found transform node or null if not found at all.
  27937. */
  27938. Scene.prototype.getTransformNodeByID = function (id) {
  27939. for (var index = 0; index < this.transformNodes.length; index++) {
  27940. if (this.transformNodes[index].id === id) {
  27941. return this.transformNodes[index];
  27942. }
  27943. }
  27944. return null;
  27945. };
  27946. /**
  27947. * Gets a list of transform nodes using their id
  27948. * @param id defines the id to search for
  27949. * @returns a list of transform nodes
  27950. */
  27951. Scene.prototype.getTransformNodesByID = function (id) {
  27952. return this.transformNodes.filter(function (m) {
  27953. return m.id === id;
  27954. });
  27955. };
  27956. /**
  27957. * Gets a mesh with its auto-generated unique id
  27958. * @param uniqueId defines the unique id to search for
  27959. * @return the found mesh or null if not found at all.
  27960. */
  27961. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27962. for (var index = 0; index < this.meshes.length; index++) {
  27963. if (this.meshes[index].uniqueId === uniqueId) {
  27964. return this.meshes[index];
  27965. }
  27966. }
  27967. return null;
  27968. };
  27969. /**
  27970. * Gets a the last added mesh using a given id
  27971. * @param id defines the id to search for
  27972. * @return the found mesh or null if not found at all.
  27973. */
  27974. Scene.prototype.getLastMeshByID = function (id) {
  27975. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27976. if (this.meshes[index].id === id) {
  27977. return this.meshes[index];
  27978. }
  27979. }
  27980. return null;
  27981. };
  27982. /**
  27983. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27984. * @param id defines the id to search for
  27985. * @return the found node or null if not found at all
  27986. */
  27987. Scene.prototype.getLastEntryByID = function (id) {
  27988. var index;
  27989. for (index = this.meshes.length - 1; index >= 0; index--) {
  27990. if (this.meshes[index].id === id) {
  27991. return this.meshes[index];
  27992. }
  27993. }
  27994. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27995. if (this.transformNodes[index].id === id) {
  27996. return this.transformNodes[index];
  27997. }
  27998. }
  27999. for (index = this.cameras.length - 1; index >= 0; index--) {
  28000. if (this.cameras[index].id === id) {
  28001. return this.cameras[index];
  28002. }
  28003. }
  28004. for (index = this.lights.length - 1; index >= 0; index--) {
  28005. if (this.lights[index].id === id) {
  28006. return this.lights[index];
  28007. }
  28008. }
  28009. return null;
  28010. };
  28011. /**
  28012. * Gets a node (Mesh, Camera, Light) using a given id
  28013. * @param id defines the id to search for
  28014. * @return the found node or null if not found at all
  28015. */
  28016. Scene.prototype.getNodeByID = function (id) {
  28017. var mesh = this.getMeshByID(id);
  28018. if (mesh) {
  28019. return mesh;
  28020. }
  28021. var light = this.getLightByID(id);
  28022. if (light) {
  28023. return light;
  28024. }
  28025. var camera = this.getCameraByID(id);
  28026. if (camera) {
  28027. return camera;
  28028. }
  28029. var bone = this.getBoneByID(id);
  28030. return bone;
  28031. };
  28032. /**
  28033. * Gets a node (Mesh, Camera, Light) using a given name
  28034. * @param name defines the name to search for
  28035. * @return the found node or null if not found at all.
  28036. */
  28037. Scene.prototype.getNodeByName = function (name) {
  28038. var mesh = this.getMeshByName(name);
  28039. if (mesh) {
  28040. return mesh;
  28041. }
  28042. var light = this.getLightByName(name);
  28043. if (light) {
  28044. return light;
  28045. }
  28046. var camera = this.getCameraByName(name);
  28047. if (camera) {
  28048. return camera;
  28049. }
  28050. var bone = this.getBoneByName(name);
  28051. return bone;
  28052. };
  28053. /**
  28054. * Gets a mesh using a given name
  28055. * @param name defines the name to search for
  28056. * @return the found mesh or null if not found at all.
  28057. */
  28058. Scene.prototype.getMeshByName = function (name) {
  28059. for (var index = 0; index < this.meshes.length; index++) {
  28060. if (this.meshes[index].name === name) {
  28061. return this.meshes[index];
  28062. }
  28063. }
  28064. return null;
  28065. };
  28066. /**
  28067. * Gets a transform node using a given name
  28068. * @param name defines the name to search for
  28069. * @return the found transform node or null if not found at all.
  28070. */
  28071. Scene.prototype.getTransformNodeByName = function (name) {
  28072. for (var index = 0; index < this.transformNodes.length; index++) {
  28073. if (this.transformNodes[index].name === name) {
  28074. return this.transformNodes[index];
  28075. }
  28076. }
  28077. return null;
  28078. };
  28079. /**
  28080. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28081. * @param id defines the id to search for
  28082. * @return the found skeleton or null if not found at all.
  28083. */
  28084. Scene.prototype.getLastSkeletonByID = function (id) {
  28085. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28086. if (this.skeletons[index].id === id) {
  28087. return this.skeletons[index];
  28088. }
  28089. }
  28090. return null;
  28091. };
  28092. /**
  28093. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28094. * @param id defines the id to search for
  28095. * @return the found skeleton or null if not found at all.
  28096. */
  28097. Scene.prototype.getSkeletonById = function (id) {
  28098. for (var index = 0; index < this.skeletons.length; index++) {
  28099. if (this.skeletons[index].id === id) {
  28100. return this.skeletons[index];
  28101. }
  28102. }
  28103. return null;
  28104. };
  28105. /**
  28106. * Gets a skeleton using a given name
  28107. * @param name defines the name to search for
  28108. * @return the found skeleton or null if not found at all.
  28109. */
  28110. Scene.prototype.getSkeletonByName = function (name) {
  28111. for (var index = 0; index < this.skeletons.length; index++) {
  28112. if (this.skeletons[index].name === name) {
  28113. return this.skeletons[index];
  28114. }
  28115. }
  28116. return null;
  28117. };
  28118. /**
  28119. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28120. * @param id defines the id to search for
  28121. * @return the found morph target manager or null if not found at all.
  28122. */
  28123. Scene.prototype.getMorphTargetManagerById = function (id) {
  28124. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28125. if (this.morphTargetManagers[index].uniqueId === id) {
  28126. return this.morphTargetManagers[index];
  28127. }
  28128. }
  28129. return null;
  28130. };
  28131. /**
  28132. * Gets a boolean indicating if the given mesh is active
  28133. * @param mesh defines the mesh to look for
  28134. * @returns true if the mesh is in the active list
  28135. */
  28136. Scene.prototype.isActiveMesh = function (mesh) {
  28137. return (this._activeMeshes.indexOf(mesh) !== -1);
  28138. };
  28139. Object.defineProperty(Scene.prototype, "uid", {
  28140. /**
  28141. * Return a unique id as a string which can serve as an identifier for the scene
  28142. */
  28143. get: function () {
  28144. if (!this._uid) {
  28145. this._uid = BABYLON.Tools.RandomId();
  28146. }
  28147. return this._uid;
  28148. },
  28149. enumerable: true,
  28150. configurable: true
  28151. });
  28152. /**
  28153. * Add an externaly attached data from its key.
  28154. * This method call will fail and return false, if such key already exists.
  28155. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28156. * @param key the unique key that identifies the data
  28157. * @param data the data object to associate to the key for this Engine instance
  28158. * @return true if no such key were already present and the data was added successfully, false otherwise
  28159. */
  28160. Scene.prototype.addExternalData = function (key, data) {
  28161. if (!this._externalData) {
  28162. this._externalData = new BABYLON.StringDictionary();
  28163. }
  28164. return this._externalData.add(key, data);
  28165. };
  28166. /**
  28167. * Get an externaly attached data from its key
  28168. * @param key the unique key that identifies the data
  28169. * @return the associated data, if present (can be null), or undefined if not present
  28170. */
  28171. Scene.prototype.getExternalData = function (key) {
  28172. if (!this._externalData) {
  28173. return null;
  28174. }
  28175. return this._externalData.get(key);
  28176. };
  28177. /**
  28178. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28179. * @param key the unique key that identifies the data
  28180. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28181. * @return the associated data, can be null if the factory returned null.
  28182. */
  28183. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28184. if (!this._externalData) {
  28185. this._externalData = new BABYLON.StringDictionary();
  28186. }
  28187. return this._externalData.getOrAddWithFactory(key, factory);
  28188. };
  28189. /**
  28190. * Remove an externaly attached data from the Engine instance
  28191. * @param key the unique key that identifies the data
  28192. * @return true if the data was successfully removed, false if it doesn't exist
  28193. */
  28194. Scene.prototype.removeExternalData = function (key) {
  28195. return this._externalData.remove(key);
  28196. };
  28197. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28198. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28199. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28200. var step = _a[_i];
  28201. step.action(mesh, subMesh);
  28202. }
  28203. var material = subMesh.getMaterial();
  28204. if (material !== null && material !== undefined) {
  28205. // Render targets
  28206. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28207. if (this._processedMaterials.indexOf(material) === -1) {
  28208. this._processedMaterials.push(material);
  28209. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28210. }
  28211. }
  28212. // Dispatch
  28213. this._activeIndices.addCount(subMesh.indexCount, false);
  28214. this._renderingManager.dispatch(subMesh, mesh, material);
  28215. }
  28216. }
  28217. };
  28218. /**
  28219. * Clear the processed materials smart array preventing retention point in material dispose.
  28220. */
  28221. Scene.prototype.freeProcessedMaterials = function () {
  28222. this._processedMaterials.dispose();
  28223. };
  28224. /**
  28225. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28226. */
  28227. Scene.prototype.freeActiveMeshes = function () {
  28228. this._activeMeshes.dispose();
  28229. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28230. this.activeCamera._activeMeshes.dispose();
  28231. }
  28232. if (this.activeCameras) {
  28233. for (var i = 0; i < this.activeCameras.length; i++) {
  28234. var activeCamera = this.activeCameras[i];
  28235. if (activeCamera && activeCamera._activeMeshes) {
  28236. activeCamera._activeMeshes.dispose();
  28237. }
  28238. }
  28239. }
  28240. };
  28241. /**
  28242. * Clear the info related to rendering groups preventing retention points during dispose.
  28243. */
  28244. Scene.prototype.freeRenderingGroups = function () {
  28245. if (this._renderingManager) {
  28246. this._renderingManager.freeRenderingGroups();
  28247. }
  28248. if (this.textures) {
  28249. for (var i = 0; i < this.textures.length; i++) {
  28250. var texture = this.textures[i];
  28251. if (texture && texture.renderList) {
  28252. texture.freeRenderingGroups();
  28253. }
  28254. }
  28255. }
  28256. };
  28257. /** @hidden */
  28258. Scene.prototype._isInIntermediateRendering = function () {
  28259. return this._intermediateRendering;
  28260. };
  28261. /**
  28262. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28263. * @returns the current scene
  28264. */
  28265. Scene.prototype.freezeActiveMeshes = function () {
  28266. if (!this.activeCamera) {
  28267. return this;
  28268. }
  28269. if (!this._frustumPlanes) {
  28270. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28271. }
  28272. this._evaluateActiveMeshes();
  28273. this._activeMeshesFrozen = true;
  28274. return this;
  28275. };
  28276. /**
  28277. * Use this function to restart evaluating active meshes on every frame
  28278. * @returns the current scene
  28279. */
  28280. Scene.prototype.unfreezeActiveMeshes = function () {
  28281. this._activeMeshesFrozen = false;
  28282. return this;
  28283. };
  28284. Scene.prototype._evaluateActiveMeshes = function () {
  28285. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28286. return;
  28287. }
  28288. if (!this.activeCamera) {
  28289. return;
  28290. }
  28291. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28292. this.activeCamera._activeMeshes.reset();
  28293. this._activeMeshes.reset();
  28294. this._renderingManager.reset();
  28295. this._processedMaterials.reset();
  28296. this._activeParticleSystems.reset();
  28297. this._activeSkeletons.reset();
  28298. this._softwareSkinnedMeshes.reset();
  28299. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28300. var step = _a[_i];
  28301. step.action();
  28302. }
  28303. // Determine mesh candidates
  28304. var meshes = this.getActiveMeshCandidates();
  28305. // Check each mesh
  28306. var len = meshes.length;
  28307. for (var i = 0; i < len; i++) {
  28308. var mesh = meshes.data[i];
  28309. if (mesh.isBlocked) {
  28310. continue;
  28311. }
  28312. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28313. if (!mesh.isReady() || !mesh.isEnabled()) {
  28314. continue;
  28315. }
  28316. mesh.computeWorldMatrix();
  28317. // Intersections
  28318. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28319. this._meshesForIntersections.pushNoDuplicate(mesh);
  28320. }
  28321. // Switch to current LOD
  28322. var meshLOD = mesh.getLOD(this.activeCamera);
  28323. if (meshLOD === undefined || meshLOD === null) {
  28324. continue;
  28325. }
  28326. mesh._preActivate();
  28327. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28328. this._activeMeshes.push(mesh);
  28329. this.activeCamera._activeMeshes.push(mesh);
  28330. mesh._activate(this._renderId);
  28331. if (meshLOD !== mesh) {
  28332. meshLOD._activate(this._renderId);
  28333. }
  28334. this._activeMesh(mesh, meshLOD);
  28335. }
  28336. }
  28337. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28338. // Particle systems
  28339. if (this.particlesEnabled) {
  28340. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28341. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28342. var particleSystem = this.particleSystems[particleIndex];
  28343. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28344. continue;
  28345. }
  28346. var emitter = particleSystem.emitter;
  28347. if (!emitter.position || emitter.isEnabled()) {
  28348. this._activeParticleSystems.push(particleSystem);
  28349. particleSystem.animate();
  28350. this._renderingManager.dispatchParticles(particleSystem);
  28351. }
  28352. }
  28353. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28354. }
  28355. };
  28356. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28357. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28358. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28359. mesh.skeleton.prepare();
  28360. }
  28361. if (!mesh.computeBonesUsingShaders) {
  28362. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28363. }
  28364. }
  28365. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28366. var step = _a[_i];
  28367. step.action(sourceMesh, mesh);
  28368. }
  28369. if (mesh !== undefined && mesh !== null
  28370. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28371. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28372. var len = subMeshes.length;
  28373. for (var i = 0; i < len; i++) {
  28374. var subMesh = subMeshes.data[i];
  28375. this._evaluateSubMesh(subMesh, mesh);
  28376. }
  28377. }
  28378. };
  28379. /**
  28380. * Update the transform matrix to update from the current active camera
  28381. * @param force defines a boolean used to force the update even if cache is up to date
  28382. */
  28383. Scene.prototype.updateTransformMatrix = function (force) {
  28384. if (!this.activeCamera) {
  28385. return;
  28386. }
  28387. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28388. };
  28389. /**
  28390. * 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)
  28391. * @param alternateCamera defines the camera to use
  28392. */
  28393. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28394. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28395. };
  28396. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28397. if (camera && camera._skipRendering) {
  28398. return;
  28399. }
  28400. var engine = this._engine;
  28401. this.activeCamera = camera;
  28402. if (!this.activeCamera)
  28403. throw new Error("Active camera not set");
  28404. // Viewport
  28405. engine.setViewport(this.activeCamera.viewport);
  28406. // Camera
  28407. this.resetCachedMaterial();
  28408. this._renderId++;
  28409. this.updateTransformMatrix();
  28410. if (camera._alternateCamera) {
  28411. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28412. this._alternateRendering = true;
  28413. }
  28414. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28415. // Meshes
  28416. this._evaluateActiveMeshes();
  28417. // Software skinning
  28418. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28419. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28420. mesh.applySkeleton(mesh.skeleton);
  28421. }
  28422. // Render targets
  28423. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28424. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28425. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28426. }
  28427. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28428. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28429. }
  28430. // Collects render targets from external components.
  28431. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28432. var step = _a[_i];
  28433. step.action(this._renderTargets);
  28434. }
  28435. if (this.renderTargetsEnabled) {
  28436. this._intermediateRendering = true;
  28437. if (this._renderTargets.length > 0) {
  28438. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28439. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28440. var renderTarget = this._renderTargets.data[renderIndex];
  28441. if (renderTarget._shouldRender()) {
  28442. this._renderId++;
  28443. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28444. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28445. }
  28446. }
  28447. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28448. this._renderId++;
  28449. }
  28450. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28451. var step = _c[_b];
  28452. step.action(this.activeCamera);
  28453. }
  28454. this._intermediateRendering = false;
  28455. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28456. }
  28457. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28458. // Prepare Frame
  28459. if (this.postProcessManager) {
  28460. this.postProcessManager._prepareFrame();
  28461. }
  28462. // Before Camera Draw
  28463. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28464. var step = _e[_d];
  28465. step.action(this.activeCamera);
  28466. }
  28467. // Render
  28468. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28469. this._renderingManager.render(null, null, true, true);
  28470. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28471. // After Camera Draw
  28472. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28473. var step = _g[_f];
  28474. step.action(this.activeCamera);
  28475. }
  28476. // Finalize frame
  28477. if (this.postProcessManager) {
  28478. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28479. }
  28480. // Reset some special arrays
  28481. this._renderTargets.reset();
  28482. this._alternateRendering = false;
  28483. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28484. };
  28485. Scene.prototype._processSubCameras = function (camera) {
  28486. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28487. this._renderForCamera(camera);
  28488. return;
  28489. }
  28490. // rig cameras
  28491. for (var index = 0; index < camera._rigCameras.length; index++) {
  28492. this._renderForCamera(camera._rigCameras[index], camera);
  28493. }
  28494. this.activeCamera = camera;
  28495. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28496. };
  28497. Scene.prototype._checkIntersections = function () {
  28498. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28499. var sourceMesh = this._meshesForIntersections.data[index];
  28500. if (!sourceMesh.actionManager) {
  28501. continue;
  28502. }
  28503. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28504. var action = sourceMesh.actionManager.actions[actionIndex];
  28505. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28506. var parameters = action.getTriggerParameter();
  28507. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28508. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28509. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28510. if (areIntersecting && currentIntersectionInProgress === -1) {
  28511. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28512. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28513. sourceMesh._intersectionsInProgress.push(otherMesh);
  28514. }
  28515. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28516. sourceMesh._intersectionsInProgress.push(otherMesh);
  28517. }
  28518. }
  28519. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28520. //They intersected, and now they don't.
  28521. //is this trigger an exit trigger? execute an event.
  28522. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28523. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28524. }
  28525. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28526. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28527. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28528. return otherMesh === parameterMesh;
  28529. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28530. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28531. }
  28532. }
  28533. }
  28534. }
  28535. }
  28536. };
  28537. /** @hidden */
  28538. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28539. // Do nothing. Code will be replaced if physics engine component is referenced
  28540. };
  28541. /**
  28542. * Render the scene
  28543. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28544. */
  28545. Scene.prototype.render = function (updateCameras) {
  28546. if (updateCameras === void 0) { updateCameras = true; }
  28547. if (this.isDisposed) {
  28548. return;
  28549. }
  28550. this._frameId++;
  28551. // Register components that have been associated lately to the scene.
  28552. this._registerTransientComponents();
  28553. this._activeParticles.fetchNewFrame();
  28554. this._totalVertices.fetchNewFrame();
  28555. this._activeIndices.fetchNewFrame();
  28556. this._activeBones.fetchNewFrame();
  28557. this._meshesForIntersections.reset();
  28558. this.resetCachedMaterial();
  28559. this.onBeforeAnimationsObservable.notifyObservers(this);
  28560. // Actions
  28561. if (this.actionManager) {
  28562. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28563. }
  28564. if (this._engine.isDeterministicLockStep()) {
  28565. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28566. var defaultFPS = (60.0 / 1000.0);
  28567. var defaultFrameTime = this.getDeterministicFrameTime();
  28568. var stepsTaken = 0;
  28569. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28570. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28571. internalSteps = Math.min(internalSteps, maxSubSteps);
  28572. do {
  28573. this.onBeforeStepObservable.notifyObservers(this);
  28574. // Animations
  28575. this._animationRatio = defaultFrameTime * defaultFPS;
  28576. this._animate();
  28577. this.onAfterAnimationsObservable.notifyObservers(this);
  28578. // Physics
  28579. this._advancePhysicsEngineStep(defaultFrameTime);
  28580. this.onAfterStepObservable.notifyObservers(this);
  28581. this._currentStepId++;
  28582. stepsTaken++;
  28583. deltaTime -= defaultFrameTime;
  28584. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28585. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28586. }
  28587. else {
  28588. // Animations
  28589. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28590. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28591. this._animate();
  28592. this.onAfterAnimationsObservable.notifyObservers(this);
  28593. // Physics
  28594. this._advancePhysicsEngineStep(deltaTime);
  28595. }
  28596. // Before camera update steps
  28597. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28598. var step = _a[_i];
  28599. step.action();
  28600. }
  28601. // Update Cameras
  28602. if (updateCameras) {
  28603. if (this.activeCameras.length > 0) {
  28604. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28605. var camera = this.activeCameras[cameraIndex];
  28606. camera.update();
  28607. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28608. // rig cameras
  28609. for (var index = 0; index < camera._rigCameras.length; index++) {
  28610. camera._rigCameras[index].update();
  28611. }
  28612. }
  28613. }
  28614. }
  28615. else if (this.activeCamera) {
  28616. this.activeCamera.update();
  28617. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28618. // rig cameras
  28619. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28620. this.activeCamera._rigCameras[index].update();
  28621. }
  28622. }
  28623. }
  28624. }
  28625. // Before render
  28626. this.onBeforeRenderObservable.notifyObservers(this);
  28627. // Customs render targets
  28628. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28629. var engine = this.getEngine();
  28630. var currentActiveCamera = this.activeCamera;
  28631. if (this.renderTargetsEnabled) {
  28632. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28633. this._intermediateRendering = true;
  28634. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28635. var renderTarget = this.customRenderTargets[customIndex];
  28636. if (renderTarget._shouldRender()) {
  28637. this._renderId++;
  28638. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28639. if (!this.activeCamera)
  28640. throw new Error("Active camera not set");
  28641. // Viewport
  28642. engine.setViewport(this.activeCamera.viewport);
  28643. // Camera
  28644. this.updateTransformMatrix();
  28645. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28646. }
  28647. }
  28648. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28649. this._intermediateRendering = false;
  28650. this._renderId++;
  28651. }
  28652. // Restore back buffer
  28653. if (this.customRenderTargets.length > 0) {
  28654. engine.restoreDefaultFramebuffer();
  28655. }
  28656. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28657. this.activeCamera = currentActiveCamera;
  28658. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28659. var step = _c[_b];
  28660. step.action();
  28661. }
  28662. // Clear
  28663. if (this.autoClearDepthAndStencil || this.autoClear) {
  28664. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28665. }
  28666. // Collects render targets from external components.
  28667. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28668. var step = _e[_d];
  28669. step.action(this._renderTargets);
  28670. }
  28671. // Multi-cameras?
  28672. if (this.activeCameras.length > 0) {
  28673. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28674. if (cameraIndex > 0) {
  28675. this._engine.clear(null, false, true, true);
  28676. }
  28677. this._processSubCameras(this.activeCameras[cameraIndex]);
  28678. }
  28679. }
  28680. else {
  28681. if (!this.activeCamera) {
  28682. throw new Error("No camera defined");
  28683. }
  28684. this._processSubCameras(this.activeCamera);
  28685. }
  28686. // Intersection checks
  28687. this._checkIntersections();
  28688. // Executes the after render stage actions.
  28689. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28690. var step = _g[_f];
  28691. step.action();
  28692. }
  28693. // After render
  28694. if (this.afterRender) {
  28695. this.afterRender();
  28696. }
  28697. this.onAfterRenderObservable.notifyObservers(this);
  28698. // Cleaning
  28699. if (this._toBeDisposed.length) {
  28700. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28701. var data = this._toBeDisposed[index];
  28702. if (data) {
  28703. data.dispose();
  28704. }
  28705. }
  28706. this._toBeDisposed = [];
  28707. }
  28708. if (this.dumpNextRenderTargets) {
  28709. this.dumpNextRenderTargets = false;
  28710. }
  28711. this._activeBones.addCount(0, true);
  28712. this._activeIndices.addCount(0, true);
  28713. this._activeParticles.addCount(0, true);
  28714. };
  28715. /**
  28716. * Freeze all materials
  28717. * A frozen material will not be updatable but should be faster to render
  28718. */
  28719. Scene.prototype.freezeMaterials = function () {
  28720. for (var i = 0; i < this.materials.length; i++) {
  28721. this.materials[i].freeze();
  28722. }
  28723. };
  28724. /**
  28725. * Unfreeze all materials
  28726. * A frozen material will not be updatable but should be faster to render
  28727. */
  28728. Scene.prototype.unfreezeMaterials = function () {
  28729. for (var i = 0; i < this.materials.length; i++) {
  28730. this.materials[i].unfreeze();
  28731. }
  28732. };
  28733. /**
  28734. * Releases all held ressources
  28735. */
  28736. Scene.prototype.dispose = function () {
  28737. this.beforeRender = null;
  28738. this.afterRender = null;
  28739. this.skeletons = [];
  28740. this.morphTargetManagers = [];
  28741. this._transientComponents = [];
  28742. this._isReadyForMeshStage.clear();
  28743. this._beforeEvaluateActiveMeshStage.clear();
  28744. this._evaluateSubMeshStage.clear();
  28745. this._activeMeshStage.clear();
  28746. this._cameraDrawRenderTargetStage.clear();
  28747. this._beforeCameraDrawStage.clear();
  28748. this._beforeRenderingGroupDrawStage.clear();
  28749. this._beforeRenderingMeshStage.clear();
  28750. this._afterRenderingMeshStage.clear();
  28751. this._afterRenderingGroupDrawStage.clear();
  28752. this._afterCameraDrawStage.clear();
  28753. this._afterRenderStage.clear();
  28754. this._beforeCameraUpdateStage.clear();
  28755. this._beforeClearStage.clear();
  28756. this._gatherRenderTargetsStage.clear();
  28757. this._gatherActiveCameraRenderTargetsStage.clear();
  28758. this._pointerMoveStage.clear();
  28759. this._pointerDownStage.clear();
  28760. this._pointerUpStage.clear();
  28761. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28762. var component = _a[_i];
  28763. component.dispose();
  28764. }
  28765. this.importedMeshesFiles = new Array();
  28766. this.stopAllAnimations();
  28767. this.resetCachedMaterial();
  28768. // Smart arrays
  28769. if (this.activeCamera) {
  28770. this.activeCamera._activeMeshes.dispose();
  28771. this.activeCamera = null;
  28772. }
  28773. this._activeMeshes.dispose();
  28774. this._renderingManager.dispose();
  28775. this._processedMaterials.dispose();
  28776. this._activeParticleSystems.dispose();
  28777. this._activeSkeletons.dispose();
  28778. this._softwareSkinnedMeshes.dispose();
  28779. this._renderTargets.dispose();
  28780. this._registeredForLateAnimationBindings.dispose();
  28781. this._meshesForIntersections.dispose();
  28782. this._toBeDisposed = [];
  28783. // Abort active requests
  28784. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28785. var request = _c[_b];
  28786. request.abort();
  28787. }
  28788. // Events
  28789. this.onDisposeObservable.notifyObservers(this);
  28790. this.onDisposeObservable.clear();
  28791. this.onBeforeRenderObservable.clear();
  28792. this.onAfterRenderObservable.clear();
  28793. this.onBeforeRenderTargetsRenderObservable.clear();
  28794. this.onAfterRenderTargetsRenderObservable.clear();
  28795. this.onAfterStepObservable.clear();
  28796. this.onBeforeStepObservable.clear();
  28797. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28798. this.onAfterActiveMeshesEvaluationObservable.clear();
  28799. this.onBeforeParticlesRenderingObservable.clear();
  28800. this.onAfterParticlesRenderingObservable.clear();
  28801. this.onBeforeDrawPhaseObservable.clear();
  28802. this.onAfterDrawPhaseObservable.clear();
  28803. this.onBeforeAnimationsObservable.clear();
  28804. this.onAfterAnimationsObservable.clear();
  28805. this.onDataLoadedObservable.clear();
  28806. this.onBeforeRenderingGroupObservable.clear();
  28807. this.onAfterRenderingGroupObservable.clear();
  28808. this.onMeshImportedObservable.clear();
  28809. this.onBeforeCameraRenderObservable.clear();
  28810. this.onAfterCameraRenderObservable.clear();
  28811. this.onReadyObservable.clear();
  28812. this.onNewCameraAddedObservable.clear();
  28813. this.onCameraRemovedObservable.clear();
  28814. this.onNewLightAddedObservable.clear();
  28815. this.onLightRemovedObservable.clear();
  28816. this.onNewGeometryAddedObservable.clear();
  28817. this.onGeometryRemovedObservable.clear();
  28818. this.onNewTransformNodeAddedObservable.clear();
  28819. this.onTransformNodeRemovedObservable.clear();
  28820. this.onNewMeshAddedObservable.clear();
  28821. this.onMeshRemovedObservable.clear();
  28822. this.onNewMaterialAddedObservable.clear();
  28823. this.onMaterialRemovedObservable.clear();
  28824. this.onNewTextureAddedObservable.clear();
  28825. this.onTextureRemovedObservable.clear();
  28826. this.onPrePointerObservable.clear();
  28827. this.onPointerObservable.clear();
  28828. this.onPreKeyboardObservable.clear();
  28829. this.onKeyboardObservable.clear();
  28830. this.detachControl();
  28831. // Detach cameras
  28832. var canvas = this._engine.getRenderingCanvas();
  28833. if (canvas) {
  28834. var index;
  28835. for (index = 0; index < this.cameras.length; index++) {
  28836. this.cameras[index].detachControl(canvas);
  28837. }
  28838. }
  28839. // Release animation groups
  28840. while (this.animationGroups.length) {
  28841. this.animationGroups[0].dispose();
  28842. }
  28843. // Release lights
  28844. while (this.lights.length) {
  28845. this.lights[0].dispose();
  28846. }
  28847. // Release meshes
  28848. while (this.meshes.length) {
  28849. this.meshes[0].dispose(true);
  28850. }
  28851. while (this.transformNodes.length) {
  28852. this.removeTransformNode(this.transformNodes[0]);
  28853. }
  28854. // Release cameras
  28855. while (this.cameras.length) {
  28856. this.cameras[0].dispose();
  28857. }
  28858. // Release materials
  28859. if (this.defaultMaterial) {
  28860. this.defaultMaterial.dispose();
  28861. }
  28862. while (this.multiMaterials.length) {
  28863. this.multiMaterials[0].dispose();
  28864. }
  28865. while (this.materials.length) {
  28866. this.materials[0].dispose();
  28867. }
  28868. // Release particles
  28869. while (this.particleSystems.length) {
  28870. this.particleSystems[0].dispose();
  28871. }
  28872. // Release postProcesses
  28873. while (this.postProcesses.length) {
  28874. this.postProcesses[0].dispose();
  28875. }
  28876. // Release textures
  28877. while (this.textures.length) {
  28878. this.textures[0].dispose();
  28879. }
  28880. // Release UBO
  28881. this._sceneUbo.dispose();
  28882. if (this._alternateSceneUbo) {
  28883. this._alternateSceneUbo.dispose();
  28884. }
  28885. // Post-processes
  28886. this.postProcessManager.dispose();
  28887. // Remove from engine
  28888. index = this._engine.scenes.indexOf(this);
  28889. if (index > -1) {
  28890. this._engine.scenes.splice(index, 1);
  28891. }
  28892. this._engine.wipeCaches(true);
  28893. this._isDisposed = true;
  28894. };
  28895. Object.defineProperty(Scene.prototype, "isDisposed", {
  28896. /**
  28897. * Gets if the scene is already disposed
  28898. */
  28899. get: function () {
  28900. return this._isDisposed;
  28901. },
  28902. enumerable: true,
  28903. configurable: true
  28904. });
  28905. /**
  28906. * Call this function to reduce memory footprint of the scene.
  28907. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28908. */
  28909. Scene.prototype.clearCachedVertexData = function () {
  28910. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28911. var mesh = this.meshes[meshIndex];
  28912. var geometry = mesh.geometry;
  28913. if (geometry) {
  28914. geometry._indices = [];
  28915. for (var vbName in geometry._vertexBuffers) {
  28916. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28917. continue;
  28918. }
  28919. geometry._vertexBuffers[vbName]._buffer._data = null;
  28920. }
  28921. }
  28922. }
  28923. };
  28924. /**
  28925. * This function will remove the local cached buffer data from texture.
  28926. * It will save memory but will prevent the texture from being rebuilt
  28927. */
  28928. Scene.prototype.cleanCachedTextureBuffer = function () {
  28929. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28930. var baseTexture = _a[_i];
  28931. var buffer = baseTexture._buffer;
  28932. if (buffer) {
  28933. baseTexture._buffer = null;
  28934. }
  28935. }
  28936. };
  28937. /**
  28938. * Get the world extend vectors with an optional filter
  28939. *
  28940. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28941. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28942. */
  28943. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28944. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28945. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28946. filterPredicate = filterPredicate || (function () { return true; });
  28947. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28948. mesh.computeWorldMatrix(true);
  28949. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28950. return;
  28951. }
  28952. var boundingInfo = mesh.getBoundingInfo();
  28953. var minBox = boundingInfo.boundingBox.minimumWorld;
  28954. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28955. BABYLON.Tools.CheckExtends(minBox, min, max);
  28956. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28957. });
  28958. return {
  28959. min: min,
  28960. max: max
  28961. };
  28962. };
  28963. // Picking
  28964. /**
  28965. * Creates a ray that can be used to pick in the scene
  28966. * @param x defines the x coordinate of the origin (on-screen)
  28967. * @param y defines the y coordinate of the origin (on-screen)
  28968. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28969. * @param camera defines the camera to use for the picking
  28970. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28971. * @returns a Ray
  28972. */
  28973. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28974. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28975. var result = BABYLON.Ray.Zero();
  28976. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28977. return result;
  28978. };
  28979. /**
  28980. * Creates a ray that can be used to pick in the scene
  28981. * @param x defines the x coordinate of the origin (on-screen)
  28982. * @param y defines the y coordinate of the origin (on-screen)
  28983. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28984. * @param result defines the ray where to store the picking ray
  28985. * @param camera defines the camera to use for the picking
  28986. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28987. * @returns the current scene
  28988. */
  28989. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28990. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28991. var engine = this._engine;
  28992. if (!camera) {
  28993. if (!this.activeCamera)
  28994. throw new Error("Active camera not set");
  28995. camera = this.activeCamera;
  28996. }
  28997. var cameraViewport = camera.viewport;
  28998. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28999. // Moving coordinates to local viewport world
  29000. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29001. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29002. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29003. return this;
  29004. };
  29005. /**
  29006. * Creates a ray that can be used to pick in the scene
  29007. * @param x defines the x coordinate of the origin (on-screen)
  29008. * @param y defines the y coordinate of the origin (on-screen)
  29009. * @param camera defines the camera to use for the picking
  29010. * @returns a Ray
  29011. */
  29012. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29013. var result = BABYLON.Ray.Zero();
  29014. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29015. return result;
  29016. };
  29017. /**
  29018. * Creates a ray that can be used to pick in the scene
  29019. * @param x defines the x coordinate of the origin (on-screen)
  29020. * @param y defines the y coordinate of the origin (on-screen)
  29021. * @param result defines the ray where to store the picking ray
  29022. * @param camera defines the camera to use for the picking
  29023. * @returns the current scene
  29024. */
  29025. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29026. if (!BABYLON.PickingInfo) {
  29027. return this;
  29028. }
  29029. var engine = this._engine;
  29030. if (!camera) {
  29031. if (!this.activeCamera)
  29032. throw new Error("Active camera not set");
  29033. camera = this.activeCamera;
  29034. }
  29035. var cameraViewport = camera.viewport;
  29036. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29037. var identity = BABYLON.Matrix.Identity();
  29038. // Moving coordinates to local viewport world
  29039. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29040. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29041. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29042. return this;
  29043. };
  29044. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29045. if (!BABYLON.PickingInfo) {
  29046. return null;
  29047. }
  29048. var pickingInfo = null;
  29049. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29050. var mesh = this.meshes[meshIndex];
  29051. if (predicate) {
  29052. if (!predicate(mesh)) {
  29053. continue;
  29054. }
  29055. }
  29056. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29057. continue;
  29058. }
  29059. var world = mesh.getWorldMatrix();
  29060. var ray = rayFunction(world);
  29061. var result = mesh.intersects(ray, fastCheck);
  29062. if (!result || !result.hit)
  29063. continue;
  29064. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  29065. continue;
  29066. pickingInfo = result;
  29067. if (fastCheck) {
  29068. break;
  29069. }
  29070. }
  29071. return pickingInfo || new BABYLON.PickingInfo();
  29072. };
  29073. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29074. if (!BABYLON.PickingInfo) {
  29075. return null;
  29076. }
  29077. var pickingInfos = new Array();
  29078. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29079. var mesh = this.meshes[meshIndex];
  29080. if (predicate) {
  29081. if (!predicate(mesh)) {
  29082. continue;
  29083. }
  29084. }
  29085. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29086. continue;
  29087. }
  29088. var world = mesh.getWorldMatrix();
  29089. var ray = rayFunction(world);
  29090. var result = mesh.intersects(ray, false);
  29091. if (!result || !result.hit)
  29092. continue;
  29093. pickingInfos.push(result);
  29094. }
  29095. return pickingInfos;
  29096. };
  29097. /** Launch a ray to try to pick a mesh in the scene
  29098. * @param x position on screen
  29099. * @param y position on screen
  29100. * @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
  29101. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29102. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29103. * @returns a PickingInfo
  29104. */
  29105. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29106. var _this = this;
  29107. if (!BABYLON.PickingInfo) {
  29108. return null;
  29109. }
  29110. var result = this._internalPick(function (world) {
  29111. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29112. return _this._tempPickingRay;
  29113. }, predicate, fastCheck);
  29114. if (result) {
  29115. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29116. }
  29117. return result;
  29118. };
  29119. /** Use the given ray to pick a mesh in the scene
  29120. * @param ray The ray to use to pick meshes
  29121. * @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
  29122. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29123. * @returns a PickingInfo
  29124. */
  29125. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29126. var _this = this;
  29127. var result = this._internalPick(function (world) {
  29128. if (!_this._pickWithRayInverseMatrix) {
  29129. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29130. }
  29131. world.invertToRef(_this._pickWithRayInverseMatrix);
  29132. if (!_this._cachedRayForTransform) {
  29133. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29134. }
  29135. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29136. return _this._cachedRayForTransform;
  29137. }, predicate, fastCheck);
  29138. if (result) {
  29139. result.ray = ray;
  29140. }
  29141. return result;
  29142. };
  29143. /**
  29144. * Launch a ray to try to pick a mesh in the scene
  29145. * @param x X position on screen
  29146. * @param y Y position on screen
  29147. * @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
  29148. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29149. * @returns an array of PickingInfo
  29150. */
  29151. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29152. var _this = this;
  29153. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29154. };
  29155. /**
  29156. * Launch a ray to try to pick a mesh in the scene
  29157. * @param ray Ray to use
  29158. * @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
  29159. * @returns an array of PickingInfo
  29160. */
  29161. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29162. var _this = this;
  29163. return this._internalMultiPick(function (world) {
  29164. if (!_this._pickWithRayInverseMatrix) {
  29165. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29166. }
  29167. world.invertToRef(_this._pickWithRayInverseMatrix);
  29168. if (!_this._cachedRayForTransform) {
  29169. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29170. }
  29171. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29172. return _this._cachedRayForTransform;
  29173. }, predicate);
  29174. };
  29175. /**
  29176. * Force the value of meshUnderPointer
  29177. * @param mesh defines the mesh to use
  29178. */
  29179. Scene.prototype.setPointerOverMesh = function (mesh) {
  29180. if (this._pointerOverMesh === mesh) {
  29181. return;
  29182. }
  29183. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29184. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29185. }
  29186. this._pointerOverMesh = mesh;
  29187. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29188. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29189. }
  29190. };
  29191. /**
  29192. * Gets the mesh under the pointer
  29193. * @returns a Mesh or null if no mesh is under the pointer
  29194. */
  29195. Scene.prototype.getPointerOverMesh = function () {
  29196. return this._pointerOverMesh;
  29197. };
  29198. // Misc.
  29199. /** @hidden */
  29200. Scene.prototype._rebuildGeometries = function () {
  29201. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29202. var geometry = _a[_i];
  29203. geometry._rebuild();
  29204. }
  29205. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29206. var mesh = _c[_b];
  29207. mesh._rebuild();
  29208. }
  29209. if (this.postProcessManager) {
  29210. this.postProcessManager._rebuild();
  29211. }
  29212. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29213. var component = _e[_d];
  29214. component.rebuild();
  29215. }
  29216. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29217. var system = _g[_f];
  29218. system.rebuild();
  29219. }
  29220. };
  29221. /** @hidden */
  29222. Scene.prototype._rebuildTextures = function () {
  29223. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29224. var texture = _a[_i];
  29225. texture._rebuild();
  29226. }
  29227. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29228. };
  29229. // Tags
  29230. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29231. if (tagsQuery === undefined) {
  29232. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29233. return list;
  29234. }
  29235. var listByTags = [];
  29236. forEach = forEach || (function (item) { return; });
  29237. for (var i in list) {
  29238. var item = list[i];
  29239. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29240. listByTags.push(item);
  29241. forEach(item);
  29242. }
  29243. }
  29244. return listByTags;
  29245. };
  29246. /**
  29247. * Get a list of meshes by tags
  29248. * @param tagsQuery defines the tags query to use
  29249. * @param forEach defines a predicate used to filter results
  29250. * @returns an array of Mesh
  29251. */
  29252. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29253. return this._getByTags(this.meshes, tagsQuery, forEach);
  29254. };
  29255. /**
  29256. * Get a list of cameras by tags
  29257. * @param tagsQuery defines the tags query to use
  29258. * @param forEach defines a predicate used to filter results
  29259. * @returns an array of Camera
  29260. */
  29261. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29262. return this._getByTags(this.cameras, tagsQuery, forEach);
  29263. };
  29264. /**
  29265. * Get a list of lights by tags
  29266. * @param tagsQuery defines the tags query to use
  29267. * @param forEach defines a predicate used to filter results
  29268. * @returns an array of Light
  29269. */
  29270. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29271. return this._getByTags(this.lights, tagsQuery, forEach);
  29272. };
  29273. /**
  29274. * Get a list of materials by tags
  29275. * @param tagsQuery defines the tags query to use
  29276. * @param forEach defines a predicate used to filter results
  29277. * @returns an array of Material
  29278. */
  29279. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29280. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29281. };
  29282. /**
  29283. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29284. * This allowed control for front to back rendering or reversly depending of the special needs.
  29285. *
  29286. * @param renderingGroupId The rendering group id corresponding to its index
  29287. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29288. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29289. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29290. */
  29291. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29292. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29293. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29294. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29295. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29296. };
  29297. /**
  29298. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29299. *
  29300. * @param renderingGroupId The rendering group id corresponding to its index
  29301. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29302. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29303. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29304. */
  29305. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29306. if (depth === void 0) { depth = true; }
  29307. if (stencil === void 0) { stencil = true; }
  29308. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29309. };
  29310. /**
  29311. * Gets the current auto clear configuration for one rendering group of the rendering
  29312. * manager.
  29313. * @param index the rendering group index to get the information for
  29314. * @returns The auto clear setup for the requested rendering group
  29315. */
  29316. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29317. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29318. };
  29319. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29320. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29321. get: function () {
  29322. return this._blockMaterialDirtyMechanism;
  29323. },
  29324. set: function (value) {
  29325. if (this._blockMaterialDirtyMechanism === value) {
  29326. return;
  29327. }
  29328. this._blockMaterialDirtyMechanism = value;
  29329. if (!value) { // Do a complete update
  29330. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29331. }
  29332. },
  29333. enumerable: true,
  29334. configurable: true
  29335. });
  29336. /**
  29337. * Will flag all materials as dirty to trigger new shader compilation
  29338. * @param flag defines the flag used to specify which material part must be marked as dirty
  29339. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29340. */
  29341. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29342. if (this._blockMaterialDirtyMechanism) {
  29343. return;
  29344. }
  29345. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29346. var material = _a[_i];
  29347. if (predicate && !predicate(material)) {
  29348. continue;
  29349. }
  29350. material.markAsDirty(flag);
  29351. }
  29352. };
  29353. /** @hidden */
  29354. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29355. var _this = this;
  29356. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29357. this._activeRequests.push(request);
  29358. request.onCompleteObservable.add(function (request) {
  29359. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29360. });
  29361. return request;
  29362. };
  29363. /** @hidden */
  29364. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29365. var _this = this;
  29366. return new Promise(function (resolve, reject) {
  29367. _this._loadFile(url, function (data) {
  29368. resolve(data);
  29369. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29370. reject(exception);
  29371. });
  29372. });
  29373. };
  29374. // Statics
  29375. Scene._uniqueIdCounter = 0;
  29376. /** The fog is deactivated */
  29377. Scene.FOGMODE_NONE = 0;
  29378. /** The fog density is following an exponential function */
  29379. Scene.FOGMODE_EXP = 1;
  29380. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29381. Scene.FOGMODE_EXP2 = 2;
  29382. /** The fog density is following a linear function. */
  29383. Scene.FOGMODE_LINEAR = 3;
  29384. /**
  29385. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29386. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29387. */
  29388. Scene.MinDeltaTime = 1.0;
  29389. /**
  29390. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29391. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29392. */
  29393. Scene.MaxDeltaTime = 1000.0;
  29394. /** The distance in pixel that you have to move to prevent some events */
  29395. Scene.DragMovementThreshold = 10; // in pixels
  29396. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29397. Scene.LongPressDelay = 500; // in milliseconds
  29398. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29399. Scene.DoubleClickDelay = 300; // in milliseconds
  29400. /** If you need to check double click without raising a single click at first click, enable this flag */
  29401. Scene.ExclusiveDoubleClickMode = false;
  29402. return Scene;
  29403. }(BABYLON.AbstractScene));
  29404. BABYLON.Scene = Scene;
  29405. })(BABYLON || (BABYLON = {}));
  29406. //# sourceMappingURL=babylon.scene.js.map
  29407. var BABYLON;
  29408. (function (BABYLON) {
  29409. /**
  29410. * Set of assets to keep when moving a scene into an asset container.
  29411. */
  29412. var KeepAssets = /** @class */ (function (_super) {
  29413. __extends(KeepAssets, _super);
  29414. function KeepAssets() {
  29415. return _super !== null && _super.apply(this, arguments) || this;
  29416. }
  29417. return KeepAssets;
  29418. }(BABYLON.AbstractScene));
  29419. BABYLON.KeepAssets = KeepAssets;
  29420. /**
  29421. * Container with a set of assets that can be added or removed from a scene.
  29422. */
  29423. var AssetContainer = /** @class */ (function (_super) {
  29424. __extends(AssetContainer, _super);
  29425. /**
  29426. * Instantiates an AssetContainer.
  29427. * @param scene The scene the AssetContainer belongs to.
  29428. */
  29429. function AssetContainer(scene) {
  29430. var _this = _super.call(this) || this;
  29431. _this.scene = scene;
  29432. return _this;
  29433. }
  29434. /**
  29435. * Adds all the assets from the container to the scene.
  29436. */
  29437. AssetContainer.prototype.addAllToScene = function () {
  29438. var _this = this;
  29439. this.cameras.forEach(function (o) {
  29440. _this.scene.addCamera(o);
  29441. });
  29442. this.lights.forEach(function (o) {
  29443. _this.scene.addLight(o);
  29444. });
  29445. this.meshes.forEach(function (o) {
  29446. _this.scene.addMesh(o);
  29447. });
  29448. this.skeletons.forEach(function (o) {
  29449. _this.scene.addSkeleton(o);
  29450. });
  29451. this.animations.forEach(function (o) {
  29452. _this.scene.addAnimation(o);
  29453. });
  29454. this.animationGroups.forEach(function (o) {
  29455. _this.scene.addAnimationGroup(o);
  29456. });
  29457. this.multiMaterials.forEach(function (o) {
  29458. _this.scene.addMultiMaterial(o);
  29459. });
  29460. this.materials.forEach(function (o) {
  29461. _this.scene.addMaterial(o);
  29462. });
  29463. this.morphTargetManagers.forEach(function (o) {
  29464. _this.scene.addMorphTargetManager(o);
  29465. });
  29466. this.geometries.forEach(function (o) {
  29467. _this.scene.addGeometry(o);
  29468. });
  29469. this.transformNodes.forEach(function (o) {
  29470. _this.scene.addTransformNode(o);
  29471. });
  29472. this.actionManagers.forEach(function (o) {
  29473. _this.scene.addActionManager(o);
  29474. });
  29475. this.textures.forEach(function (o) {
  29476. _this.scene.addTexture(o);
  29477. });
  29478. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29479. var component = _a[_i];
  29480. component.addFromContainer(this.scene);
  29481. }
  29482. };
  29483. /**
  29484. * Removes all the assets in the container from the scene
  29485. */
  29486. AssetContainer.prototype.removeAllFromScene = function () {
  29487. var _this = this;
  29488. this.cameras.forEach(function (o) {
  29489. _this.scene.removeCamera(o);
  29490. });
  29491. this.lights.forEach(function (o) {
  29492. _this.scene.removeLight(o);
  29493. });
  29494. this.meshes.forEach(function (o) {
  29495. _this.scene.removeMesh(o);
  29496. });
  29497. this.skeletons.forEach(function (o) {
  29498. _this.scene.removeSkeleton(o);
  29499. });
  29500. this.animations.forEach(function (o) {
  29501. _this.scene.removeAnimation(o);
  29502. });
  29503. this.animationGroups.forEach(function (o) {
  29504. _this.scene.removeAnimationGroup(o);
  29505. });
  29506. this.multiMaterials.forEach(function (o) {
  29507. _this.scene.removeMultiMaterial(o);
  29508. });
  29509. this.materials.forEach(function (o) {
  29510. _this.scene.removeMaterial(o);
  29511. });
  29512. this.morphTargetManagers.forEach(function (o) {
  29513. _this.scene.removeMorphTargetManager(o);
  29514. });
  29515. this.geometries.forEach(function (o) {
  29516. _this.scene.removeGeometry(o);
  29517. });
  29518. this.transformNodes.forEach(function (o) {
  29519. _this.scene.removeTransformNode(o);
  29520. });
  29521. this.actionManagers.forEach(function (o) {
  29522. _this.scene.removeActionManager(o);
  29523. });
  29524. this.textures.forEach(function (o) {
  29525. _this.scene.removeTexture(o);
  29526. });
  29527. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29528. var component = _a[_i];
  29529. component.removeFromContainer(this.scene);
  29530. }
  29531. };
  29532. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29533. if (!sourceAssets) {
  29534. return;
  29535. }
  29536. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29537. var asset = sourceAssets_1[_i];
  29538. var move = true;
  29539. if (keepAssets) {
  29540. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29541. var keepAsset = keepAssets_1[_a];
  29542. if (asset === keepAsset) {
  29543. move = false;
  29544. break;
  29545. }
  29546. }
  29547. }
  29548. if (move) {
  29549. targetAssets.push(asset);
  29550. }
  29551. }
  29552. };
  29553. /**
  29554. * Removes all the assets contained in the scene and adds them to the container.
  29555. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29556. */
  29557. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29558. if (keepAssets === undefined) {
  29559. keepAssets = new KeepAssets();
  29560. }
  29561. for (var key in this) {
  29562. if (this.hasOwnProperty(key)) {
  29563. this[key] = this[key] || [];
  29564. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29565. }
  29566. }
  29567. this.removeAllFromScene();
  29568. };
  29569. /**
  29570. * 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.
  29571. * @returns the root mesh
  29572. */
  29573. AssetContainer.prototype.createRootMesh = function () {
  29574. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29575. this.meshes.forEach(function (m) {
  29576. if (!m.parent) {
  29577. rootMesh.addChild(m);
  29578. }
  29579. });
  29580. this.meshes.unshift(rootMesh);
  29581. return rootMesh;
  29582. };
  29583. return AssetContainer;
  29584. }(BABYLON.AbstractScene));
  29585. BABYLON.AssetContainer = AssetContainer;
  29586. })(BABYLON || (BABYLON = {}));
  29587. //# sourceMappingURL=babylon.assetContainer.js.map
  29588. var BABYLON;
  29589. (function (BABYLON) {
  29590. /**
  29591. * Class used to store data that will be store in GPU memory
  29592. */
  29593. var Buffer = /** @class */ (function () {
  29594. /**
  29595. * Constructor
  29596. * @param engine the engine
  29597. * @param data the data to use for this buffer
  29598. * @param updatable whether the data is updatable
  29599. * @param stride the stride (optional)
  29600. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29601. * @param instanced whether the buffer is instanced (optional)
  29602. * @param useBytes set to true if the stride in in bytes (optional)
  29603. */
  29604. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29605. if (stride === void 0) { stride = 0; }
  29606. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29607. if (instanced === void 0) { instanced = false; }
  29608. if (useBytes === void 0) { useBytes = false; }
  29609. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29610. this._engine = engine.getScene().getEngine();
  29611. }
  29612. else {
  29613. this._engine = engine;
  29614. }
  29615. this._updatable = updatable;
  29616. this._instanced = instanced;
  29617. this._data = data;
  29618. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29619. if (!postponeInternalCreation) { // by default
  29620. this.create();
  29621. }
  29622. }
  29623. /**
  29624. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29625. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29626. * @param offset defines offset in the buffer (0 by default)
  29627. * @param size defines the size in floats of attributes (position is 3 for instance)
  29628. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29629. * @param instanced defines if the vertex buffer contains indexed data
  29630. * @param useBytes defines if the offset and stride are in bytes
  29631. * @returns the new vertex buffer
  29632. */
  29633. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29634. if (useBytes === void 0) { useBytes = false; }
  29635. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29636. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29637. // a lot of these parameters are ignored as they are overriden by the buffer
  29638. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29639. };
  29640. // Properties
  29641. /**
  29642. * Gets a boolean indicating if the Buffer is updatable?
  29643. * @returns true if the buffer is updatable
  29644. */
  29645. Buffer.prototype.isUpdatable = function () {
  29646. return this._updatable;
  29647. };
  29648. /**
  29649. * Gets current buffer's data
  29650. * @returns a DataArray or null
  29651. */
  29652. Buffer.prototype.getData = function () {
  29653. return this._data;
  29654. };
  29655. /**
  29656. * Gets underlying native buffer
  29657. * @returns underlying native buffer
  29658. */
  29659. Buffer.prototype.getBuffer = function () {
  29660. return this._buffer;
  29661. };
  29662. /**
  29663. * Gets the stride in float32 units (i.e. byte stride / 4).
  29664. * May not be an integer if the byte stride is not divisible by 4.
  29665. * DEPRECATED. Use byteStride instead.
  29666. * @returns the stride in float32 units
  29667. */
  29668. Buffer.prototype.getStrideSize = function () {
  29669. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29670. };
  29671. // Methods
  29672. /**
  29673. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29674. * @param data defines the data to store
  29675. */
  29676. Buffer.prototype.create = function (data) {
  29677. if (data === void 0) { data = null; }
  29678. if (!data && this._buffer) {
  29679. return; // nothing to do
  29680. }
  29681. data = data || this._data;
  29682. if (!data) {
  29683. return;
  29684. }
  29685. if (!this._buffer) { // create buffer
  29686. if (this._updatable) {
  29687. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29688. this._data = data;
  29689. }
  29690. else {
  29691. this._buffer = this._engine.createVertexBuffer(data);
  29692. }
  29693. }
  29694. else if (this._updatable) { // update buffer
  29695. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29696. this._data = data;
  29697. }
  29698. };
  29699. /** @hidden */
  29700. Buffer.prototype._rebuild = function () {
  29701. this._buffer = null;
  29702. this.create(this._data);
  29703. };
  29704. /**
  29705. * Update current buffer data
  29706. * @param data defines the data to store
  29707. */
  29708. Buffer.prototype.update = function (data) {
  29709. this.create(data);
  29710. };
  29711. /**
  29712. * Updates the data directly.
  29713. * @param data the new data
  29714. * @param offset the new offset
  29715. * @param vertexCount the vertex count (optional)
  29716. * @param useBytes set to true if the offset is in bytes
  29717. */
  29718. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29719. if (useBytes === void 0) { useBytes = false; }
  29720. if (!this._buffer) {
  29721. return;
  29722. }
  29723. if (this._updatable) { // update buffer
  29724. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29725. this._data = null;
  29726. }
  29727. };
  29728. /**
  29729. * Release all resources
  29730. */
  29731. Buffer.prototype.dispose = function () {
  29732. if (!this._buffer) {
  29733. return;
  29734. }
  29735. if (this._engine._releaseBuffer(this._buffer)) {
  29736. this._buffer = null;
  29737. }
  29738. };
  29739. return Buffer;
  29740. }());
  29741. BABYLON.Buffer = Buffer;
  29742. })(BABYLON || (BABYLON = {}));
  29743. //# sourceMappingURL=babylon.buffer.js.map
  29744. var BABYLON;
  29745. (function (BABYLON) {
  29746. /**
  29747. * Specialized buffer used to store vertex data
  29748. */
  29749. var VertexBuffer = /** @class */ (function () {
  29750. /**
  29751. * Constructor
  29752. * @param engine the engine
  29753. * @param data the data to use for this vertex buffer
  29754. * @param kind the vertex buffer kind
  29755. * @param updatable whether the data is updatable
  29756. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29757. * @param stride the stride (optional)
  29758. * @param instanced whether the buffer is instanced (optional)
  29759. * @param offset the offset of the data (optional)
  29760. * @param size the number of components (optional)
  29761. * @param type the type of the component (optional)
  29762. * @param normalized whether the data contains normalized data (optional)
  29763. * @param useBytes set to true if stride and offset are in bytes (optional)
  29764. */
  29765. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29766. if (normalized === void 0) { normalized = false; }
  29767. if (useBytes === void 0) { useBytes = false; }
  29768. if (data instanceof BABYLON.Buffer) {
  29769. this._buffer = data;
  29770. this._ownsBuffer = false;
  29771. }
  29772. else {
  29773. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29774. this._ownsBuffer = true;
  29775. }
  29776. this._kind = kind;
  29777. if (type == undefined) {
  29778. var data_1 = this.getData();
  29779. this.type = VertexBuffer.FLOAT;
  29780. if (data_1 instanceof Int8Array)
  29781. this.type = VertexBuffer.BYTE;
  29782. else if (data_1 instanceof Uint8Array)
  29783. this.type = VertexBuffer.UNSIGNED_BYTE;
  29784. else if (data_1 instanceof Int16Array)
  29785. this.type = VertexBuffer.SHORT;
  29786. else if (data_1 instanceof Uint16Array)
  29787. this.type = VertexBuffer.UNSIGNED_SHORT;
  29788. else if (data_1 instanceof Int32Array)
  29789. this.type = VertexBuffer.INT;
  29790. else if (data_1 instanceof Uint32Array)
  29791. this.type = VertexBuffer.UNSIGNED_INT;
  29792. }
  29793. else {
  29794. this.type = type;
  29795. }
  29796. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29797. if (useBytes) {
  29798. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29799. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29800. this.byteOffset = offset || 0;
  29801. }
  29802. else {
  29803. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29804. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29805. this.byteOffset = (offset || 0) * typeByteLength;
  29806. }
  29807. this.normalized = normalized;
  29808. this._instanced = instanced !== undefined ? instanced : false;
  29809. this._instanceDivisor = instanced ? 1 : 0;
  29810. }
  29811. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29812. /**
  29813. * Gets or sets the instance divisor when in instanced mode
  29814. */
  29815. get: function () {
  29816. return this._instanceDivisor;
  29817. },
  29818. set: function (value) {
  29819. this._instanceDivisor = value;
  29820. if (value == 0) {
  29821. this._instanced = false;
  29822. }
  29823. else {
  29824. this._instanced = true;
  29825. }
  29826. },
  29827. enumerable: true,
  29828. configurable: true
  29829. });
  29830. /** @hidden */
  29831. VertexBuffer.prototype._rebuild = function () {
  29832. if (!this._buffer) {
  29833. return;
  29834. }
  29835. this._buffer._rebuild();
  29836. };
  29837. /**
  29838. * Returns the kind of the VertexBuffer (string)
  29839. * @returns a string
  29840. */
  29841. VertexBuffer.prototype.getKind = function () {
  29842. return this._kind;
  29843. };
  29844. // Properties
  29845. /**
  29846. * Gets a boolean indicating if the VertexBuffer is updatable?
  29847. * @returns true if the buffer is updatable
  29848. */
  29849. VertexBuffer.prototype.isUpdatable = function () {
  29850. return this._buffer.isUpdatable();
  29851. };
  29852. /**
  29853. * Gets current buffer's data
  29854. * @returns a DataArray or null
  29855. */
  29856. VertexBuffer.prototype.getData = function () {
  29857. return this._buffer.getData();
  29858. };
  29859. /**
  29860. * Gets underlying native buffer
  29861. * @returns underlying native buffer
  29862. */
  29863. VertexBuffer.prototype.getBuffer = function () {
  29864. return this._buffer.getBuffer();
  29865. };
  29866. /**
  29867. * Gets the stride in float32 units (i.e. byte stride / 4).
  29868. * May not be an integer if the byte stride is not divisible by 4.
  29869. * DEPRECATED. Use byteStride instead.
  29870. * @returns the stride in float32 units
  29871. */
  29872. VertexBuffer.prototype.getStrideSize = function () {
  29873. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29874. };
  29875. /**
  29876. * Returns the offset as a multiple of the type byte length.
  29877. * DEPRECATED. Use byteOffset instead.
  29878. * @returns the offset in bytes
  29879. */
  29880. VertexBuffer.prototype.getOffset = function () {
  29881. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29882. };
  29883. /**
  29884. * Returns the number of components per vertex attribute (integer)
  29885. * @returns the size in float
  29886. */
  29887. VertexBuffer.prototype.getSize = function () {
  29888. return this._size;
  29889. };
  29890. /**
  29891. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  29892. * @returns true if this buffer is instanced
  29893. */
  29894. VertexBuffer.prototype.getIsInstanced = function () {
  29895. return this._instanced;
  29896. };
  29897. /**
  29898. * Returns the instancing divisor, zero for non-instanced (integer).
  29899. * @returns a number
  29900. */
  29901. VertexBuffer.prototype.getInstanceDivisor = function () {
  29902. return this._instanceDivisor;
  29903. };
  29904. // Methods
  29905. /**
  29906. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29907. * @param data defines the data to store
  29908. */
  29909. VertexBuffer.prototype.create = function (data) {
  29910. this._buffer.create(data);
  29911. };
  29912. /**
  29913. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  29914. * This function will create a new buffer if the current one is not updatable
  29915. * @param data defines the data to store
  29916. */
  29917. VertexBuffer.prototype.update = function (data) {
  29918. this._buffer.update(data);
  29919. };
  29920. /**
  29921. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29922. * Returns the directly updated WebGLBuffer.
  29923. * @param data the new data
  29924. * @param offset the new offset
  29925. * @param useBytes set to true if the offset is in bytes
  29926. */
  29927. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29928. if (useBytes === void 0) { useBytes = false; }
  29929. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29930. };
  29931. /**
  29932. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29933. */
  29934. VertexBuffer.prototype.dispose = function () {
  29935. if (this._ownsBuffer) {
  29936. this._buffer.dispose();
  29937. }
  29938. };
  29939. /**
  29940. * Enumerates each value of this vertex buffer as numbers.
  29941. * @param count the number of values to enumerate
  29942. * @param callback the callback function called for each value
  29943. */
  29944. VertexBuffer.prototype.forEach = function (count, callback) {
  29945. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29946. };
  29947. /**
  29948. * Deduces the stride given a kind.
  29949. * @param kind The kind string to deduce
  29950. * @returns The deduced stride
  29951. */
  29952. VertexBuffer.DeduceStride = function (kind) {
  29953. switch (kind) {
  29954. case VertexBuffer.UVKind:
  29955. case VertexBuffer.UV2Kind:
  29956. case VertexBuffer.UV3Kind:
  29957. case VertexBuffer.UV4Kind:
  29958. case VertexBuffer.UV5Kind:
  29959. case VertexBuffer.UV6Kind:
  29960. return 2;
  29961. case VertexBuffer.NormalKind:
  29962. case VertexBuffer.PositionKind:
  29963. return 3;
  29964. case VertexBuffer.ColorKind:
  29965. case VertexBuffer.MatricesIndicesKind:
  29966. case VertexBuffer.MatricesIndicesExtraKind:
  29967. case VertexBuffer.MatricesWeightsKind:
  29968. case VertexBuffer.MatricesWeightsExtraKind:
  29969. case VertexBuffer.TangentKind:
  29970. return 4;
  29971. default:
  29972. throw new Error("Invalid kind '" + kind + "'");
  29973. }
  29974. };
  29975. /**
  29976. * Gets the byte length of the given type.
  29977. * @param type the type
  29978. * @returns the number of bytes
  29979. */
  29980. VertexBuffer.GetTypeByteLength = function (type) {
  29981. switch (type) {
  29982. case VertexBuffer.BYTE:
  29983. case VertexBuffer.UNSIGNED_BYTE:
  29984. return 1;
  29985. case VertexBuffer.SHORT:
  29986. case VertexBuffer.UNSIGNED_SHORT:
  29987. return 2;
  29988. case VertexBuffer.INT:
  29989. case VertexBuffer.FLOAT:
  29990. return 4;
  29991. default:
  29992. throw new Error("Invalid type '" + type + "'");
  29993. }
  29994. };
  29995. /**
  29996. * Enumerates each value of the given parameters as numbers.
  29997. * @param data the data to enumerate
  29998. * @param byteOffset the byte offset of the data
  29999. * @param byteStride the byte stride of the data
  30000. * @param componentCount the number of components per element
  30001. * @param componentType the type of the component
  30002. * @param count the total number of components
  30003. * @param normalized whether the data is normalized
  30004. * @param callback the callback function called for each value
  30005. */
  30006. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30007. if (data instanceof Array) {
  30008. var offset = byteOffset / 4;
  30009. var stride = byteStride / 4;
  30010. for (var index = 0; index < count; index += componentCount) {
  30011. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30012. callback(data[offset + componentIndex], index + componentIndex);
  30013. }
  30014. offset += stride;
  30015. }
  30016. }
  30017. else {
  30018. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30019. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30020. for (var index = 0; index < count; index += componentCount) {
  30021. var componentByteOffset = byteOffset;
  30022. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30023. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30024. callback(value, index + componentIndex);
  30025. componentByteOffset += componentByteLength;
  30026. }
  30027. byteOffset += byteStride;
  30028. }
  30029. }
  30030. };
  30031. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30032. switch (type) {
  30033. case VertexBuffer.BYTE: {
  30034. var value = dataView.getInt8(byteOffset);
  30035. if (normalized) {
  30036. value = Math.max(value / 127, -1);
  30037. }
  30038. return value;
  30039. }
  30040. case VertexBuffer.UNSIGNED_BYTE: {
  30041. var value = dataView.getUint8(byteOffset);
  30042. if (normalized) {
  30043. value = value / 255;
  30044. }
  30045. return value;
  30046. }
  30047. case VertexBuffer.SHORT: {
  30048. var value = dataView.getInt16(byteOffset, true);
  30049. if (normalized) {
  30050. value = Math.max(value / 16383, -1);
  30051. }
  30052. return value;
  30053. }
  30054. case VertexBuffer.UNSIGNED_SHORT: {
  30055. var value = dataView.getUint16(byteOffset, true);
  30056. if (normalized) {
  30057. value = value / 65535;
  30058. }
  30059. return value;
  30060. }
  30061. case VertexBuffer.FLOAT: {
  30062. return dataView.getFloat32(byteOffset, true);
  30063. }
  30064. default: {
  30065. throw new Error("Invalid component type " + type);
  30066. }
  30067. }
  30068. };
  30069. /**
  30070. * The byte type.
  30071. */
  30072. VertexBuffer.BYTE = 5120;
  30073. /**
  30074. * The unsigned byte type.
  30075. */
  30076. VertexBuffer.UNSIGNED_BYTE = 5121;
  30077. /**
  30078. * The short type.
  30079. */
  30080. VertexBuffer.SHORT = 5122;
  30081. /**
  30082. * The unsigned short type.
  30083. */
  30084. VertexBuffer.UNSIGNED_SHORT = 5123;
  30085. /**
  30086. * The integer type.
  30087. */
  30088. VertexBuffer.INT = 5124;
  30089. /**
  30090. * The unsigned integer type.
  30091. */
  30092. VertexBuffer.UNSIGNED_INT = 5125;
  30093. /**
  30094. * The float type.
  30095. */
  30096. VertexBuffer.FLOAT = 5126;
  30097. // Enums
  30098. /**
  30099. * Positions
  30100. */
  30101. VertexBuffer.PositionKind = "position";
  30102. /**
  30103. * Normals
  30104. */
  30105. VertexBuffer.NormalKind = "normal";
  30106. /**
  30107. * Tangents
  30108. */
  30109. VertexBuffer.TangentKind = "tangent";
  30110. /**
  30111. * Texture coordinates
  30112. */
  30113. VertexBuffer.UVKind = "uv";
  30114. /**
  30115. * Texture coordinates 2
  30116. */
  30117. VertexBuffer.UV2Kind = "uv2";
  30118. /**
  30119. * Texture coordinates 3
  30120. */
  30121. VertexBuffer.UV3Kind = "uv3";
  30122. /**
  30123. * Texture coordinates 4
  30124. */
  30125. VertexBuffer.UV4Kind = "uv4";
  30126. /**
  30127. * Texture coordinates 5
  30128. */
  30129. VertexBuffer.UV5Kind = "uv5";
  30130. /**
  30131. * Texture coordinates 6
  30132. */
  30133. VertexBuffer.UV6Kind = "uv6";
  30134. /**
  30135. * Colors
  30136. */
  30137. VertexBuffer.ColorKind = "color";
  30138. /**
  30139. * Matrix indices (for bones)
  30140. */
  30141. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30142. /**
  30143. * Matrix weights (for bones)
  30144. */
  30145. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30146. /**
  30147. * Additional matrix indices (for bones)
  30148. */
  30149. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30150. /**
  30151. * Additional matrix weights (for bones)
  30152. */
  30153. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30154. return VertexBuffer;
  30155. }());
  30156. BABYLON.VertexBuffer = VertexBuffer;
  30157. })(BABYLON || (BABYLON = {}));
  30158. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30159. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30160. var BABYLON;
  30161. (function (BABYLON) {
  30162. /**
  30163. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30164. */
  30165. var DummyInternalTextureTracker = /** @class */ (function () {
  30166. function DummyInternalTextureTracker() {
  30167. /**
  30168. * Gets or set the previous tracker in the list
  30169. */
  30170. this.previous = null;
  30171. /**
  30172. * Gets or set the next tracker in the list
  30173. */
  30174. this.next = null;
  30175. }
  30176. return DummyInternalTextureTracker;
  30177. }());
  30178. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30179. })(BABYLON || (BABYLON = {}));
  30180. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30181. var BABYLON;
  30182. (function (BABYLON) {
  30183. /**
  30184. * Class used to store data associated with WebGL texture data for the engine
  30185. * This class should not be used directly
  30186. */
  30187. var InternalTexture = /** @class */ (function () {
  30188. /**
  30189. * Creates a new InternalTexture
  30190. * @param engine defines the engine to use
  30191. * @param dataSource defines the type of data that will be used
  30192. */
  30193. function InternalTexture(engine, dataSource) {
  30194. /**
  30195. * Observable called when the texture is loaded
  30196. */
  30197. this.onLoadedObservable = new BABYLON.Observable();
  30198. /**
  30199. * Gets or set the previous tracker in the list
  30200. */
  30201. this.previous = null;
  30202. /**
  30203. * Gets or set the next tracker in the list
  30204. */
  30205. this.next = null;
  30206. // Private
  30207. /** @hidden */
  30208. this._initialSlot = -1;
  30209. /** @hidden */
  30210. this._designatedSlot = -1;
  30211. /** @hidden */
  30212. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30213. /** @hidden */
  30214. this._comparisonFunction = 0;
  30215. /** @hidden */
  30216. this._sphericalPolynomial = null;
  30217. /** @hidden */
  30218. this._lodGenerationScale = 0;
  30219. /** @hidden */
  30220. this._lodGenerationOffset = 0;
  30221. /** @hidden */
  30222. this._isRGBD = false;
  30223. /** @hidden */
  30224. this._references = 1;
  30225. this._engine = engine;
  30226. this._dataSource = dataSource;
  30227. this._webGLTexture = engine._createTexture();
  30228. }
  30229. /**
  30230. * Gets the Engine the texture belongs to.
  30231. * @returns The babylon engine
  30232. */
  30233. InternalTexture.prototype.getEngine = function () {
  30234. return this._engine;
  30235. };
  30236. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30237. /**
  30238. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30239. */
  30240. get: function () {
  30241. return this._dataSource;
  30242. },
  30243. enumerable: true,
  30244. configurable: true
  30245. });
  30246. /**
  30247. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30248. */
  30249. InternalTexture.prototype.incrementReferences = function () {
  30250. this._references++;
  30251. };
  30252. /**
  30253. * Change the size of the texture (not the size of the content)
  30254. * @param width defines the new width
  30255. * @param height defines the new height
  30256. * @param depth defines the new depth (1 by default)
  30257. */
  30258. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30259. if (depth === void 0) { depth = 1; }
  30260. this.width = width;
  30261. this.height = height;
  30262. this.depth = depth;
  30263. this.baseWidth = width;
  30264. this.baseHeight = height;
  30265. this.baseDepth = depth;
  30266. this._size = width * height * depth;
  30267. };
  30268. /** @hidden */
  30269. InternalTexture.prototype._rebuild = function () {
  30270. var _this = this;
  30271. var proxy;
  30272. this.isReady = false;
  30273. this._cachedCoordinatesMode = null;
  30274. this._cachedWrapU = null;
  30275. this._cachedWrapV = null;
  30276. this._cachedAnisotropicFilteringLevel = null;
  30277. switch (this._dataSource) {
  30278. case InternalTexture.DATASOURCE_TEMP:
  30279. return;
  30280. case InternalTexture.DATASOURCE_URL:
  30281. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30282. _this.isReady = true;
  30283. }, null, this._buffer, undefined, this.format);
  30284. proxy._swapAndDie(this);
  30285. return;
  30286. case InternalTexture.DATASOURCE_RAW:
  30287. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30288. proxy._swapAndDie(this);
  30289. this.isReady = true;
  30290. return;
  30291. case InternalTexture.DATASOURCE_RAW3D:
  30292. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30293. proxy._swapAndDie(this);
  30294. this.isReady = true;
  30295. return;
  30296. case InternalTexture.DATASOURCE_DYNAMIC:
  30297. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30298. proxy._swapAndDie(this);
  30299. // The engine will make sure to update content so no need to flag it as isReady = true
  30300. return;
  30301. case InternalTexture.DATASOURCE_RENDERTARGET:
  30302. var options = new BABYLON.RenderTargetCreationOptions();
  30303. options.generateDepthBuffer = this._generateDepthBuffer;
  30304. options.generateMipMaps = this.generateMipMaps;
  30305. options.generateStencilBuffer = this._generateStencilBuffer;
  30306. options.samplingMode = this.samplingMode;
  30307. options.type = this.type;
  30308. if (this.isCube) {
  30309. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30310. }
  30311. else {
  30312. var size = {
  30313. width: this.width,
  30314. height: this.height
  30315. };
  30316. proxy = this._engine.createRenderTargetTexture(size, options);
  30317. }
  30318. proxy._swapAndDie(this);
  30319. this.isReady = true;
  30320. return;
  30321. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30322. var depthTextureOptions = {
  30323. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30324. comparisonFunction: this._comparisonFunction,
  30325. generateStencil: this._generateStencilBuffer,
  30326. isCube: this.isCube
  30327. };
  30328. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30329. proxy._swapAndDie(this);
  30330. this.isReady = true;
  30331. return;
  30332. case InternalTexture.DATASOURCE_CUBE:
  30333. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30334. _this.isReady = true;
  30335. }, null, this.format, this._extension);
  30336. proxy._swapAndDie(this);
  30337. return;
  30338. case InternalTexture.DATASOURCE_CUBERAW:
  30339. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30340. proxy._swapAndDie(this);
  30341. this.isReady = true;
  30342. return;
  30343. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30344. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30345. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30346. _this.isReady = true;
  30347. });
  30348. proxy._swapAndDie(this);
  30349. return;
  30350. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30351. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30352. if (proxy) {
  30353. proxy._swapAndDie(_this);
  30354. }
  30355. _this.isReady = true;
  30356. }, null, this.format, this._extension);
  30357. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30358. return;
  30359. }
  30360. };
  30361. /** @hidden */
  30362. InternalTexture.prototype._swapAndDie = function (target) {
  30363. target._webGLTexture = this._webGLTexture;
  30364. if (this._framebuffer) {
  30365. target._framebuffer = this._framebuffer;
  30366. }
  30367. if (this._depthStencilBuffer) {
  30368. target._depthStencilBuffer = this._depthStencilBuffer;
  30369. }
  30370. if (this._lodTextureHigh) {
  30371. if (target._lodTextureHigh) {
  30372. target._lodTextureHigh.dispose();
  30373. }
  30374. target._lodTextureHigh = this._lodTextureHigh;
  30375. }
  30376. if (this._lodTextureMid) {
  30377. if (target._lodTextureMid) {
  30378. target._lodTextureMid.dispose();
  30379. }
  30380. target._lodTextureMid = this._lodTextureMid;
  30381. }
  30382. if (this._lodTextureLow) {
  30383. if (target._lodTextureLow) {
  30384. target._lodTextureLow.dispose();
  30385. }
  30386. target._lodTextureLow = this._lodTextureLow;
  30387. }
  30388. var cache = this._engine.getLoadedTexturesCache();
  30389. var index = cache.indexOf(this);
  30390. if (index !== -1) {
  30391. cache.splice(index, 1);
  30392. }
  30393. };
  30394. /**
  30395. * Dispose the current allocated resources
  30396. */
  30397. InternalTexture.prototype.dispose = function () {
  30398. if (!this._webGLTexture) {
  30399. return;
  30400. }
  30401. this._references--;
  30402. if (this._references === 0) {
  30403. this._engine._releaseTexture(this);
  30404. this._webGLTexture = null;
  30405. this.previous = null;
  30406. this.next = null;
  30407. }
  30408. };
  30409. /**
  30410. * The source of the texture data is unknown
  30411. */
  30412. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30413. /**
  30414. * Texture data comes from an URL
  30415. */
  30416. InternalTexture.DATASOURCE_URL = 1;
  30417. /**
  30418. * Texture data is only used for temporary storage
  30419. */
  30420. InternalTexture.DATASOURCE_TEMP = 2;
  30421. /**
  30422. * Texture data comes from raw data (ArrayBuffer)
  30423. */
  30424. InternalTexture.DATASOURCE_RAW = 3;
  30425. /**
  30426. * Texture content is dynamic (video or dynamic texture)
  30427. */
  30428. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30429. /**
  30430. * Texture content is generated by rendering to it
  30431. */
  30432. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30433. /**
  30434. * Texture content is part of a multi render target process
  30435. */
  30436. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30437. /**
  30438. * Texture data comes from a cube data file
  30439. */
  30440. InternalTexture.DATASOURCE_CUBE = 7;
  30441. /**
  30442. * Texture data comes from a raw cube data
  30443. */
  30444. InternalTexture.DATASOURCE_CUBERAW = 8;
  30445. /**
  30446. * Texture data come from a prefiltered cube data file
  30447. */
  30448. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30449. /**
  30450. * Texture content is raw 3D data
  30451. */
  30452. InternalTexture.DATASOURCE_RAW3D = 10;
  30453. /**
  30454. * Texture content is a depth texture
  30455. */
  30456. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30457. /**
  30458. * Texture data comes from a raw cube data encoded with RGBD
  30459. */
  30460. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30461. return InternalTexture;
  30462. }());
  30463. BABYLON.InternalTexture = InternalTexture;
  30464. })(BABYLON || (BABYLON = {}));
  30465. //# sourceMappingURL=babylon.internalTexture.js.map
  30466. var BABYLON;
  30467. (function (BABYLON) {
  30468. /**
  30469. * Base class of all the textures in babylon.
  30470. * It groups all the common properties the materials, post process, lights... might need
  30471. * in order to make a correct use of the texture.
  30472. */
  30473. var BaseTexture = /** @class */ (function () {
  30474. /**
  30475. * Instantiates a new BaseTexture.
  30476. * Base class of all the textures in babylon.
  30477. * It groups all the common properties the materials, post process, lights... might need
  30478. * in order to make a correct use of the texture.
  30479. * @param scene Define the scene the texture blongs to
  30480. */
  30481. function BaseTexture(scene) {
  30482. this._hasAlpha = false;
  30483. /**
  30484. * Defines if the alpha value should be determined via the rgb values.
  30485. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  30486. */
  30487. this.getAlphaFromRGB = false;
  30488. /**
  30489. * Intensity or strength of the texture.
  30490. * It is commonly used by materials to fine tune the intensity of the texture
  30491. */
  30492. this.level = 1;
  30493. /**
  30494. * Define the UV chanel to use starting from 0 and defaulting to 0.
  30495. * This is part of the texture as textures usually maps to one uv set.
  30496. */
  30497. this.coordinatesIndex = 0;
  30498. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30499. /**
  30500. * | Value | Type | Description |
  30501. * | ----- | ------------------ | ----------- |
  30502. * | 0 | CLAMP_ADDRESSMODE | |
  30503. * | 1 | WRAP_ADDRESSMODE | |
  30504. * | 2 | MIRROR_ADDRESSMODE | |
  30505. */
  30506. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30507. /**
  30508. * | Value | Type | Description |
  30509. * | ----- | ------------------ | ----------- |
  30510. * | 0 | CLAMP_ADDRESSMODE | |
  30511. * | 1 | WRAP_ADDRESSMODE | |
  30512. * | 2 | MIRROR_ADDRESSMODE | |
  30513. */
  30514. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30515. /**
  30516. * | Value | Type | Description |
  30517. * | ----- | ------------------ | ----------- |
  30518. * | 0 | CLAMP_ADDRESSMODE | |
  30519. * | 1 | WRAP_ADDRESSMODE | |
  30520. * | 2 | MIRROR_ADDRESSMODE | |
  30521. */
  30522. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30523. /**
  30524. * With compliant hardware and browser (supporting anisotropic filtering)
  30525. * this defines the level of anisotropic filtering in the texture.
  30526. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  30527. */
  30528. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30529. /**
  30530. * Define if the texture is a cube texture or if false a 2d texture.
  30531. */
  30532. this.isCube = false;
  30533. /**
  30534. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  30535. */
  30536. this.is3D = false;
  30537. /**
  30538. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  30539. * HDR texture are usually stored in linear space.
  30540. * This only impacts the PBR and Background materials
  30541. */
  30542. this.gammaSpace = true;
  30543. /**
  30544. * Is Z inverted in the texture (useful in a cube texture).
  30545. */
  30546. this.invertZ = false;
  30547. /**
  30548. * @hidden
  30549. */
  30550. this.lodLevelInAlpha = false;
  30551. /**
  30552. * Define if the texture is a render target.
  30553. */
  30554. this.isRenderTarget = false;
  30555. /**
  30556. * Define the list of animation attached to the texture.
  30557. */
  30558. this.animations = new Array();
  30559. /**
  30560. * An event triggered when the texture is disposed.
  30561. */
  30562. this.onDisposeObservable = new BABYLON.Observable();
  30563. /**
  30564. * Define the current state of the loading sequence when in delayed load mode.
  30565. */
  30566. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30567. this._cachedSize = BABYLON.Size.Zero();
  30568. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30569. if (this._scene) {
  30570. this._scene.textures.push(this);
  30571. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30572. }
  30573. this._uid = null;
  30574. }
  30575. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30576. get: function () {
  30577. return this._hasAlpha;
  30578. },
  30579. /**
  30580. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  30581. */
  30582. set: function (value) {
  30583. if (this._hasAlpha === value) {
  30584. return;
  30585. }
  30586. this._hasAlpha = value;
  30587. if (this._scene) {
  30588. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30589. }
  30590. },
  30591. enumerable: true,
  30592. configurable: true
  30593. });
  30594. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30595. get: function () {
  30596. return this._coordinatesMode;
  30597. },
  30598. /**
  30599. * How a texture is mapped.
  30600. *
  30601. * | Value | Type | Description |
  30602. * | ----- | ----------------------------------- | ----------- |
  30603. * | 0 | EXPLICIT_MODE | |
  30604. * | 1 | SPHERICAL_MODE | |
  30605. * | 2 | PLANAR_MODE | |
  30606. * | 3 | CUBIC_MODE | |
  30607. * | 4 | PROJECTION_MODE | |
  30608. * | 5 | SKYBOX_MODE | |
  30609. * | 6 | INVCUBIC_MODE | |
  30610. * | 7 | EQUIRECTANGULAR_MODE | |
  30611. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30612. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30613. */
  30614. set: function (value) {
  30615. if (this._coordinatesMode === value) {
  30616. return;
  30617. }
  30618. this._coordinatesMode = value;
  30619. if (this._scene) {
  30620. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30621. }
  30622. },
  30623. enumerable: true,
  30624. configurable: true
  30625. });
  30626. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30627. /**
  30628. * Gets whether or not the texture contains RGBD data.
  30629. */
  30630. get: function () {
  30631. return this._texture != null && this._texture._isRGBD;
  30632. },
  30633. enumerable: true,
  30634. configurable: true
  30635. });
  30636. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30637. /**
  30638. * With prefiltered texture, defined the offset used during the prefiltering steps.
  30639. */
  30640. get: function () {
  30641. if (this._texture)
  30642. return this._texture._lodGenerationOffset;
  30643. return 0.0;
  30644. },
  30645. set: function (value) {
  30646. if (this._texture)
  30647. this._texture._lodGenerationOffset = value;
  30648. },
  30649. enumerable: true,
  30650. configurable: true
  30651. });
  30652. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30653. /**
  30654. * With prefiltered texture, defined the scale used during the prefiltering steps.
  30655. */
  30656. get: function () {
  30657. if (this._texture)
  30658. return this._texture._lodGenerationScale;
  30659. return 0.0;
  30660. },
  30661. set: function (value) {
  30662. if (this._texture)
  30663. this._texture._lodGenerationScale = value;
  30664. },
  30665. enumerable: true,
  30666. configurable: true
  30667. });
  30668. Object.defineProperty(BaseTexture.prototype, "uid", {
  30669. /**
  30670. * Define the unique id of the texture in the scene.
  30671. */
  30672. get: function () {
  30673. if (!this._uid) {
  30674. this._uid = BABYLON.Tools.RandomId();
  30675. }
  30676. return this._uid;
  30677. },
  30678. enumerable: true,
  30679. configurable: true
  30680. });
  30681. /**
  30682. * Return a string representation of the texture.
  30683. * @returns the texture as a string
  30684. */
  30685. BaseTexture.prototype.toString = function () {
  30686. return this.name;
  30687. };
  30688. /**
  30689. * Get the class name of the texture.
  30690. * @returns "BaseTexture"
  30691. */
  30692. BaseTexture.prototype.getClassName = function () {
  30693. return "BaseTexture";
  30694. };
  30695. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30696. /**
  30697. * Callback triggered when the texture has been disposed.
  30698. * Kept for back compatibility, you can use the onDisposeObservable instead.
  30699. */
  30700. set: function (callback) {
  30701. if (this._onDisposeObserver) {
  30702. this.onDisposeObservable.remove(this._onDisposeObserver);
  30703. }
  30704. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30705. },
  30706. enumerable: true,
  30707. configurable: true
  30708. });
  30709. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30710. /**
  30711. * Define if the texture is preventinga material to render or not.
  30712. * If not and the texture is not ready, the engine will use a default black texture instead.
  30713. */
  30714. get: function () {
  30715. return true;
  30716. },
  30717. enumerable: true,
  30718. configurable: true
  30719. });
  30720. /**
  30721. * Get the scene the texture belongs to.
  30722. * @returns the scene or null if undefined
  30723. */
  30724. BaseTexture.prototype.getScene = function () {
  30725. return this._scene;
  30726. };
  30727. /**
  30728. * Get the texture transform matrix used to offset tile the texture for istance.
  30729. * @returns the transformation matrix
  30730. */
  30731. BaseTexture.prototype.getTextureMatrix = function () {
  30732. return BABYLON.Matrix.IdentityReadOnly;
  30733. };
  30734. /**
  30735. * Get the texture reflection matrix used to rotate/transform the reflection.
  30736. * @returns the reflection matrix
  30737. */
  30738. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30739. return BABYLON.Matrix.IdentityReadOnly;
  30740. };
  30741. /**
  30742. * Get the underlying lower level texture from Babylon.
  30743. * @returns the insternal texture
  30744. */
  30745. BaseTexture.prototype.getInternalTexture = function () {
  30746. return this._texture;
  30747. };
  30748. /**
  30749. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  30750. * @returns true if ready or not blocking
  30751. */
  30752. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30753. return !this.isBlocking || this.isReady();
  30754. };
  30755. /**
  30756. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  30757. * @returns true if fully ready
  30758. */
  30759. BaseTexture.prototype.isReady = function () {
  30760. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30761. this.delayLoad();
  30762. return false;
  30763. }
  30764. if (this._texture) {
  30765. return this._texture.isReady;
  30766. }
  30767. return false;
  30768. };
  30769. /**
  30770. * Get the size of the texture.
  30771. * @returns the texture size.
  30772. */
  30773. BaseTexture.prototype.getSize = function () {
  30774. if (this._texture) {
  30775. if (this._texture.width) {
  30776. this._cachedSize.width = this._texture.width;
  30777. this._cachedSize.height = this._texture.height;
  30778. return this._cachedSize;
  30779. }
  30780. if (this._texture._size) {
  30781. this._cachedSize.width = this._texture._size;
  30782. this._cachedSize.height = this._texture._size;
  30783. return this._cachedSize;
  30784. }
  30785. }
  30786. return this._cachedSize;
  30787. };
  30788. /**
  30789. * Get the base size of the texture.
  30790. * It can be different from the size if the texture has been resized for POT for instance
  30791. * @returns the base size
  30792. */
  30793. BaseTexture.prototype.getBaseSize = function () {
  30794. if (!this.isReady() || !this._texture)
  30795. return BABYLON.Size.Zero();
  30796. if (this._texture._size) {
  30797. return new BABYLON.Size(this._texture._size, this._texture._size);
  30798. }
  30799. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30800. };
  30801. /**
  30802. * Scales the texture if is `canRescale()`
  30803. * @param ratio the resize factor we want to use to rescale
  30804. */
  30805. BaseTexture.prototype.scale = function (ratio) {
  30806. };
  30807. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30808. /**
  30809. * Get if the texture can rescale.
  30810. */
  30811. get: function () {
  30812. return false;
  30813. },
  30814. enumerable: true,
  30815. configurable: true
  30816. });
  30817. /** @hidden */
  30818. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30819. if (!this._scene) {
  30820. return null;
  30821. }
  30822. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30823. for (var index = 0; index < texturesCache.length; index++) {
  30824. var texturesCacheEntry = texturesCache[index];
  30825. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30826. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30827. texturesCacheEntry.incrementReferences();
  30828. return texturesCacheEntry;
  30829. }
  30830. }
  30831. }
  30832. return null;
  30833. };
  30834. /** @hidden */
  30835. BaseTexture.prototype._rebuild = function () {
  30836. };
  30837. /**
  30838. * Triggers the load sequence in delayed load mode.
  30839. */
  30840. BaseTexture.prototype.delayLoad = function () {
  30841. };
  30842. /**
  30843. * Clones the texture.
  30844. * @returns the cloned texture
  30845. */
  30846. BaseTexture.prototype.clone = function () {
  30847. return null;
  30848. };
  30849. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30850. /**
  30851. * Get the texture underlying type (INT, FLOAT...)
  30852. */
  30853. get: function () {
  30854. if (!this._texture) {
  30855. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30856. }
  30857. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30858. },
  30859. enumerable: true,
  30860. configurable: true
  30861. });
  30862. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30863. /**
  30864. * Get the texture underlying format (RGB, RGBA...)
  30865. */
  30866. get: function () {
  30867. if (!this._texture) {
  30868. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30869. }
  30870. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30871. },
  30872. enumerable: true,
  30873. configurable: true
  30874. });
  30875. /**
  30876. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30877. * This will returns an RGBA array buffer containing either in values (0-255) or
  30878. * float values (0-1) depending of the underlying buffer type.
  30879. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30880. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30881. * @param buffer defines a user defined buffer to fill with data (can be null)
  30882. * @returns The Array buffer containing the pixels data.
  30883. */
  30884. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30885. if (faceIndex === void 0) { faceIndex = 0; }
  30886. if (level === void 0) { level = 0; }
  30887. if (buffer === void 0) { buffer = null; }
  30888. if (!this._texture) {
  30889. return null;
  30890. }
  30891. var size = this.getSize();
  30892. var width = size.width;
  30893. var height = size.height;
  30894. var scene = this.getScene();
  30895. if (!scene) {
  30896. return null;
  30897. }
  30898. var engine = scene.getEngine();
  30899. if (level != 0) {
  30900. width = width / Math.pow(2, level);
  30901. height = height / Math.pow(2, level);
  30902. width = Math.round(width);
  30903. height = Math.round(height);
  30904. }
  30905. if (this._texture.isCube) {
  30906. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30907. }
  30908. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30909. };
  30910. /**
  30911. * Release and destroy the underlying lower level texture aka internalTexture.
  30912. */
  30913. BaseTexture.prototype.releaseInternalTexture = function () {
  30914. if (this._texture) {
  30915. this._texture.dispose();
  30916. this._texture = null;
  30917. }
  30918. };
  30919. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30920. /**
  30921. * Get the polynomial representation of the texture data.
  30922. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  30923. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  30924. */
  30925. get: function () {
  30926. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30927. return null;
  30928. }
  30929. if (!this._texture._sphericalPolynomial) {
  30930. this._texture._sphericalPolynomial =
  30931. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30932. }
  30933. return this._texture._sphericalPolynomial;
  30934. },
  30935. set: function (value) {
  30936. if (this._texture) {
  30937. this._texture._sphericalPolynomial = value;
  30938. }
  30939. },
  30940. enumerable: true,
  30941. configurable: true
  30942. });
  30943. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30944. /** @hidden */
  30945. get: function () {
  30946. if (this._texture) {
  30947. return this._texture._lodTextureHigh;
  30948. }
  30949. return null;
  30950. },
  30951. enumerable: true,
  30952. configurable: true
  30953. });
  30954. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30955. /** @hidden */
  30956. get: function () {
  30957. if (this._texture) {
  30958. return this._texture._lodTextureMid;
  30959. }
  30960. return null;
  30961. },
  30962. enumerable: true,
  30963. configurable: true
  30964. });
  30965. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30966. /** @hidden */
  30967. get: function () {
  30968. if (this._texture) {
  30969. return this._texture._lodTextureLow;
  30970. }
  30971. return null;
  30972. },
  30973. enumerable: true,
  30974. configurable: true
  30975. });
  30976. /**
  30977. * Dispose the texture and release its associated resources.
  30978. */
  30979. BaseTexture.prototype.dispose = function () {
  30980. if (!this._scene) {
  30981. return;
  30982. }
  30983. // Animations
  30984. this._scene.stopAnimation(this);
  30985. // Remove from scene
  30986. this._scene._removePendingData(this);
  30987. var index = this._scene.textures.indexOf(this);
  30988. if (index >= 0) {
  30989. this._scene.textures.splice(index, 1);
  30990. }
  30991. this._scene.onTextureRemovedObservable.notifyObservers(this);
  30992. if (this._texture === undefined) {
  30993. return;
  30994. }
  30995. // Release
  30996. this.releaseInternalTexture();
  30997. // Callback
  30998. this.onDisposeObservable.notifyObservers(this);
  30999. this.onDisposeObservable.clear();
  31000. };
  31001. /**
  31002. * Serialize the texture into a JSON representation that can be parsed later on.
  31003. * @returns the JSON representation of the texture
  31004. */
  31005. BaseTexture.prototype.serialize = function () {
  31006. if (!this.name) {
  31007. return null;
  31008. }
  31009. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31010. // Animations
  31011. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31012. return serializationObject;
  31013. };
  31014. /**
  31015. * Helper function to be called back once a list of texture contains only ready textures.
  31016. * @param textures Define the list of textures to wait for
  31017. * @param callback Define the callback triggered once the entire list will be ready
  31018. */
  31019. BaseTexture.WhenAllReady = function (textures, callback) {
  31020. var numRemaining = textures.length;
  31021. if (numRemaining === 0) {
  31022. callback();
  31023. return;
  31024. }
  31025. var _loop_1 = function () {
  31026. texture = textures[i];
  31027. if (texture.isReady()) {
  31028. if (--numRemaining === 0) {
  31029. callback();
  31030. }
  31031. }
  31032. else {
  31033. onLoadObservable = texture.onLoadObservable;
  31034. var onLoadCallback_1 = function () {
  31035. onLoadObservable.removeCallback(onLoadCallback_1);
  31036. if (--numRemaining === 0) {
  31037. callback();
  31038. }
  31039. };
  31040. onLoadObservable.add(onLoadCallback_1);
  31041. }
  31042. };
  31043. var texture, onLoadObservable;
  31044. for (var i = 0; i < textures.length; i++) {
  31045. _loop_1();
  31046. }
  31047. };
  31048. /**
  31049. * Default anisotropic filtering level for the application.
  31050. * It is set to 4 as a good tradeoff between perf and quality.
  31051. */
  31052. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31053. __decorate([
  31054. BABYLON.serialize()
  31055. ], BaseTexture.prototype, "name", void 0);
  31056. __decorate([
  31057. BABYLON.serialize("hasAlpha")
  31058. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31059. __decorate([
  31060. BABYLON.serialize()
  31061. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31062. __decorate([
  31063. BABYLON.serialize()
  31064. ], BaseTexture.prototype, "level", void 0);
  31065. __decorate([
  31066. BABYLON.serialize()
  31067. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31068. __decorate([
  31069. BABYLON.serialize("coordinatesMode")
  31070. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31071. __decorate([
  31072. BABYLON.serialize()
  31073. ], BaseTexture.prototype, "wrapU", void 0);
  31074. __decorate([
  31075. BABYLON.serialize()
  31076. ], BaseTexture.prototype, "wrapV", void 0);
  31077. __decorate([
  31078. BABYLON.serialize()
  31079. ], BaseTexture.prototype, "wrapR", void 0);
  31080. __decorate([
  31081. BABYLON.serialize()
  31082. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31083. __decorate([
  31084. BABYLON.serialize()
  31085. ], BaseTexture.prototype, "isCube", void 0);
  31086. __decorate([
  31087. BABYLON.serialize()
  31088. ], BaseTexture.prototype, "is3D", void 0);
  31089. __decorate([
  31090. BABYLON.serialize()
  31091. ], BaseTexture.prototype, "gammaSpace", void 0);
  31092. __decorate([
  31093. BABYLON.serialize()
  31094. ], BaseTexture.prototype, "invertZ", void 0);
  31095. __decorate([
  31096. BABYLON.serialize()
  31097. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31098. __decorate([
  31099. BABYLON.serialize()
  31100. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31101. __decorate([
  31102. BABYLON.serialize()
  31103. ], BaseTexture.prototype, "lodGenerationScale", null);
  31104. __decorate([
  31105. BABYLON.serialize()
  31106. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31107. return BaseTexture;
  31108. }());
  31109. BABYLON.BaseTexture = BaseTexture;
  31110. })(BABYLON || (BABYLON = {}));
  31111. //# sourceMappingURL=babylon.baseTexture.js.map
  31112. var BABYLON;
  31113. (function (BABYLON) {
  31114. var Texture = /** @class */ (function (_super) {
  31115. __extends(Texture, _super);
  31116. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31117. if (noMipmap === void 0) { noMipmap = false; }
  31118. if (invertY === void 0) { invertY = true; }
  31119. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31120. if (onLoad === void 0) { onLoad = null; }
  31121. if (onError === void 0) { onError = null; }
  31122. if (buffer === void 0) { buffer = null; }
  31123. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31124. var _this = _super.call(this, scene) || this;
  31125. _this.uOffset = 0;
  31126. _this.vOffset = 0;
  31127. _this.uScale = 1.0;
  31128. _this.vScale = 1.0;
  31129. _this.uAng = 0;
  31130. _this.vAng = 0;
  31131. _this.wAng = 0;
  31132. /**
  31133. * Defines the center of rotation (U)
  31134. */
  31135. _this.uRotationCenter = 0.5;
  31136. /**
  31137. * Defines the center of rotation (V)
  31138. */
  31139. _this.vRotationCenter = 0.5;
  31140. /**
  31141. * Defines the center of rotation (W)
  31142. */
  31143. _this.wRotationCenter = 0.5;
  31144. _this._isBlocking = true;
  31145. _this.name = url || "";
  31146. _this.url = url;
  31147. _this._noMipmap = noMipmap;
  31148. _this._invertY = invertY;
  31149. _this._samplingMode = samplingMode;
  31150. _this._buffer = buffer;
  31151. _this._deleteBuffer = deleteBuffer;
  31152. if (format) {
  31153. _this._format = format;
  31154. }
  31155. scene = _this.getScene();
  31156. if (!scene) {
  31157. return _this;
  31158. }
  31159. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31160. var load = function () {
  31161. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  31162. _this.onLoadObservable.notifyObservers(_this);
  31163. }
  31164. if (onLoad) {
  31165. onLoad();
  31166. }
  31167. if (!_this.isBlocking && scene) {
  31168. scene.resetCachedMaterial();
  31169. }
  31170. };
  31171. if (!_this.url) {
  31172. _this._delayedOnLoad = load;
  31173. _this._delayedOnError = onError;
  31174. return _this;
  31175. }
  31176. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31177. if (!_this._texture) {
  31178. if (!scene.useDelayedTextureLoading) {
  31179. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31180. if (deleteBuffer) {
  31181. delete _this._buffer;
  31182. }
  31183. }
  31184. else {
  31185. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31186. _this._delayedOnLoad = load;
  31187. _this._delayedOnError = onError;
  31188. }
  31189. }
  31190. else {
  31191. if (_this._texture.isReady) {
  31192. BABYLON.Tools.SetImmediate(function () { return load(); });
  31193. }
  31194. else {
  31195. _this._texture.onLoadedObservable.add(load);
  31196. }
  31197. }
  31198. return _this;
  31199. }
  31200. Object.defineProperty(Texture.prototype, "noMipmap", {
  31201. get: function () {
  31202. return this._noMipmap;
  31203. },
  31204. enumerable: true,
  31205. configurable: true
  31206. });
  31207. Object.defineProperty(Texture.prototype, "isBlocking", {
  31208. get: function () {
  31209. return this._isBlocking;
  31210. },
  31211. set: function (value) {
  31212. this._isBlocking = value;
  31213. },
  31214. enumerable: true,
  31215. configurable: true
  31216. });
  31217. Object.defineProperty(Texture.prototype, "samplingMode", {
  31218. get: function () {
  31219. return this._samplingMode;
  31220. },
  31221. enumerable: true,
  31222. configurable: true
  31223. });
  31224. /**
  31225. * Update the url (and optional buffer) of this texture if url was null during construction.
  31226. * @param url the url of the texture
  31227. * @param buffer the buffer of the texture (defaults to null)
  31228. */
  31229. Texture.prototype.updateURL = function (url, buffer) {
  31230. if (buffer === void 0) { buffer = null; }
  31231. if (this.url) {
  31232. throw new Error("URL is already set");
  31233. }
  31234. this.url = url;
  31235. this._buffer = buffer;
  31236. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31237. this.delayLoad();
  31238. };
  31239. Texture.prototype.delayLoad = function () {
  31240. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31241. return;
  31242. }
  31243. var scene = this.getScene();
  31244. if (!scene) {
  31245. return;
  31246. }
  31247. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31248. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31249. if (!this._texture) {
  31250. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31251. if (this._deleteBuffer) {
  31252. delete this._buffer;
  31253. }
  31254. }
  31255. else {
  31256. if (this._delayedOnLoad) {
  31257. if (this._texture.isReady) {
  31258. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31259. }
  31260. else {
  31261. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31262. }
  31263. }
  31264. }
  31265. this._delayedOnLoad = null;
  31266. this._delayedOnError = null;
  31267. };
  31268. /**
  31269. * Default is Trilinear mode.
  31270. *
  31271. * | Value | Type | Description |
  31272. * | ----- | ------------------ | ----------- |
  31273. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31274. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31275. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31276. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31277. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31278. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31279. * | 7 | NEAREST_LINEAR | |
  31280. * | 8 | NEAREST_NEAREST | |
  31281. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31282. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31283. * | 11 | LINEAR_LINEAR | |
  31284. * | 12 | LINEAR_NEAREST | |
  31285. *
  31286. * > _mag_: magnification filter (close to the viewer)
  31287. * > _min_: minification filter (far from the viewer)
  31288. * > _mip_: filter used between mip map levels
  31289. *
  31290. */
  31291. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31292. if (!this._texture) {
  31293. return;
  31294. }
  31295. var scene = this.getScene();
  31296. if (!scene) {
  31297. return;
  31298. }
  31299. this._samplingMode = samplingMode;
  31300. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31301. };
  31302. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31303. x *= this.uScale;
  31304. y *= this.vScale;
  31305. x -= this.uRotationCenter * this.uScale;
  31306. y -= this.vRotationCenter * this.vScale;
  31307. z -= this.wRotationCenter;
  31308. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31309. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31310. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31311. t.z += this.wRotationCenter;
  31312. };
  31313. Texture.prototype.getTextureMatrix = function () {
  31314. var _this = this;
  31315. if (this.uOffset === this._cachedUOffset &&
  31316. this.vOffset === this._cachedVOffset &&
  31317. this.uScale === this._cachedUScale &&
  31318. this.vScale === this._cachedVScale &&
  31319. this.uAng === this._cachedUAng &&
  31320. this.vAng === this._cachedVAng &&
  31321. this.wAng === this._cachedWAng) {
  31322. return this._cachedTextureMatrix;
  31323. }
  31324. this._cachedUOffset = this.uOffset;
  31325. this._cachedVOffset = this.vOffset;
  31326. this._cachedUScale = this.uScale;
  31327. this._cachedVScale = this.vScale;
  31328. this._cachedUAng = this.uAng;
  31329. this._cachedVAng = this.vAng;
  31330. this._cachedWAng = this.wAng;
  31331. if (!this._cachedTextureMatrix) {
  31332. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31333. this._rowGenerationMatrix = new BABYLON.Matrix();
  31334. this._t0 = BABYLON.Vector3.Zero();
  31335. this._t1 = BABYLON.Vector3.Zero();
  31336. this._t2 = BABYLON.Vector3.Zero();
  31337. }
  31338. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31339. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31340. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31341. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31342. this._t1.subtractInPlace(this._t0);
  31343. this._t2.subtractInPlace(this._t0);
  31344. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31345. this._cachedTextureMatrix.m[0] = this._t1.x;
  31346. this._cachedTextureMatrix.m[1] = this._t1.y;
  31347. this._cachedTextureMatrix.m[2] = this._t1.z;
  31348. this._cachedTextureMatrix.m[4] = this._t2.x;
  31349. this._cachedTextureMatrix.m[5] = this._t2.y;
  31350. this._cachedTextureMatrix.m[6] = this._t2.z;
  31351. this._cachedTextureMatrix.m[8] = this._t0.x;
  31352. this._cachedTextureMatrix.m[9] = this._t0.y;
  31353. this._cachedTextureMatrix.m[10] = this._t0.z;
  31354. var scene = this.getScene();
  31355. if (!scene) {
  31356. return this._cachedTextureMatrix;
  31357. }
  31358. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31359. return mat.hasTexture(_this);
  31360. });
  31361. return this._cachedTextureMatrix;
  31362. };
  31363. Texture.prototype.getReflectionTextureMatrix = function () {
  31364. var _this = this;
  31365. var scene = this.getScene();
  31366. if (!scene) {
  31367. return this._cachedTextureMatrix;
  31368. }
  31369. if (this.uOffset === this._cachedUOffset &&
  31370. this.vOffset === this._cachedVOffset &&
  31371. this.uScale === this._cachedUScale &&
  31372. this.vScale === this._cachedVScale &&
  31373. this.coordinatesMode === this._cachedCoordinatesMode) {
  31374. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31375. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31376. return this._cachedTextureMatrix;
  31377. }
  31378. }
  31379. else {
  31380. return this._cachedTextureMatrix;
  31381. }
  31382. }
  31383. if (!this._cachedTextureMatrix) {
  31384. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31385. }
  31386. if (!this._projectionModeMatrix) {
  31387. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31388. }
  31389. this._cachedUOffset = this.uOffset;
  31390. this._cachedVOffset = this.vOffset;
  31391. this._cachedUScale = this.uScale;
  31392. this._cachedVScale = this.vScale;
  31393. this._cachedCoordinatesMode = this.coordinatesMode;
  31394. switch (this.coordinatesMode) {
  31395. case Texture.PLANAR_MODE:
  31396. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31397. this._cachedTextureMatrix[0] = this.uScale;
  31398. this._cachedTextureMatrix[5] = this.vScale;
  31399. this._cachedTextureMatrix[12] = this.uOffset;
  31400. this._cachedTextureMatrix[13] = this.vOffset;
  31401. break;
  31402. case Texture.PROJECTION_MODE:
  31403. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31404. this._projectionModeMatrix.m[0] = 0.5;
  31405. this._projectionModeMatrix.m[5] = -0.5;
  31406. this._projectionModeMatrix.m[10] = 0.0;
  31407. this._projectionModeMatrix.m[12] = 0.5;
  31408. this._projectionModeMatrix.m[13] = 0.5;
  31409. this._projectionModeMatrix.m[14] = 1.0;
  31410. this._projectionModeMatrix.m[15] = 1.0;
  31411. var projectionMatrix = scene.getProjectionMatrix();
  31412. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31413. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31414. break;
  31415. default:
  31416. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31417. break;
  31418. }
  31419. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31420. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31421. });
  31422. return this._cachedTextureMatrix;
  31423. };
  31424. Texture.prototype.clone = function () {
  31425. var _this = this;
  31426. return BABYLON.SerializationHelper.Clone(function () {
  31427. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31428. }, this);
  31429. };
  31430. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31431. get: function () {
  31432. if (!this._onLoadObservable) {
  31433. this._onLoadObservable = new BABYLON.Observable();
  31434. }
  31435. return this._onLoadObservable;
  31436. },
  31437. enumerable: true,
  31438. configurable: true
  31439. });
  31440. Texture.prototype.serialize = function () {
  31441. var serializationObject = _super.prototype.serialize.call(this);
  31442. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31443. serializationObject.base64String = this._buffer;
  31444. serializationObject.name = serializationObject.name.replace("data:", "");
  31445. }
  31446. serializationObject.invertY = this._invertY;
  31447. serializationObject.samplingMode = this.samplingMode;
  31448. return serializationObject;
  31449. };
  31450. Texture.prototype.getClassName = function () {
  31451. return "Texture";
  31452. };
  31453. Texture.prototype.dispose = function () {
  31454. _super.prototype.dispose.call(this);
  31455. if (this._onLoadObservable) {
  31456. this._onLoadObservable.clear();
  31457. this._onLoadObservable = null;
  31458. }
  31459. this._delayedOnLoad = null;
  31460. this._delayedOnError = null;
  31461. };
  31462. // Statics
  31463. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31464. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31465. if (onLoad === void 0) { onLoad = null; }
  31466. if (onError === void 0) { onError = null; }
  31467. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31468. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31469. };
  31470. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31471. if (parsedTexture.customType) {
  31472. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31473. // Update Sampling Mode
  31474. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31475. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31476. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31477. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31478. }
  31479. }
  31480. return parsedCustomTexture;
  31481. }
  31482. if (parsedTexture.isCube) {
  31483. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31484. }
  31485. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31486. return null;
  31487. }
  31488. var texture = BABYLON.SerializationHelper.Parse(function () {
  31489. var generateMipMaps = true;
  31490. if (parsedTexture.noMipmap) {
  31491. generateMipMaps = false;
  31492. }
  31493. if (parsedTexture.mirrorPlane) {
  31494. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31495. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31496. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31497. return mirrorTexture;
  31498. }
  31499. else if (parsedTexture.isRenderTarget) {
  31500. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31501. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31502. return renderTargetTexture;
  31503. }
  31504. else {
  31505. var texture;
  31506. if (parsedTexture.base64String) {
  31507. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31508. }
  31509. else {
  31510. var url = rootUrl + parsedTexture.name;
  31511. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31512. url = parsedTexture.url;
  31513. }
  31514. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31515. }
  31516. return texture;
  31517. }
  31518. }, parsedTexture, scene);
  31519. // Update Sampling Mode
  31520. if (parsedTexture.samplingMode) {
  31521. var sampling = parsedTexture.samplingMode;
  31522. if (texture._samplingMode !== sampling) {
  31523. texture.updateSamplingMode(sampling);
  31524. }
  31525. }
  31526. // Animations
  31527. if (parsedTexture.animations) {
  31528. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31529. var parsedAnimation = parsedTexture.animations[animationIndex];
  31530. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31531. }
  31532. }
  31533. return texture;
  31534. };
  31535. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31536. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31537. if (noMipmap === void 0) { noMipmap = false; }
  31538. if (invertY === void 0) { invertY = true; }
  31539. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31540. if (onLoad === void 0) { onLoad = null; }
  31541. if (onError === void 0) { onError = null; }
  31542. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31543. if (name.substr(0, 5) !== "data:") {
  31544. name = "data:" + name;
  31545. }
  31546. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31547. };
  31548. // Constants
  31549. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31550. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31551. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31552. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31553. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31554. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31555. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31556. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31557. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31558. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31559. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31560. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31561. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31562. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31563. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31564. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31565. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31566. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31567. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31568. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31569. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31570. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31571. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31572. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31573. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31574. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31575. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31576. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31577. /**
  31578. * 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
  31579. */
  31580. Texture.UseSerializedUrlIfAny = false;
  31581. __decorate([
  31582. BABYLON.serialize()
  31583. ], Texture.prototype, "url", void 0);
  31584. __decorate([
  31585. BABYLON.serialize()
  31586. ], Texture.prototype, "uOffset", void 0);
  31587. __decorate([
  31588. BABYLON.serialize()
  31589. ], Texture.prototype, "vOffset", void 0);
  31590. __decorate([
  31591. BABYLON.serialize()
  31592. ], Texture.prototype, "uScale", void 0);
  31593. __decorate([
  31594. BABYLON.serialize()
  31595. ], Texture.prototype, "vScale", void 0);
  31596. __decorate([
  31597. BABYLON.serialize()
  31598. ], Texture.prototype, "uAng", void 0);
  31599. __decorate([
  31600. BABYLON.serialize()
  31601. ], Texture.prototype, "vAng", void 0);
  31602. __decorate([
  31603. BABYLON.serialize()
  31604. ], Texture.prototype, "wAng", void 0);
  31605. __decorate([
  31606. BABYLON.serialize()
  31607. ], Texture.prototype, "uRotationCenter", void 0);
  31608. __decorate([
  31609. BABYLON.serialize()
  31610. ], Texture.prototype, "vRotationCenter", void 0);
  31611. __decorate([
  31612. BABYLON.serialize()
  31613. ], Texture.prototype, "wRotationCenter", void 0);
  31614. __decorate([
  31615. BABYLON.serialize()
  31616. ], Texture.prototype, "isBlocking", null);
  31617. return Texture;
  31618. }(BABYLON.BaseTexture));
  31619. BABYLON.Texture = Texture;
  31620. })(BABYLON || (BABYLON = {}));
  31621. //# sourceMappingURL=babylon.texture.js.map
  31622. var BABYLON;
  31623. (function (BABYLON) {
  31624. /**
  31625. * @hidden
  31626. **/
  31627. var _CreationDataStorage = /** @class */ (function () {
  31628. function _CreationDataStorage() {
  31629. }
  31630. return _CreationDataStorage;
  31631. }());
  31632. BABYLON._CreationDataStorage = _CreationDataStorage;
  31633. /**
  31634. * @hidden
  31635. **/
  31636. var _InstanceDataStorage = /** @class */ (function () {
  31637. function _InstanceDataStorage() {
  31638. this.visibleInstances = {};
  31639. this.renderIdForInstances = new Array();
  31640. this.batchCache = new _InstancesBatch();
  31641. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31642. }
  31643. return _InstanceDataStorage;
  31644. }());
  31645. /**
  31646. * @hidden
  31647. **/
  31648. var _InstancesBatch = /** @class */ (function () {
  31649. function _InstancesBatch() {
  31650. this.mustReturn = false;
  31651. this.visibleInstances = new Array();
  31652. this.renderSelf = new Array();
  31653. }
  31654. return _InstancesBatch;
  31655. }());
  31656. BABYLON._InstancesBatch = _InstancesBatch;
  31657. /**
  31658. * Class used to represent renderable models
  31659. */
  31660. var Mesh = /** @class */ (function (_super) {
  31661. __extends(Mesh, _super);
  31662. /**
  31663. * @constructor
  31664. * @param name The value used by scene.getMeshByName() to do a lookup.
  31665. * @param scene The scene to add this mesh to.
  31666. * @param parent The parent of this mesh, if it has one
  31667. * @param source An optional Mesh from which geometry is shared, cloned.
  31668. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31669. * When false, achieved by calling a clone(), also passing False.
  31670. * This will make creation of children, recursive.
  31671. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31672. */
  31673. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31674. if (scene === void 0) { scene = null; }
  31675. if (parent === void 0) { parent = null; }
  31676. if (source === void 0) { source = null; }
  31677. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31678. var _this = _super.call(this, name, scene) || this;
  31679. // Members
  31680. /**
  31681. * Gets the delay loading state of the mesh (when delay loading is turned on)
  31682. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  31683. */
  31684. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31685. /**
  31686. * Gets the list of instances created from this mesh
  31687. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  31688. */
  31689. _this.instances = new Array();
  31690. _this._LODLevels = new Array();
  31691. /** @hidden */
  31692. _this._instanceDataStorage = new _InstanceDataStorage();
  31693. // Use by builder only to know what orientation were the mesh build in.
  31694. /** @hidden */
  31695. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  31696. /**
  31697. * Use this property to change the original side orientation defined at construction time
  31698. */
  31699. _this.overrideMaterialSideOrientation = null;
  31700. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31701. // Will be used to save a source mesh reference, If any
  31702. _this._source = null;
  31703. scene = _this.getScene();
  31704. if (source) {
  31705. // Geometry
  31706. if (source._geometry) {
  31707. source._geometry.applyToMesh(_this);
  31708. }
  31709. // Deep copy
  31710. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31711. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31712. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31713. ], ["_poseMatrix"]);
  31714. // Source mesh
  31715. _this._source = source;
  31716. // Construction Params
  31717. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31718. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31719. _this._creationDataStorage = source._creationDataStorage;
  31720. // Animation ranges
  31721. if (_this._source._ranges) {
  31722. var ranges = _this._source._ranges;
  31723. for (var name in ranges) {
  31724. if (!ranges.hasOwnProperty(name)) {
  31725. continue;
  31726. }
  31727. if (!ranges[name]) {
  31728. continue;
  31729. }
  31730. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31731. }
  31732. }
  31733. // Metadata
  31734. if (source.metadata && source.metadata.clone) {
  31735. _this.metadata = source.metadata.clone();
  31736. }
  31737. else {
  31738. _this.metadata = source.metadata;
  31739. }
  31740. // Tags
  31741. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31742. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31743. }
  31744. // Parent
  31745. _this.parent = source.parent;
  31746. // Pivot
  31747. _this.setPivotMatrix(source.getPivotMatrix());
  31748. _this.id = name + "." + source.id;
  31749. // Material
  31750. _this.material = source.material;
  31751. var index;
  31752. if (!doNotCloneChildren) {
  31753. // Children
  31754. var directDescendants = source.getDescendants(true);
  31755. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31756. var child = directDescendants[index_1];
  31757. if (child.clone) {
  31758. child.clone(name + "." + child.name, _this);
  31759. }
  31760. }
  31761. }
  31762. // Physics clone
  31763. var physicsEngine = _this.getScene().getPhysicsEngine();
  31764. if (clonePhysicsImpostor && physicsEngine) {
  31765. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31766. if (impostor) {
  31767. _this.physicsImpostor = impostor.clone(_this);
  31768. }
  31769. }
  31770. // Particles
  31771. for (index = 0; index < scene.particleSystems.length; index++) {
  31772. var system = scene.particleSystems[index];
  31773. if (system.emitter === source) {
  31774. system.clone(system.name, _this);
  31775. }
  31776. }
  31777. _this.refreshBoundingInfo();
  31778. _this.computeWorldMatrix(true);
  31779. }
  31780. // Parent
  31781. if (parent !== null) {
  31782. _this.parent = parent;
  31783. }
  31784. return _this;
  31785. }
  31786. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31787. /**
  31788. * An event triggered before rendering the mesh
  31789. */
  31790. get: function () {
  31791. if (!this._onBeforeRenderObservable) {
  31792. this._onBeforeRenderObservable = new BABYLON.Observable();
  31793. }
  31794. return this._onBeforeRenderObservable;
  31795. },
  31796. enumerable: true,
  31797. configurable: true
  31798. });
  31799. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31800. /**
  31801. * An event triggered after rendering the mesh
  31802. */
  31803. get: function () {
  31804. if (!this._onAfterRenderObservable) {
  31805. this._onAfterRenderObservable = new BABYLON.Observable();
  31806. }
  31807. return this._onAfterRenderObservable;
  31808. },
  31809. enumerable: true,
  31810. configurable: true
  31811. });
  31812. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31813. /**
  31814. * An event triggered before drawing the mesh
  31815. */
  31816. get: function () {
  31817. if (!this._onBeforeDrawObservable) {
  31818. this._onBeforeDrawObservable = new BABYLON.Observable();
  31819. }
  31820. return this._onBeforeDrawObservable;
  31821. },
  31822. enumerable: true,
  31823. configurable: true
  31824. });
  31825. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31826. /**
  31827. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  31828. */
  31829. set: function (callback) {
  31830. if (this._onBeforeDrawObserver) {
  31831. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31832. }
  31833. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31834. },
  31835. enumerable: true,
  31836. configurable: true
  31837. });
  31838. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31839. /**
  31840. * Gets or sets the morph target manager
  31841. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31842. */
  31843. get: function () {
  31844. return this._morphTargetManager;
  31845. },
  31846. set: function (value) {
  31847. if (this._morphTargetManager === value) {
  31848. return;
  31849. }
  31850. this._morphTargetManager = value;
  31851. this._syncGeometryWithMorphTargetManager();
  31852. },
  31853. enumerable: true,
  31854. configurable: true
  31855. });
  31856. Object.defineProperty(Mesh.prototype, "source", {
  31857. /**
  31858. * Gets the source mesh (the one used to clone this one from)
  31859. */
  31860. get: function () {
  31861. return this._source;
  31862. },
  31863. enumerable: true,
  31864. configurable: true
  31865. });
  31866. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31867. /**
  31868. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31869. */
  31870. get: function () {
  31871. return this._unIndexed;
  31872. },
  31873. set: function (value) {
  31874. if (this._unIndexed !== value) {
  31875. this._unIndexed = value;
  31876. this._markSubMeshesAsAttributesDirty();
  31877. }
  31878. },
  31879. enumerable: true,
  31880. configurable: true
  31881. });
  31882. // Methods
  31883. /**
  31884. * Gets the class name
  31885. * @returns the string "Mesh".
  31886. */
  31887. Mesh.prototype.getClassName = function () {
  31888. return "Mesh";
  31889. };
  31890. /**
  31891. * Returns a description of this mesh
  31892. * @param fullDetails define if full details about this mesh must be used
  31893. * @returns a descriptive string representing this mesh
  31894. */
  31895. Mesh.prototype.toString = function (fullDetails) {
  31896. var ret = _super.prototype.toString.call(this, fullDetails);
  31897. ret += ", n vertices: " + this.getTotalVertices();
  31898. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31899. if (this.animations) {
  31900. for (var i = 0; i < this.animations.length; i++) {
  31901. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31902. }
  31903. }
  31904. if (fullDetails) {
  31905. if (this._geometry) {
  31906. var ib = this.getIndices();
  31907. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31908. if (vb && ib) {
  31909. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31910. }
  31911. }
  31912. else {
  31913. ret += ", flat shading: UNKNOWN";
  31914. }
  31915. }
  31916. return ret;
  31917. };
  31918. /** @hidden */
  31919. Mesh.prototype._unBindEffect = function () {
  31920. _super.prototype._unBindEffect.call(this);
  31921. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31922. var instance = _a[_i];
  31923. instance._unBindEffect();
  31924. }
  31925. };
  31926. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31927. /**
  31928. * Gets a boolean indicating if this mesh has LOD
  31929. */
  31930. get: function () {
  31931. return this._LODLevels.length > 0;
  31932. },
  31933. enumerable: true,
  31934. configurable: true
  31935. });
  31936. /**
  31937. * Gets the list of MeshLODLevel associated with the current mesh
  31938. * @returns an array of MeshLODLevel
  31939. */
  31940. Mesh.prototype.getLODLevels = function () {
  31941. return this._LODLevels;
  31942. };
  31943. Mesh.prototype._sortLODLevels = function () {
  31944. this._LODLevels.sort(function (a, b) {
  31945. if (a.distance < b.distance) {
  31946. return 1;
  31947. }
  31948. if (a.distance > b.distance) {
  31949. return -1;
  31950. }
  31951. return 0;
  31952. });
  31953. };
  31954. /**
  31955. * Add a mesh as LOD level triggered at the given distance.
  31956. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31957. * @param distance The distance from the center of the object to show this level
  31958. * @param mesh The mesh to be added as LOD level (can be null)
  31959. * @return This mesh (for chaining)
  31960. */
  31961. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31962. if (mesh && mesh._masterMesh) {
  31963. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31964. return this;
  31965. }
  31966. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31967. this._LODLevels.push(level);
  31968. if (mesh) {
  31969. mesh._masterMesh = this;
  31970. }
  31971. this._sortLODLevels();
  31972. return this;
  31973. };
  31974. /**
  31975. * Returns the LOD level mesh at the passed distance or null if not found.
  31976. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31977. * @param distance The distance from the center of the object to show this level
  31978. * @returns a Mesh or `null`
  31979. */
  31980. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31981. for (var index = 0; index < this._LODLevels.length; index++) {
  31982. var level = this._LODLevels[index];
  31983. if (level.distance === distance) {
  31984. return level.mesh;
  31985. }
  31986. }
  31987. return null;
  31988. };
  31989. /**
  31990. * Remove a mesh from the LOD array
  31991. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31992. * @param mesh defines the mesh to be removed
  31993. * @return This mesh (for chaining)
  31994. */
  31995. Mesh.prototype.removeLODLevel = function (mesh) {
  31996. for (var index = 0; index < this._LODLevels.length; index++) {
  31997. if (this._LODLevels[index].mesh === mesh) {
  31998. this._LODLevels.splice(index, 1);
  31999. if (mesh) {
  32000. mesh._masterMesh = null;
  32001. }
  32002. }
  32003. }
  32004. this._sortLODLevels();
  32005. return this;
  32006. };
  32007. /**
  32008. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32009. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32010. * @param camera defines the camera to use to compute distance
  32011. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32012. * @return This mesh (for chaining)
  32013. */
  32014. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32015. if (!this._LODLevels || this._LODLevels.length === 0) {
  32016. return this;
  32017. }
  32018. var bSphere;
  32019. if (boundingSphere) {
  32020. bSphere = boundingSphere;
  32021. }
  32022. else {
  32023. var boundingInfo = this.getBoundingInfo();
  32024. bSphere = boundingInfo.boundingSphere;
  32025. }
  32026. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32027. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32028. if (this.onLODLevelSelection) {
  32029. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32030. }
  32031. return this;
  32032. }
  32033. for (var index = 0; index < this._LODLevels.length; index++) {
  32034. var level = this._LODLevels[index];
  32035. if (level.distance < distanceToCamera) {
  32036. if (level.mesh) {
  32037. level.mesh._preActivate();
  32038. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32039. }
  32040. if (this.onLODLevelSelection) {
  32041. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32042. }
  32043. return level.mesh;
  32044. }
  32045. }
  32046. if (this.onLODLevelSelection) {
  32047. this.onLODLevelSelection(distanceToCamera, this, this);
  32048. }
  32049. return this;
  32050. };
  32051. Object.defineProperty(Mesh.prototype, "geometry", {
  32052. /**
  32053. * Gets the mesh internal Geometry object
  32054. */
  32055. get: function () {
  32056. return this._geometry;
  32057. },
  32058. enumerable: true,
  32059. configurable: true
  32060. });
  32061. /**
  32062. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32063. * @returns the total number of vertices
  32064. */
  32065. Mesh.prototype.getTotalVertices = function () {
  32066. if (this._geometry === null || this._geometry === undefined) {
  32067. return 0;
  32068. }
  32069. return this._geometry.getTotalVertices();
  32070. };
  32071. /**
  32072. * Returns the content of an associated vertex buffer
  32073. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32074. * - BABYLON.VertexBuffer.PositionKind
  32075. * - BABYLON.VertexBuffer.UVKind
  32076. * - BABYLON.VertexBuffer.UV2Kind
  32077. * - BABYLON.VertexBuffer.UV3Kind
  32078. * - BABYLON.VertexBuffer.UV4Kind
  32079. * - BABYLON.VertexBuffer.UV5Kind
  32080. * - BABYLON.VertexBuffer.UV6Kind
  32081. * - BABYLON.VertexBuffer.ColorKind
  32082. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32083. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32084. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32085. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32086. * @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
  32087. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32088. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32089. */
  32090. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32091. if (!this._geometry) {
  32092. return null;
  32093. }
  32094. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32095. };
  32096. /**
  32097. * Returns the mesh VertexBuffer object from the requested `kind`
  32098. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32099. * - BABYLON.VertexBuffer.PositionKind
  32100. * - BABYLON.VertexBuffer.UVKind
  32101. * - BABYLON.VertexBuffer.UV2Kind
  32102. * - BABYLON.VertexBuffer.UV3Kind
  32103. * - BABYLON.VertexBuffer.UV4Kind
  32104. * - BABYLON.VertexBuffer.UV5Kind
  32105. * - BABYLON.VertexBuffer.UV6Kind
  32106. * - BABYLON.VertexBuffer.ColorKind
  32107. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32108. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32109. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32110. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32111. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32112. */
  32113. Mesh.prototype.getVertexBuffer = function (kind) {
  32114. if (!this._geometry) {
  32115. return null;
  32116. }
  32117. return this._geometry.getVertexBuffer(kind);
  32118. };
  32119. /**
  32120. * Tests if a specific vertex buffer is associated with this mesh
  32121. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32122. * - BABYLON.VertexBuffer.PositionKind
  32123. * - BABYLON.VertexBuffer.UVKind
  32124. * - BABYLON.VertexBuffer.UV2Kind
  32125. * - BABYLON.VertexBuffer.UV3Kind
  32126. * - BABYLON.VertexBuffer.UV4Kind
  32127. * - BABYLON.VertexBuffer.UV5Kind
  32128. * - BABYLON.VertexBuffer.UV6Kind
  32129. * - BABYLON.VertexBuffer.ColorKind
  32130. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32131. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32132. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32133. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32134. * @returns a boolean
  32135. */
  32136. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32137. if (!this._geometry) {
  32138. if (this._delayInfo) {
  32139. return this._delayInfo.indexOf(kind) !== -1;
  32140. }
  32141. return false;
  32142. }
  32143. return this._geometry.isVerticesDataPresent(kind);
  32144. };
  32145. /**
  32146. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32147. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32148. * - BABYLON.VertexBuffer.PositionKind
  32149. * - BABYLON.VertexBuffer.UVKind
  32150. * - BABYLON.VertexBuffer.UV2Kind
  32151. * - BABYLON.VertexBuffer.UV3Kind
  32152. * - BABYLON.VertexBuffer.UV4Kind
  32153. * - BABYLON.VertexBuffer.UV5Kind
  32154. * - BABYLON.VertexBuffer.UV6Kind
  32155. * - BABYLON.VertexBuffer.ColorKind
  32156. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32157. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32158. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32159. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32160. * @returns a boolean
  32161. */
  32162. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32163. if (!this._geometry) {
  32164. if (this._delayInfo) {
  32165. return this._delayInfo.indexOf(kind) !== -1;
  32166. }
  32167. return false;
  32168. }
  32169. return this._geometry.isVertexBufferUpdatable(kind);
  32170. };
  32171. /**
  32172. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32173. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32174. * - BABYLON.VertexBuffer.PositionKind
  32175. * - BABYLON.VertexBuffer.UVKind
  32176. * - BABYLON.VertexBuffer.UV2Kind
  32177. * - BABYLON.VertexBuffer.UV3Kind
  32178. * - BABYLON.VertexBuffer.UV4Kind
  32179. * - BABYLON.VertexBuffer.UV5Kind
  32180. * - BABYLON.VertexBuffer.UV6Kind
  32181. * - BABYLON.VertexBuffer.ColorKind
  32182. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32183. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32184. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32185. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32186. * @returns an array of strings
  32187. */
  32188. Mesh.prototype.getVerticesDataKinds = function () {
  32189. if (!this._geometry) {
  32190. var result = new Array();
  32191. if (this._delayInfo) {
  32192. this._delayInfo.forEach(function (kind, index, array) {
  32193. result.push(kind);
  32194. });
  32195. }
  32196. return result;
  32197. }
  32198. return this._geometry.getVerticesDataKinds();
  32199. };
  32200. /**
  32201. * Returns a positive integer : the total number of indices in this mesh geometry.
  32202. * @returns the numner of indices or zero if the mesh has no geometry.
  32203. */
  32204. Mesh.prototype.getTotalIndices = function () {
  32205. if (!this._geometry) {
  32206. return 0;
  32207. }
  32208. return this._geometry.getTotalIndices();
  32209. };
  32210. /**
  32211. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32212. * @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.
  32213. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32214. * @returns the indices array or an empty array if the mesh has no geometry
  32215. */
  32216. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32217. if (!this._geometry) {
  32218. return [];
  32219. }
  32220. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32221. };
  32222. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32223. get: function () {
  32224. return this._masterMesh !== null && this._masterMesh !== undefined;
  32225. },
  32226. enumerable: true,
  32227. configurable: true
  32228. });
  32229. /**
  32230. * Determine if the current mesh is ready to be rendered
  32231. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32232. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32233. * @returns true if all associated assets are ready (material, textures, shaders)
  32234. */
  32235. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32236. if (completeCheck === void 0) { completeCheck = false; }
  32237. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32238. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32239. return false;
  32240. }
  32241. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32242. return false;
  32243. }
  32244. if (!this.subMeshes || this.subMeshes.length === 0) {
  32245. return true;
  32246. }
  32247. if (!completeCheck) {
  32248. return true;
  32249. }
  32250. var engine = this.getEngine();
  32251. var scene = this.getScene();
  32252. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32253. this.computeWorldMatrix();
  32254. var mat = this.material || scene.defaultMaterial;
  32255. if (mat) {
  32256. if (mat.storeEffectOnSubMeshes) {
  32257. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32258. var subMesh = _a[_i];
  32259. var effectiveMaterial = subMesh.getMaterial();
  32260. if (effectiveMaterial) {
  32261. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32262. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32263. return false;
  32264. }
  32265. }
  32266. else {
  32267. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32268. return false;
  32269. }
  32270. }
  32271. }
  32272. }
  32273. }
  32274. else {
  32275. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32276. return false;
  32277. }
  32278. }
  32279. }
  32280. // Shadows
  32281. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32282. var light = _c[_b];
  32283. var generator = light.getShadowGenerator();
  32284. if (generator) {
  32285. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32286. var subMesh = _e[_d];
  32287. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32288. return false;
  32289. }
  32290. }
  32291. }
  32292. }
  32293. // LOD
  32294. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32295. var lod = _g[_f];
  32296. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32297. return false;
  32298. }
  32299. }
  32300. return true;
  32301. };
  32302. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32303. /**
  32304. * 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.
  32305. */
  32306. get: function () {
  32307. return this._areNormalsFrozen;
  32308. },
  32309. enumerable: true,
  32310. configurable: true
  32311. });
  32312. /**
  32313. * 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.
  32314. * @returns the current mesh
  32315. */
  32316. Mesh.prototype.freezeNormals = function () {
  32317. this._areNormalsFrozen = true;
  32318. return this;
  32319. };
  32320. /**
  32321. * 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
  32322. * @returns the current mesh
  32323. */
  32324. Mesh.prototype.unfreezeNormals = function () {
  32325. this._areNormalsFrozen = false;
  32326. return this;
  32327. };
  32328. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32329. /**
  32330. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32331. */
  32332. set: function (count) {
  32333. this._instanceDataStorage.overridenInstanceCount = count;
  32334. },
  32335. enumerable: true,
  32336. configurable: true
  32337. });
  32338. // Methods
  32339. /** @hidden */
  32340. Mesh.prototype._preActivate = function () {
  32341. var sceneRenderId = this.getScene().getRenderId();
  32342. if (this._preActivateId === sceneRenderId) {
  32343. return this;
  32344. }
  32345. this._preActivateId = sceneRenderId;
  32346. this._instanceDataStorage.visibleInstances = null;
  32347. return this;
  32348. };
  32349. /** @hidden */
  32350. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32351. if (this._instanceDataStorage.visibleInstances) {
  32352. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32353. }
  32354. return this;
  32355. };
  32356. /** @hidden */
  32357. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32358. if (!this._instanceDataStorage.visibleInstances) {
  32359. this._instanceDataStorage.visibleInstances = {};
  32360. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32361. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32362. }
  32363. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32364. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32365. }
  32366. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32367. return this;
  32368. };
  32369. /**
  32370. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32371. * This means the mesh underlying bounding box and sphere are recomputed.
  32372. * @returns the current mesh
  32373. */
  32374. Mesh.prototype.refreshBoundingInfo = function () {
  32375. return this._refreshBoundingInfo(false);
  32376. };
  32377. /** @hidden */
  32378. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32379. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32380. return this;
  32381. }
  32382. var data = this._getPositionData(applySkeleton);
  32383. if (data) {
  32384. var bias = this.geometry ? this.geometry.boundingBias : null;
  32385. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32386. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32387. }
  32388. if (this.subMeshes) {
  32389. for (var index = 0; index < this.subMeshes.length; index++) {
  32390. this.subMeshes[index].refreshBoundingInfo();
  32391. }
  32392. }
  32393. this._updateBoundingInfo();
  32394. return this;
  32395. };
  32396. Mesh.prototype._getPositionData = function (applySkeleton) {
  32397. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32398. if (data && applySkeleton && this.skeleton) {
  32399. data = BABYLON.Tools.Slice(data);
  32400. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32401. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32402. if (matricesWeightsData && matricesIndicesData) {
  32403. var needExtras = this.numBoneInfluencers > 4;
  32404. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32405. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32406. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32407. var tempVector = BABYLON.Tmp.Vector3[0];
  32408. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32409. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32410. var matWeightIdx = 0;
  32411. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32412. finalMatrix.reset();
  32413. var inf;
  32414. var weight;
  32415. for (inf = 0; inf < 4; inf++) {
  32416. weight = matricesWeightsData[matWeightIdx + inf];
  32417. if (weight > 0) {
  32418. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32419. finalMatrix.addToSelf(tempMatrix);
  32420. }
  32421. }
  32422. if (needExtras) {
  32423. for (inf = 0; inf < 4; inf++) {
  32424. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32425. if (weight > 0) {
  32426. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32427. finalMatrix.addToSelf(tempMatrix);
  32428. }
  32429. }
  32430. }
  32431. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32432. tempVector.toArray(data, index);
  32433. }
  32434. }
  32435. }
  32436. return data;
  32437. };
  32438. /** @hidden */
  32439. Mesh.prototype._createGlobalSubMesh = function (force) {
  32440. var totalVertices = this.getTotalVertices();
  32441. if (!totalVertices || !this.getIndices()) {
  32442. return null;
  32443. }
  32444. // Check if we need to recreate the submeshes
  32445. if (this.subMeshes && this.subMeshes.length > 0) {
  32446. var ib = this.getIndices();
  32447. if (!ib) {
  32448. return null;
  32449. }
  32450. var totalIndices = ib.length;
  32451. var needToRecreate = false;
  32452. if (force) {
  32453. needToRecreate = true;
  32454. }
  32455. else {
  32456. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32457. var submesh = _a[_i];
  32458. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32459. needToRecreate = true;
  32460. break;
  32461. }
  32462. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32463. needToRecreate = true;
  32464. break;
  32465. }
  32466. }
  32467. }
  32468. if (!needToRecreate) {
  32469. return this.subMeshes[0];
  32470. }
  32471. }
  32472. this.releaseSubMeshes();
  32473. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32474. };
  32475. /**
  32476. * This function will subdivide the mesh into multiple submeshes
  32477. * @param count defines the expected number of submeshes
  32478. */
  32479. Mesh.prototype.subdivide = function (count) {
  32480. if (count < 1) {
  32481. return;
  32482. }
  32483. var totalIndices = this.getTotalIndices();
  32484. var subdivisionSize = (totalIndices / count) | 0;
  32485. var offset = 0;
  32486. // Ensure that subdivisionSize is a multiple of 3
  32487. while (subdivisionSize % 3 !== 0) {
  32488. subdivisionSize++;
  32489. }
  32490. this.releaseSubMeshes();
  32491. for (var index = 0; index < count; index++) {
  32492. if (offset >= totalIndices) {
  32493. break;
  32494. }
  32495. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32496. offset += subdivisionSize;
  32497. }
  32498. this.synchronizeInstances();
  32499. };
  32500. /**
  32501. * Copy a FloatArray into a specific associated vertex buffer
  32502. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32503. * - BABYLON.VertexBuffer.PositionKind
  32504. * - BABYLON.VertexBuffer.UVKind
  32505. * - BABYLON.VertexBuffer.UV2Kind
  32506. * - BABYLON.VertexBuffer.UV3Kind
  32507. * - BABYLON.VertexBuffer.UV4Kind
  32508. * - BABYLON.VertexBuffer.UV5Kind
  32509. * - BABYLON.VertexBuffer.UV6Kind
  32510. * - BABYLON.VertexBuffer.ColorKind
  32511. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32512. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32513. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32514. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32515. * @param data defines the data source
  32516. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32517. * @param stride defines the data stride size (can be null)
  32518. * @returns the current mesh
  32519. */
  32520. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32521. if (updatable === void 0) { updatable = false; }
  32522. if (!this._geometry) {
  32523. var vertexData = new BABYLON.VertexData();
  32524. vertexData.set(data, kind);
  32525. var scene = this.getScene();
  32526. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32527. }
  32528. else {
  32529. this._geometry.setVerticesData(kind, data, updatable, stride);
  32530. }
  32531. return this;
  32532. };
  32533. /**
  32534. * Flags an associated vertex buffer as updatable
  32535. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  32536. * - BABYLON.VertexBuffer.PositionKind
  32537. * - BABYLON.VertexBuffer.UVKind
  32538. * - BABYLON.VertexBuffer.UV2Kind
  32539. * - BABYLON.VertexBuffer.UV3Kind
  32540. * - BABYLON.VertexBuffer.UV4Kind
  32541. * - BABYLON.VertexBuffer.UV5Kind
  32542. * - BABYLON.VertexBuffer.UV6Kind
  32543. * - BABYLON.VertexBuffer.ColorKind
  32544. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32545. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32546. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32547. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32548. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32549. */
  32550. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32551. if (updatable === void 0) { updatable = true; }
  32552. var vb = this.getVertexBuffer(kind);
  32553. if (!vb || vb.isUpdatable() === updatable) {
  32554. return;
  32555. }
  32556. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32557. };
  32558. /**
  32559. * Sets the mesh global Vertex Buffer
  32560. * @param buffer defines the buffer to use
  32561. * @returns the current mesh
  32562. */
  32563. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32564. if (!this._geometry) {
  32565. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32566. }
  32567. this._geometry.setVerticesBuffer(buffer);
  32568. return this;
  32569. };
  32570. /**
  32571. * Update a specific associated vertex buffer
  32572. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32573. * - BABYLON.VertexBuffer.PositionKind
  32574. * - BABYLON.VertexBuffer.UVKind
  32575. * - BABYLON.VertexBuffer.UV2Kind
  32576. * - BABYLON.VertexBuffer.UV3Kind
  32577. * - BABYLON.VertexBuffer.UV4Kind
  32578. * - BABYLON.VertexBuffer.UV5Kind
  32579. * - BABYLON.VertexBuffer.UV6Kind
  32580. * - BABYLON.VertexBuffer.ColorKind
  32581. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32582. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32583. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32584. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32585. * @param data defines the data source
  32586. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  32587. * @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)
  32588. * @returns the current mesh
  32589. */
  32590. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32591. if (!this._geometry) {
  32592. return this;
  32593. }
  32594. if (!makeItUnique) {
  32595. this._geometry.updateVerticesData(kind, data, updateExtends);
  32596. }
  32597. else {
  32598. this.makeGeometryUnique();
  32599. this.updateVerticesData(kind, data, updateExtends, false);
  32600. }
  32601. return this;
  32602. };
  32603. /**
  32604. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32605. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32606. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  32607. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  32608. * @returns the current mesh
  32609. */
  32610. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32611. if (computeNormals === void 0) { computeNormals = true; }
  32612. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32613. if (!positions) {
  32614. return this;
  32615. }
  32616. positionFunction(positions);
  32617. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32618. if (computeNormals) {
  32619. var indices = this.getIndices();
  32620. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32621. if (!normals) {
  32622. return this;
  32623. }
  32624. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32625. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32626. }
  32627. return this;
  32628. };
  32629. /**
  32630. * Creates a un-shared specific occurence of the geometry for the mesh.
  32631. * @returns the current mesh
  32632. */
  32633. Mesh.prototype.makeGeometryUnique = function () {
  32634. if (!this._geometry) {
  32635. return this;
  32636. }
  32637. var oldGeometry = this._geometry;
  32638. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32639. oldGeometry.releaseForMesh(this, true);
  32640. geometry.applyToMesh(this);
  32641. return this;
  32642. };
  32643. /**
  32644. * Set the index buffer of this mesh
  32645. * @param indices defines the source data
  32646. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  32647. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  32648. * @returns the current mesh
  32649. */
  32650. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32651. if (totalVertices === void 0) { totalVertices = null; }
  32652. if (updatable === void 0) { updatable = false; }
  32653. if (!this._geometry) {
  32654. var vertexData = new BABYLON.VertexData();
  32655. vertexData.indices = indices;
  32656. var scene = this.getScene();
  32657. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32658. }
  32659. else {
  32660. this._geometry.setIndices(indices, totalVertices, updatable);
  32661. }
  32662. return this;
  32663. };
  32664. /**
  32665. * Update the current index buffer
  32666. * @param indices defines the source data
  32667. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  32668. * @returns the current mesh
  32669. */
  32670. Mesh.prototype.updateIndices = function (indices, offset) {
  32671. if (!this._geometry) {
  32672. return this;
  32673. }
  32674. this._geometry.updateIndices(indices, offset);
  32675. return this;
  32676. };
  32677. /**
  32678. * Invert the geometry to move from a right handed system to a left handed one.
  32679. * @returns the current mesh
  32680. */
  32681. Mesh.prototype.toLeftHanded = function () {
  32682. if (!this._geometry) {
  32683. return this;
  32684. }
  32685. this._geometry.toLeftHanded();
  32686. return this;
  32687. };
  32688. /** @hidden */
  32689. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32690. if (!this._geometry) {
  32691. return this;
  32692. }
  32693. var engine = this.getScene().getEngine();
  32694. // Wireframe
  32695. var indexToBind;
  32696. if (this._unIndexed) {
  32697. indexToBind = null;
  32698. }
  32699. else {
  32700. switch (fillMode) {
  32701. case BABYLON.Material.PointFillMode:
  32702. indexToBind = null;
  32703. break;
  32704. case BABYLON.Material.WireFrameFillMode:
  32705. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  32706. break;
  32707. default:
  32708. case BABYLON.Material.TriangleFillMode:
  32709. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32710. break;
  32711. }
  32712. }
  32713. // VBOs
  32714. this._geometry._bind(effect, indexToBind);
  32715. return this;
  32716. };
  32717. /** @hidden */
  32718. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32719. if (alternate === void 0) { alternate = false; }
  32720. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32721. return this;
  32722. }
  32723. if (this._onBeforeDrawObservable) {
  32724. this._onBeforeDrawObservable.notifyObservers(this);
  32725. }
  32726. var scene = this.getScene();
  32727. var engine = scene.getEngine();
  32728. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32729. // or triangles as points
  32730. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32731. }
  32732. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32733. // Triangles as wireframe
  32734. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  32735. }
  32736. else {
  32737. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32738. }
  32739. if (scene._isAlternateRenderingEnabled && !alternate) {
  32740. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32741. if (!effect || !scene.activeCamera) {
  32742. return this;
  32743. }
  32744. scene._switchToAlternateCameraConfiguration(true);
  32745. this._effectiveMaterial.bindView(effect);
  32746. this._effectiveMaterial.bindViewProjection(effect);
  32747. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32748. this._draw(subMesh, fillMode, instancesCount, true);
  32749. engine.setViewport(scene.activeCamera.viewport);
  32750. scene._switchToAlternateCameraConfiguration(false);
  32751. this._effectiveMaterial.bindView(effect);
  32752. this._effectiveMaterial.bindViewProjection(effect);
  32753. }
  32754. return this;
  32755. };
  32756. /**
  32757. * Registers for this mesh a javascript function called just before the rendering process
  32758. * @param func defines the function to call before rendering this mesh
  32759. * @returns the current mesh
  32760. */
  32761. Mesh.prototype.registerBeforeRender = function (func) {
  32762. this.onBeforeRenderObservable.add(func);
  32763. return this;
  32764. };
  32765. /**
  32766. * Disposes a previously registered javascript function called before the rendering
  32767. * @param func defines the function to remove
  32768. * @returns the current mesh
  32769. */
  32770. Mesh.prototype.unregisterBeforeRender = function (func) {
  32771. this.onBeforeRenderObservable.removeCallback(func);
  32772. return this;
  32773. };
  32774. /**
  32775. * Registers for this mesh a javascript function called just after the rendering is complete
  32776. * @param func defines the function to call after rendering this mesh
  32777. * @returns the current mesh
  32778. */
  32779. Mesh.prototype.registerAfterRender = function (func) {
  32780. this.onAfterRenderObservable.add(func);
  32781. return this;
  32782. };
  32783. /**
  32784. * Disposes a previously registered javascript function called after the rendering.
  32785. * @param func defines the function to remove
  32786. * @returns the current mesh
  32787. */
  32788. Mesh.prototype.unregisterAfterRender = function (func) {
  32789. this.onAfterRenderObservable.removeCallback(func);
  32790. return this;
  32791. };
  32792. /** @hidden */
  32793. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32794. var scene = this.getScene();
  32795. var batchCache = this._instanceDataStorage.batchCache;
  32796. batchCache.mustReturn = false;
  32797. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32798. batchCache.visibleInstances[subMeshId] = null;
  32799. if (this._instanceDataStorage.visibleInstances) {
  32800. var visibleInstances = this._instanceDataStorage.visibleInstances;
  32801. var currentRenderId = scene.getRenderId();
  32802. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  32803. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  32804. var selfRenderId = this._renderId;
  32805. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32806. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  32807. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32808. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  32809. }
  32810. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  32811. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32812. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  32813. batchCache.mustReturn = true;
  32814. return batchCache;
  32815. }
  32816. if (currentRenderId !== selfRenderId) {
  32817. batchCache.renderSelf[subMeshId] = false;
  32818. }
  32819. }
  32820. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  32821. }
  32822. return batchCache;
  32823. };
  32824. /** @hidden */
  32825. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32826. var visibleInstances = batch.visibleInstances[subMesh._id];
  32827. if (!visibleInstances) {
  32828. return this;
  32829. }
  32830. var matricesCount = visibleInstances.length + 1;
  32831. var bufferSize = matricesCount * 16 * 4;
  32832. var instanceStorage = this._instanceDataStorage;
  32833. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  32834. var instancesBuffer = instanceStorage.instancesBuffer;
  32835. while (instanceStorage.instancesBufferSize < bufferSize) {
  32836. instanceStorage.instancesBufferSize *= 2;
  32837. }
  32838. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  32839. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  32840. }
  32841. var offset = 0;
  32842. var instancesCount = 0;
  32843. var world = this.getWorldMatrix();
  32844. if (batch.renderSelf[subMesh._id]) {
  32845. world.copyToArray(instanceStorage.instancesData, offset);
  32846. offset += 16;
  32847. instancesCount++;
  32848. }
  32849. if (visibleInstances) {
  32850. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32851. var instance = visibleInstances[instanceIndex];
  32852. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  32853. offset += 16;
  32854. instancesCount++;
  32855. }
  32856. }
  32857. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  32858. if (instancesBuffer) {
  32859. instancesBuffer.dispose();
  32860. }
  32861. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  32862. instanceStorage.instancesBuffer = instancesBuffer;
  32863. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32864. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32865. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32866. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32867. }
  32868. else {
  32869. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  32870. }
  32871. this._bind(subMesh, effect, fillMode);
  32872. this._draw(subMesh, fillMode, instancesCount);
  32873. engine.unbindInstanceAttributes();
  32874. return this;
  32875. };
  32876. /** @hidden */
  32877. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32878. var scene = this.getScene();
  32879. var engine = scene.getEngine();
  32880. if (hardwareInstancedRendering) {
  32881. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32882. }
  32883. else {
  32884. if (batch.renderSelf[subMesh._id]) {
  32885. // Draw
  32886. if (onBeforeDraw) {
  32887. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32888. }
  32889. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  32890. }
  32891. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32892. if (visibleInstancesForSubMesh) {
  32893. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32894. var instance = visibleInstancesForSubMesh[instanceIndex];
  32895. // World
  32896. var world = instance.getWorldMatrix();
  32897. if (onBeforeDraw) {
  32898. onBeforeDraw(true, world, effectiveMaterial);
  32899. }
  32900. // Draw
  32901. this._draw(subMesh, fillMode);
  32902. }
  32903. }
  32904. }
  32905. return this;
  32906. };
  32907. /**
  32908. * 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
  32909. * @param subMesh defines the subMesh to render
  32910. * @param enableAlphaMode defines if alpha mode can be changed
  32911. * @returns the current mesh
  32912. */
  32913. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32914. if (this._checkOcclusionQuery()) {
  32915. return this;
  32916. }
  32917. var scene = this.getScene();
  32918. // Managing instances
  32919. var batch = this._getInstancesRenderList(subMesh._id);
  32920. if (batch.mustReturn) {
  32921. return this;
  32922. }
  32923. // Checking geometry state
  32924. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32925. return this;
  32926. }
  32927. if (this._onBeforeRenderObservable) {
  32928. this._onBeforeRenderObservable.notifyObservers(this);
  32929. }
  32930. var engine = scene.getEngine();
  32931. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32932. // Material
  32933. var material = subMesh.getMaterial();
  32934. if (!material) {
  32935. return this;
  32936. }
  32937. this._effectiveMaterial = material;
  32938. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32939. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32940. return this;
  32941. }
  32942. }
  32943. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32944. return this;
  32945. }
  32946. // Alpha mode
  32947. if (enableAlphaMode) {
  32948. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32949. }
  32950. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32951. var step = _a[_i];
  32952. step.action(this, subMesh, batch);
  32953. }
  32954. var effect;
  32955. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32956. effect = subMesh.effect;
  32957. }
  32958. else {
  32959. effect = this._effectiveMaterial.getEffect();
  32960. }
  32961. if (!effect) {
  32962. return this;
  32963. }
  32964. var sideOrientation = this.overrideMaterialSideOrientation;
  32965. if (sideOrientation == null) {
  32966. sideOrientation = this._effectiveMaterial.sideOrientation;
  32967. if (this._getWorldMatrixDeterminant() < 0) {
  32968. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32969. }
  32970. }
  32971. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32972. if (this._effectiveMaterial.forceDepthWrite) {
  32973. engine.setDepthWrite(true);
  32974. }
  32975. // Bind
  32976. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32977. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32978. this._bind(subMesh, effect, fillMode);
  32979. }
  32980. var world = this.getWorldMatrix();
  32981. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32982. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32983. }
  32984. else {
  32985. this._effectiveMaterial.bind(world, this);
  32986. }
  32987. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32988. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32989. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32990. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32991. }
  32992. // Draw
  32993. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32994. // Unbind
  32995. this._effectiveMaterial.unbind();
  32996. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32997. var step = _c[_b];
  32998. step.action(this, subMesh, batch);
  32999. }
  33000. if (this._onAfterRenderObservable) {
  33001. this._onAfterRenderObservable.notifyObservers(this);
  33002. }
  33003. return this;
  33004. };
  33005. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33006. if (isInstance && effectiveMaterial) {
  33007. effectiveMaterial.bindOnlyWorldMatrix(world);
  33008. }
  33009. };
  33010. /**
  33011. * Normalize matrix weights so that all vertices have a total weight set to 1
  33012. */
  33013. Mesh.prototype.cleanMatrixWeights = function () {
  33014. var epsilon = 1e-3;
  33015. var noInfluenceBoneIndex = 0.0;
  33016. if (this.skeleton) {
  33017. noInfluenceBoneIndex = this.skeleton.bones.length;
  33018. }
  33019. else {
  33020. return;
  33021. }
  33022. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33023. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33024. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33025. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33026. var influencers = this.numBoneInfluencers;
  33027. var size = matricesWeights.length;
  33028. for (var i = 0; i < size; i += 4) {
  33029. var weight = 0.0;
  33030. var firstZeroWeight = -1;
  33031. for (var j = 0; j < 4; j++) {
  33032. var w = matricesWeights[i + j];
  33033. weight += w;
  33034. if (w < epsilon && firstZeroWeight < 0) {
  33035. firstZeroWeight = j;
  33036. }
  33037. }
  33038. if (matricesWeightsExtra) {
  33039. for (var j = 0; j < 4; j++) {
  33040. var w = matricesWeightsExtra[i + j];
  33041. weight += w;
  33042. if (w < epsilon && firstZeroWeight < 0) {
  33043. firstZeroWeight = j + 4;
  33044. }
  33045. }
  33046. }
  33047. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33048. firstZeroWeight = influencers - 1;
  33049. }
  33050. if (weight > epsilon) {
  33051. var mweight = 1.0 / weight;
  33052. for (var j = 0; j < 4; j++) {
  33053. matricesWeights[i + j] *= mweight;
  33054. }
  33055. if (matricesWeightsExtra) {
  33056. for (var j = 0; j < 4; j++) {
  33057. matricesWeightsExtra[i + j] *= mweight;
  33058. }
  33059. }
  33060. }
  33061. else {
  33062. if (firstZeroWeight >= 4) {
  33063. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33064. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33065. }
  33066. else {
  33067. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33068. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33069. }
  33070. }
  33071. }
  33072. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33073. if (matricesIndicesExtra) {
  33074. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33075. }
  33076. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33077. if (matricesWeightsExtra) {
  33078. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  33079. }
  33080. };
  33081. /** @hidden */
  33082. Mesh.prototype._checkDelayState = function () {
  33083. var scene = this.getScene();
  33084. if (this._geometry) {
  33085. this._geometry.load(scene);
  33086. }
  33087. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33088. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33089. this._queueLoad(scene);
  33090. }
  33091. return this;
  33092. };
  33093. Mesh.prototype._queueLoad = function (scene) {
  33094. var _this = this;
  33095. scene._addPendingData(this);
  33096. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33097. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33098. if (data instanceof ArrayBuffer) {
  33099. _this._delayLoadingFunction(data, _this);
  33100. }
  33101. else {
  33102. _this._delayLoadingFunction(JSON.parse(data), _this);
  33103. }
  33104. _this.instances.forEach(function (instance) {
  33105. instance._syncSubMeshes();
  33106. });
  33107. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33108. scene._removePendingData(_this);
  33109. }, function () { }, scene.database, getBinaryData);
  33110. return this;
  33111. };
  33112. /**
  33113. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33114. * A mesh is in the frustum if its bounding box intersects the frustum
  33115. * @param frustumPlanes defines the frustum to test
  33116. * @returns true if the mesh is in the frustum planes
  33117. */
  33118. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33119. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33120. return false;
  33121. }
  33122. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33123. return false;
  33124. }
  33125. this._checkDelayState();
  33126. return true;
  33127. };
  33128. /**
  33129. * Sets the mesh material by the material or multiMaterial `id` property
  33130. * @param id is a string identifying the material or the multiMaterial
  33131. * @returns the current mesh
  33132. */
  33133. Mesh.prototype.setMaterialByID = function (id) {
  33134. var materials = this.getScene().materials;
  33135. var index;
  33136. for (index = materials.length - 1; index > -1; index--) {
  33137. if (materials[index].id === id) {
  33138. this.material = materials[index];
  33139. return this;
  33140. }
  33141. }
  33142. // Multi
  33143. var multiMaterials = this.getScene().multiMaterials;
  33144. for (index = multiMaterials.length - 1; index > -1; index--) {
  33145. if (multiMaterials[index].id === id) {
  33146. this.material = multiMaterials[index];
  33147. return this;
  33148. }
  33149. }
  33150. return this;
  33151. };
  33152. /**
  33153. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33154. * @returns an array of IAnimatable
  33155. */
  33156. Mesh.prototype.getAnimatables = function () {
  33157. var results = new Array();
  33158. if (this.material) {
  33159. results.push(this.material);
  33160. }
  33161. if (this.skeleton) {
  33162. results.push(this.skeleton);
  33163. }
  33164. return results;
  33165. };
  33166. /**
  33167. * Modifies the mesh geometry according to the passed transformation matrix.
  33168. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33169. * The mesh normals are modified using the same transformation.
  33170. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33171. * @param transform defines the transform matrix to use
  33172. * @see http://doc.babylonjs.com/resources/baking_transformations
  33173. * @returns the current mesh
  33174. */
  33175. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33176. // Position
  33177. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33178. return this;
  33179. }
  33180. var submeshes = this.subMeshes.splice(0);
  33181. this._resetPointsArrayCache();
  33182. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33183. var temp = new Array();
  33184. var index;
  33185. for (index = 0; index < data.length; index += 3) {
  33186. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33187. }
  33188. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33189. // Normals
  33190. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33191. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33192. temp = [];
  33193. for (index = 0; index < data.length; index += 3) {
  33194. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33195. }
  33196. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33197. }
  33198. // flip faces?
  33199. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33200. this.flipFaces();
  33201. }
  33202. // Restore submeshes
  33203. this.releaseSubMeshes();
  33204. this.subMeshes = submeshes;
  33205. return this;
  33206. };
  33207. /**
  33208. * Modifies the mesh geometry according to its own current World Matrix.
  33209. * The mesh World Matrix is then reset.
  33210. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33211. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33212. * @see http://doc.babylonjs.com/resources/baking_transformations
  33213. * @returns the current mesh
  33214. */
  33215. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33216. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33217. this.scaling.copyFromFloats(1, 1, 1);
  33218. this.position.copyFromFloats(0, 0, 0);
  33219. this.rotation.copyFromFloats(0, 0, 0);
  33220. //only if quaternion is already set
  33221. if (this.rotationQuaternion) {
  33222. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33223. }
  33224. this._worldMatrix = BABYLON.Matrix.Identity();
  33225. return this;
  33226. };
  33227. Object.defineProperty(Mesh.prototype, "_positions", {
  33228. // Cache
  33229. /** @hidden */
  33230. get: function () {
  33231. if (this._geometry) {
  33232. return this._geometry._positions;
  33233. }
  33234. return null;
  33235. },
  33236. enumerable: true,
  33237. configurable: true
  33238. });
  33239. /** @hidden */
  33240. Mesh.prototype._resetPointsArrayCache = function () {
  33241. if (this._geometry) {
  33242. this._geometry._resetPointsArrayCache();
  33243. }
  33244. return this;
  33245. };
  33246. /** @hidden */
  33247. Mesh.prototype._generatePointsArray = function () {
  33248. if (this._geometry) {
  33249. return this._geometry._generatePointsArray();
  33250. }
  33251. return false;
  33252. };
  33253. /**
  33254. * Returns a new Mesh object generated from the current mesh properties.
  33255. * This method must not get confused with createInstance()
  33256. * @param name is a string, the name given to the new mesh
  33257. * @param newParent can be any Node object (default `null`)
  33258. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33259. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33260. * @returns a new mesh
  33261. */
  33262. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33263. if (name === void 0) { name = ""; }
  33264. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33265. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33266. };
  33267. /**
  33268. * Releases resources associated with this mesh.
  33269. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33270. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33271. */
  33272. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33273. var _this = this;
  33274. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33275. this.morphTargetManager = null;
  33276. if (this._geometry) {
  33277. this._geometry.releaseForMesh(this, true);
  33278. }
  33279. if (this._onBeforeDrawObservable) {
  33280. this._onBeforeDrawObservable.clear();
  33281. }
  33282. if (this._onBeforeRenderObservable) {
  33283. this._onBeforeRenderObservable.clear();
  33284. }
  33285. if (this._onAfterRenderObservable) {
  33286. this._onAfterRenderObservable.clear();
  33287. }
  33288. // Sources
  33289. var meshes = this.getScene().meshes;
  33290. meshes.forEach(function (abstractMesh) {
  33291. var mesh = abstractMesh;
  33292. if (mesh._source && mesh._source === _this) {
  33293. mesh._source = null;
  33294. }
  33295. });
  33296. this._source = null;
  33297. // Instances
  33298. if (this._instanceDataStorage.instancesBuffer) {
  33299. this._instanceDataStorage.instancesBuffer.dispose();
  33300. this._instanceDataStorage.instancesBuffer = null;
  33301. }
  33302. while (this.instances.length) {
  33303. this.instances[0].dispose();
  33304. }
  33305. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33306. };
  33307. /**
  33308. * Modifies the mesh geometry according to a displacement map.
  33309. * 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.
  33310. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33311. * @param url is a string, the URL from the image file is to be downloaded.
  33312. * @param minHeight is the lower limit of the displacement.
  33313. * @param maxHeight is the upper limit of the displacement.
  33314. * @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.
  33315. * @param uvOffset is an optional vector2 used to offset UV.
  33316. * @param uvScale is an optional vector2 used to scale UV.
  33317. * @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.
  33318. * @returns the Mesh.
  33319. */
  33320. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33321. var _this = this;
  33322. if (forceUpdate === void 0) { forceUpdate = false; }
  33323. var scene = this.getScene();
  33324. var onload = function (img) {
  33325. // Getting height map data
  33326. var canvas = document.createElement("canvas");
  33327. var context = canvas.getContext("2d");
  33328. var heightMapWidth = img.width;
  33329. var heightMapHeight = img.height;
  33330. canvas.width = heightMapWidth;
  33331. canvas.height = heightMapHeight;
  33332. context.drawImage(img, 0, 0);
  33333. // Create VertexData from map data
  33334. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33335. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33336. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33337. //execute success callback, if set
  33338. if (onSuccess) {
  33339. onSuccess(_this);
  33340. }
  33341. };
  33342. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33343. return this;
  33344. };
  33345. /**
  33346. * Modifies the mesh geometry according to a displacementMap buffer.
  33347. * 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.
  33348. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33349. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33350. * @param heightMapWidth is the width of the buffer image.
  33351. * @param heightMapHeight is the height of the buffer image.
  33352. * @param minHeight is the lower limit of the displacement.
  33353. * @param maxHeight is the upper limit of the displacement.
  33354. * @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.
  33355. * @param uvOffset is an optional vector2 used to offset UV.
  33356. * @param uvScale is an optional vector2 used to scale UV.
  33357. * @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.
  33358. * @returns the Mesh.
  33359. */
  33360. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33361. if (forceUpdate === void 0) { forceUpdate = false; }
  33362. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33363. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33364. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33365. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33366. return this;
  33367. }
  33368. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33369. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33370. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33371. var position = BABYLON.Vector3.Zero();
  33372. var normal = BABYLON.Vector3.Zero();
  33373. var uv = BABYLON.Vector2.Zero();
  33374. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33375. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33376. for (var index = 0; index < positions.length; index += 3) {
  33377. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33378. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33379. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33380. // Compute height
  33381. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33382. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33383. var pos = (u + v * heightMapWidth) * 4;
  33384. var r = buffer[pos] / 255.0;
  33385. var g = buffer[pos + 1] / 255.0;
  33386. var b = buffer[pos + 2] / 255.0;
  33387. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33388. normal.normalize();
  33389. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33390. position = position.add(normal);
  33391. position.toArray(positions, index);
  33392. }
  33393. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33394. if (forceUpdate) {
  33395. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33396. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33397. }
  33398. else {
  33399. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33400. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33401. }
  33402. return this;
  33403. };
  33404. /**
  33405. * Modify the mesh to get a flat shading rendering.
  33406. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33407. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33408. * @returns current mesh
  33409. */
  33410. Mesh.prototype.convertToFlatShadedMesh = function () {
  33411. var kinds = this.getVerticesDataKinds();
  33412. var vbs = {};
  33413. var data = {};
  33414. var newdata = {};
  33415. var updatableNormals = false;
  33416. var kindIndex;
  33417. var kind;
  33418. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33419. kind = kinds[kindIndex];
  33420. var vertexBuffer = this.getVertexBuffer(kind);
  33421. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33422. updatableNormals = vertexBuffer.isUpdatable();
  33423. kinds.splice(kindIndex, 1);
  33424. kindIndex--;
  33425. continue;
  33426. }
  33427. vbs[kind] = vertexBuffer;
  33428. data[kind] = vbs[kind].getData();
  33429. newdata[kind] = [];
  33430. }
  33431. // Save previous submeshes
  33432. var previousSubmeshes = this.subMeshes.slice(0);
  33433. var indices = this.getIndices();
  33434. var totalIndices = this.getTotalIndices();
  33435. // Generating unique vertices per face
  33436. var index;
  33437. for (index = 0; index < totalIndices; index++) {
  33438. var vertexIndex = indices[index];
  33439. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33440. kind = kinds[kindIndex];
  33441. var stride = vbs[kind].getStrideSize();
  33442. for (var offset = 0; offset < stride; offset++) {
  33443. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33444. }
  33445. }
  33446. }
  33447. // Updating faces & normal
  33448. var normals = [];
  33449. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33450. for (index = 0; index < totalIndices; index += 3) {
  33451. indices[index] = index;
  33452. indices[index + 1] = index + 1;
  33453. indices[index + 2] = index + 2;
  33454. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33455. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33456. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33457. var p1p2 = p1.subtract(p2);
  33458. var p3p2 = p3.subtract(p2);
  33459. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33460. // Store same normals for every vertex
  33461. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33462. normals.push(normal.x);
  33463. normals.push(normal.y);
  33464. normals.push(normal.z);
  33465. }
  33466. }
  33467. this.setIndices(indices);
  33468. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33469. // Updating vertex buffers
  33470. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33471. kind = kinds[kindIndex];
  33472. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33473. }
  33474. // Updating submeshes
  33475. this.releaseSubMeshes();
  33476. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33477. var previousOne = previousSubmeshes[submeshIndex];
  33478. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33479. }
  33480. this.synchronizeInstances();
  33481. return this;
  33482. };
  33483. /**
  33484. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33485. * In other words, more vertices, no more indices and a single bigger VBO.
  33486. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33487. * @returns current mesh
  33488. */
  33489. Mesh.prototype.convertToUnIndexedMesh = function () {
  33490. var kinds = this.getVerticesDataKinds();
  33491. var vbs = {};
  33492. var data = {};
  33493. var newdata = {};
  33494. var kindIndex;
  33495. var kind;
  33496. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33497. kind = kinds[kindIndex];
  33498. var vertexBuffer = this.getVertexBuffer(kind);
  33499. vbs[kind] = vertexBuffer;
  33500. data[kind] = vbs[kind].getData();
  33501. newdata[kind] = [];
  33502. }
  33503. // Save previous submeshes
  33504. var previousSubmeshes = this.subMeshes.slice(0);
  33505. var indices = this.getIndices();
  33506. var totalIndices = this.getTotalIndices();
  33507. // Generating unique vertices per face
  33508. var index;
  33509. for (index = 0; index < totalIndices; index++) {
  33510. var vertexIndex = indices[index];
  33511. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33512. kind = kinds[kindIndex];
  33513. var stride = vbs[kind].getStrideSize();
  33514. for (var offset = 0; offset < stride; offset++) {
  33515. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33516. }
  33517. }
  33518. }
  33519. // Updating indices
  33520. for (index = 0; index < totalIndices; index += 3) {
  33521. indices[index] = index;
  33522. indices[index + 1] = index + 1;
  33523. indices[index + 2] = index + 2;
  33524. }
  33525. this.setIndices(indices);
  33526. // Updating vertex buffers
  33527. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33528. kind = kinds[kindIndex];
  33529. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33530. }
  33531. // Updating submeshes
  33532. this.releaseSubMeshes();
  33533. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33534. var previousOne = previousSubmeshes[submeshIndex];
  33535. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33536. }
  33537. this._unIndexed = true;
  33538. this.synchronizeInstances();
  33539. return this;
  33540. };
  33541. /**
  33542. * Inverses facet orientations.
  33543. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33544. * @param flipNormals will also inverts the normals
  33545. * @returns current mesh
  33546. */
  33547. Mesh.prototype.flipFaces = function (flipNormals) {
  33548. if (flipNormals === void 0) { flipNormals = false; }
  33549. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33550. var i;
  33551. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33552. for (i = 0; i < vertex_data.normals.length; i++) {
  33553. vertex_data.normals[i] *= -1;
  33554. }
  33555. }
  33556. if (vertex_data.indices) {
  33557. var temp;
  33558. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33559. // reassign indices
  33560. temp = vertex_data.indices[i + 1];
  33561. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33562. vertex_data.indices[i + 2] = temp;
  33563. }
  33564. }
  33565. vertex_data.applyToMesh(this);
  33566. return this;
  33567. };
  33568. // Instances
  33569. /**
  33570. * Creates a new InstancedMesh object from the mesh model.
  33571. * Warning : this method is not supported for Line mesh and LineSystem
  33572. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33573. * @param name defines the name of the new instance
  33574. * @returns a new InstancedMesh
  33575. */
  33576. Mesh.prototype.createInstance = function (name) {
  33577. return new BABYLON.InstancedMesh(name, this);
  33578. };
  33579. /**
  33580. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33581. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33582. * @returns the current mesh
  33583. */
  33584. Mesh.prototype.synchronizeInstances = function () {
  33585. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33586. var instance = this.instances[instanceIndex];
  33587. instance._syncSubMeshes();
  33588. }
  33589. return this;
  33590. };
  33591. /**
  33592. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33593. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33594. * This should be used together with the simplification to avoid disappearing triangles.
  33595. * @param successCallback an optional success callback to be called after the optimization finished.
  33596. * @returns the current mesh
  33597. */
  33598. Mesh.prototype.optimizeIndices = function (successCallback) {
  33599. var _this = this;
  33600. var indices = this.getIndices();
  33601. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33602. if (!positions || !indices) {
  33603. return this;
  33604. }
  33605. var vectorPositions = new Array();
  33606. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33607. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33608. }
  33609. var dupes = new Array();
  33610. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33611. var realPos = vectorPositions.length - 1 - iteration;
  33612. var testedPosition = vectorPositions[realPos];
  33613. for (var j = 0; j < realPos; ++j) {
  33614. var againstPosition = vectorPositions[j];
  33615. if (testedPosition.equals(againstPosition)) {
  33616. dupes[realPos] = j;
  33617. break;
  33618. }
  33619. }
  33620. }, function () {
  33621. for (var i = 0; i < indices.length; ++i) {
  33622. indices[i] = dupes[indices[i]] || indices[i];
  33623. }
  33624. //indices are now reordered
  33625. var originalSubMeshes = _this.subMeshes.slice(0);
  33626. _this.setIndices(indices);
  33627. _this.subMeshes = originalSubMeshes;
  33628. if (successCallback) {
  33629. successCallback(_this);
  33630. }
  33631. });
  33632. return this;
  33633. };
  33634. /**
  33635. * Serialize current mesh
  33636. * @param serializationObject defines the object which will receive the serialization data
  33637. */
  33638. Mesh.prototype.serialize = function (serializationObject) {
  33639. serializationObject.name = this.name;
  33640. serializationObject.id = this.id;
  33641. serializationObject.type = this.getClassName();
  33642. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33643. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33644. }
  33645. serializationObject.position = this.position.asArray();
  33646. if (this.rotationQuaternion) {
  33647. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33648. }
  33649. else if (this.rotation) {
  33650. serializationObject.rotation = this.rotation.asArray();
  33651. }
  33652. serializationObject.scaling = this.scaling.asArray();
  33653. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33654. serializationObject.isEnabled = this.isEnabled(false);
  33655. serializationObject.isVisible = this.isVisible;
  33656. serializationObject.infiniteDistance = this.infiniteDistance;
  33657. serializationObject.pickable = this.isPickable;
  33658. serializationObject.receiveShadows = this.receiveShadows;
  33659. serializationObject.billboardMode = this.billboardMode;
  33660. serializationObject.visibility = this.visibility;
  33661. serializationObject.checkCollisions = this.checkCollisions;
  33662. serializationObject.isBlocker = this.isBlocker;
  33663. // Parent
  33664. if (this.parent) {
  33665. serializationObject.parentId = this.parent.id;
  33666. }
  33667. // Geometry
  33668. serializationObject.isUnIndexed = this.isUnIndexed;
  33669. var geometry = this._geometry;
  33670. if (geometry) {
  33671. var geometryId = geometry.id;
  33672. serializationObject.geometryId = geometryId;
  33673. // SubMeshes
  33674. serializationObject.subMeshes = [];
  33675. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33676. var subMesh = this.subMeshes[subIndex];
  33677. serializationObject.subMeshes.push({
  33678. materialIndex: subMesh.materialIndex,
  33679. verticesStart: subMesh.verticesStart,
  33680. verticesCount: subMesh.verticesCount,
  33681. indexStart: subMesh.indexStart,
  33682. indexCount: subMesh.indexCount
  33683. });
  33684. }
  33685. }
  33686. // Material
  33687. if (this.material) {
  33688. serializationObject.materialId = this.material.id;
  33689. }
  33690. else {
  33691. this.material = null;
  33692. }
  33693. // Morph targets
  33694. if (this.morphTargetManager) {
  33695. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33696. }
  33697. // Skeleton
  33698. if (this.skeleton) {
  33699. serializationObject.skeletonId = this.skeleton.id;
  33700. }
  33701. // Physics
  33702. //TODO implement correct serialization for physics impostors.
  33703. var impostor = this.getPhysicsImpostor();
  33704. if (impostor) {
  33705. serializationObject.physicsMass = impostor.getParam("mass");
  33706. serializationObject.physicsFriction = impostor.getParam("friction");
  33707. serializationObject.physicsRestitution = impostor.getParam("mass");
  33708. serializationObject.physicsImpostor = impostor.type;
  33709. }
  33710. // Metadata
  33711. if (this.metadata) {
  33712. serializationObject.metadata = this.metadata;
  33713. }
  33714. // Instances
  33715. serializationObject.instances = [];
  33716. for (var index = 0; index < this.instances.length; index++) {
  33717. var instance = this.instances[index];
  33718. if (instance.doNotSerialize) {
  33719. continue;
  33720. }
  33721. var serializationInstance = {
  33722. name: instance.name,
  33723. id: instance.id,
  33724. position: instance.position.asArray(),
  33725. scaling: instance.scaling.asArray()
  33726. };
  33727. if (instance.parent) {
  33728. serializationInstance.parentId = instance.parent.id;
  33729. }
  33730. if (instance.rotationQuaternion) {
  33731. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33732. }
  33733. else if (instance.rotation) {
  33734. serializationInstance.rotation = instance.rotation.asArray();
  33735. }
  33736. serializationObject.instances.push(serializationInstance);
  33737. // Animations
  33738. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33739. serializationInstance.ranges = instance.serializeAnimationRanges();
  33740. }
  33741. //
  33742. // Animations
  33743. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33744. serializationObject.ranges = this.serializeAnimationRanges();
  33745. // Layer mask
  33746. serializationObject.layerMask = this.layerMask;
  33747. // Alpha
  33748. serializationObject.alphaIndex = this.alphaIndex;
  33749. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33750. // Overlay
  33751. serializationObject.overlayAlpha = this.overlayAlpha;
  33752. serializationObject.overlayColor = this.overlayColor.asArray();
  33753. serializationObject.renderOverlay = this.renderOverlay;
  33754. // Fog
  33755. serializationObject.applyFog = this.applyFog;
  33756. // Action Manager
  33757. if (this.actionManager) {
  33758. serializationObject.actions = this.actionManager.serialize(this.name);
  33759. }
  33760. };
  33761. /** @hidden */
  33762. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33763. if (!this.geometry) {
  33764. return;
  33765. }
  33766. this._markSubMeshesAsAttributesDirty();
  33767. var morphTargetManager = this._morphTargetManager;
  33768. if (morphTargetManager && morphTargetManager.vertexCount) {
  33769. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33770. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33771. this.morphTargetManager = null;
  33772. return;
  33773. }
  33774. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33775. var morphTarget = morphTargetManager.getActiveTarget(index);
  33776. var positions = morphTarget.getPositions();
  33777. if (!positions) {
  33778. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33779. return;
  33780. }
  33781. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33782. var normals = morphTarget.getNormals();
  33783. if (normals) {
  33784. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33785. }
  33786. var tangents = morphTarget.getTangents();
  33787. if (tangents) {
  33788. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33789. }
  33790. }
  33791. }
  33792. else {
  33793. var index = 0;
  33794. // Positions
  33795. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33796. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33797. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33798. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33799. }
  33800. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33801. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33802. }
  33803. index++;
  33804. }
  33805. }
  33806. };
  33807. // Statics
  33808. /**
  33809. * Returns a new Mesh object parsed from the source provided.
  33810. * @param parsedMesh is the source
  33811. * @param scene defines the hosting scene
  33812. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  33813. * @returns a new Mesh
  33814. */
  33815. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33816. var mesh;
  33817. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33818. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33819. }
  33820. else {
  33821. mesh = new Mesh(parsedMesh.name, scene);
  33822. }
  33823. mesh.id = parsedMesh.id;
  33824. if (BABYLON.Tags) {
  33825. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33826. }
  33827. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33828. if (parsedMesh.metadata !== undefined) {
  33829. mesh.metadata = parsedMesh.metadata;
  33830. }
  33831. if (parsedMesh.rotationQuaternion) {
  33832. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33833. }
  33834. else if (parsedMesh.rotation) {
  33835. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33836. }
  33837. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33838. if (parsedMesh.localMatrix) {
  33839. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33840. }
  33841. else if (parsedMesh.pivotMatrix) {
  33842. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33843. }
  33844. mesh.setEnabled(parsedMesh.isEnabled);
  33845. mesh.isVisible = parsedMesh.isVisible;
  33846. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33847. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33848. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33849. if (parsedMesh.applyFog !== undefined) {
  33850. mesh.applyFog = parsedMesh.applyFog;
  33851. }
  33852. if (parsedMesh.pickable !== undefined) {
  33853. mesh.isPickable = parsedMesh.pickable;
  33854. }
  33855. if (parsedMesh.alphaIndex !== undefined) {
  33856. mesh.alphaIndex = parsedMesh.alphaIndex;
  33857. }
  33858. mesh.receiveShadows = parsedMesh.receiveShadows;
  33859. mesh.billboardMode = parsedMesh.billboardMode;
  33860. if (parsedMesh.visibility !== undefined) {
  33861. mesh.visibility = parsedMesh.visibility;
  33862. }
  33863. mesh.checkCollisions = parsedMesh.checkCollisions;
  33864. if (parsedMesh.isBlocker !== undefined) {
  33865. mesh.isBlocker = parsedMesh.isBlocker;
  33866. }
  33867. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33868. // freezeWorldMatrix
  33869. if (parsedMesh.freezeWorldMatrix) {
  33870. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33871. }
  33872. // Parent
  33873. if (parsedMesh.parentId) {
  33874. mesh._waitingParentId = parsedMesh.parentId;
  33875. }
  33876. // Actions
  33877. if (parsedMesh.actions !== undefined) {
  33878. mesh._waitingActions = parsedMesh.actions;
  33879. }
  33880. // Overlay
  33881. if (parsedMesh.overlayAlpha !== undefined) {
  33882. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33883. }
  33884. if (parsedMesh.overlayColor !== undefined) {
  33885. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33886. }
  33887. if (parsedMesh.renderOverlay !== undefined) {
  33888. mesh.renderOverlay = parsedMesh.renderOverlay;
  33889. }
  33890. // Geometry
  33891. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33892. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33893. if (parsedMesh.delayLoadingFile) {
  33894. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33895. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33896. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33897. if (parsedMesh._binaryInfo) {
  33898. mesh._binaryInfo = parsedMesh._binaryInfo;
  33899. }
  33900. mesh._delayInfo = [];
  33901. if (parsedMesh.hasUVs) {
  33902. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33903. }
  33904. if (parsedMesh.hasUVs2) {
  33905. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33906. }
  33907. if (parsedMesh.hasUVs3) {
  33908. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33909. }
  33910. if (parsedMesh.hasUVs4) {
  33911. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33912. }
  33913. if (parsedMesh.hasUVs5) {
  33914. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33915. }
  33916. if (parsedMesh.hasUVs6) {
  33917. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33918. }
  33919. if (parsedMesh.hasColors) {
  33920. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33921. }
  33922. if (parsedMesh.hasMatricesIndices) {
  33923. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33924. }
  33925. if (parsedMesh.hasMatricesWeights) {
  33926. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33927. }
  33928. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33929. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33930. mesh._checkDelayState();
  33931. }
  33932. }
  33933. else {
  33934. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33935. }
  33936. // Material
  33937. if (parsedMesh.materialId) {
  33938. mesh.setMaterialByID(parsedMesh.materialId);
  33939. }
  33940. else {
  33941. mesh.material = null;
  33942. }
  33943. // Morph targets
  33944. if (parsedMesh.morphTargetManagerId > -1) {
  33945. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33946. }
  33947. // Skeleton
  33948. if (parsedMesh.skeletonId > -1) {
  33949. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33950. if (parsedMesh.numBoneInfluencers) {
  33951. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33952. }
  33953. }
  33954. // Animations
  33955. if (parsedMesh.animations) {
  33956. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33957. var parsedAnimation = parsedMesh.animations[animationIndex];
  33958. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33959. }
  33960. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33961. }
  33962. if (parsedMesh.autoAnimate) {
  33963. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33964. }
  33965. // Layer Mask
  33966. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33967. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33968. }
  33969. else {
  33970. mesh.layerMask = 0x0FFFFFFF;
  33971. }
  33972. // Physics
  33973. if (parsedMesh.physicsImpostor) {
  33974. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33975. mass: parsedMesh.physicsMass,
  33976. friction: parsedMesh.physicsFriction,
  33977. restitution: parsedMesh.physicsRestitution
  33978. }, scene);
  33979. }
  33980. // Instances
  33981. if (parsedMesh.instances) {
  33982. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33983. var parsedInstance = parsedMesh.instances[index];
  33984. var instance = mesh.createInstance(parsedInstance.name);
  33985. if (parsedInstance.id) {
  33986. instance.id = parsedInstance.id;
  33987. }
  33988. if (BABYLON.Tags) {
  33989. if (parsedInstance.tags) {
  33990. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33991. }
  33992. else {
  33993. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33994. }
  33995. }
  33996. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33997. if (parsedInstance.parentId) {
  33998. instance._waitingParentId = parsedInstance.parentId;
  33999. }
  34000. if (parsedInstance.rotationQuaternion) {
  34001. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34002. }
  34003. else if (parsedInstance.rotation) {
  34004. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34005. }
  34006. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34007. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34008. instance.checkCollisions = parsedInstance.checkCollisions;
  34009. }
  34010. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34011. instance.isPickable = parsedInstance.pickable;
  34012. }
  34013. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34014. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34015. }
  34016. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34017. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34018. }
  34019. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34020. instance.alphaIndex = parsedInstance.alphaIndex;
  34021. }
  34022. // Physics
  34023. if (parsedInstance.physicsImpostor) {
  34024. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34025. mass: parsedInstance.physicsMass,
  34026. friction: parsedInstance.physicsFriction,
  34027. restitution: parsedInstance.physicsRestitution
  34028. }, scene);
  34029. }
  34030. // Animation
  34031. if (parsedInstance.animations) {
  34032. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34033. parsedAnimation = parsedInstance.animations[animationIndex];
  34034. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34035. }
  34036. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34037. if (parsedInstance.autoAnimate) {
  34038. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34039. }
  34040. }
  34041. }
  34042. }
  34043. return mesh;
  34044. };
  34045. /**
  34046. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34047. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34048. * @param name defines the name of the mesh to create
  34049. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34050. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34051. * @param closePath creates a seam between the first and the last points of each path of the path array
  34052. * @param offset is taken in account only if the `pathArray` is containing a single path
  34053. * @param scene defines the hosting scene
  34054. * @param updatable defines if the mesh must be flagged as updatable
  34055. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34056. * @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)
  34057. * @returns a new Mesh
  34058. */
  34059. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34060. if (closeArray === void 0) { closeArray = false; }
  34061. if (updatable === void 0) { updatable = false; }
  34062. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34063. pathArray: pathArray,
  34064. closeArray: closeArray,
  34065. closePath: closePath,
  34066. offset: offset,
  34067. updatable: updatable,
  34068. sideOrientation: sideOrientation,
  34069. instance: instance
  34070. }, scene);
  34071. };
  34072. /**
  34073. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34074. * @param name defines the name of the mesh to create
  34075. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34076. * @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
  34077. * @param scene defines the hosting scene
  34078. * @param updatable defines if the mesh must be flagged as updatable
  34079. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34080. * @returns a new Mesh
  34081. */
  34082. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34083. if (scene === void 0) { scene = null; }
  34084. var options = {
  34085. radius: radius,
  34086. tessellation: tessellation,
  34087. sideOrientation: sideOrientation,
  34088. updatable: updatable
  34089. };
  34090. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34091. };
  34092. /**
  34093. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34094. * @param name defines the name of the mesh to create
  34095. * @param size sets the size (float) of each box side (default 1)
  34096. * @param scene defines the hosting scene
  34097. * @param updatable defines if the mesh must be flagged as updatable
  34098. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34099. * @returns a new Mesh
  34100. */
  34101. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34102. if (scene === void 0) { scene = null; }
  34103. var options = {
  34104. size: size,
  34105. sideOrientation: sideOrientation,
  34106. updatable: updatable
  34107. };
  34108. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34109. };
  34110. /**
  34111. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34112. * @param name defines the name of the mesh to create
  34113. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34114. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34115. * @param scene defines the hosting scene
  34116. * @param updatable defines if the mesh must be flagged as updatable
  34117. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34118. * @returns a new Mesh
  34119. */
  34120. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34121. var options = {
  34122. segments: segments,
  34123. diameterX: diameter,
  34124. diameterY: diameter,
  34125. diameterZ: diameter,
  34126. sideOrientation: sideOrientation,
  34127. updatable: updatable
  34128. };
  34129. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34130. };
  34131. /**
  34132. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34133. * @param name defines the name of the mesh to create
  34134. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34135. * @param diameterTop set the top cap diameter (floats, default 1)
  34136. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34137. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34138. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34139. * @param scene defines the hosting scene
  34140. * @param updatable defines if the mesh must be flagged as updatable
  34141. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34142. * @returns a new Mesh
  34143. */
  34144. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34145. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34146. if (scene !== undefined) {
  34147. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34148. updatable = scene;
  34149. }
  34150. scene = subdivisions;
  34151. subdivisions = 1;
  34152. }
  34153. var options = {
  34154. height: height,
  34155. diameterTop: diameterTop,
  34156. diameterBottom: diameterBottom,
  34157. tessellation: tessellation,
  34158. subdivisions: subdivisions,
  34159. sideOrientation: sideOrientation,
  34160. updatable: updatable
  34161. };
  34162. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34163. };
  34164. // Torus (Code from SharpDX.org)
  34165. /**
  34166. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34167. * @param name defines the name of the mesh to create
  34168. * @param diameter sets the diameter size (float) of the torus (default 1)
  34169. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34170. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34171. * @param scene defines the hosting scene
  34172. * @param updatable defines if the mesh must be flagged as updatable
  34173. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34174. * @returns a new Mesh
  34175. */
  34176. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34177. var options = {
  34178. diameter: diameter,
  34179. thickness: thickness,
  34180. tessellation: tessellation,
  34181. sideOrientation: sideOrientation,
  34182. updatable: updatable
  34183. };
  34184. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34185. };
  34186. /**
  34187. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34188. * @param name defines the name of the mesh to create
  34189. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34190. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34191. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34192. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34193. * @param p the number of windings on X axis (positive integers, default 2)
  34194. * @param q the number of windings on Y axis (positive integers, default 3)
  34195. * @param scene defines the hosting scene
  34196. * @param updatable defines if the mesh must be flagged as updatable
  34197. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34198. * @returns a new Mesh
  34199. */
  34200. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34201. var options = {
  34202. radius: radius,
  34203. tube: tube,
  34204. radialSegments: radialSegments,
  34205. tubularSegments: tubularSegments,
  34206. p: p,
  34207. q: q,
  34208. sideOrientation: sideOrientation,
  34209. updatable: updatable
  34210. };
  34211. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34212. };
  34213. /**
  34214. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34215. * @param name defines the name of the mesh to create
  34216. * @param points is an array successive Vector3
  34217. * @param scene defines the hosting scene
  34218. * @param updatable defines if the mesh must be flagged as updatable
  34219. * @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).
  34220. * @returns a new Mesh
  34221. */
  34222. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34223. if (scene === void 0) { scene = null; }
  34224. if (updatable === void 0) { updatable = false; }
  34225. if (instance === void 0) { instance = null; }
  34226. var options = {
  34227. points: points,
  34228. updatable: updatable,
  34229. instance: instance
  34230. };
  34231. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34232. };
  34233. /**
  34234. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34235. * @param name defines the name of the mesh to create
  34236. * @param points is an array successive Vector3
  34237. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34238. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34239. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34240. * @param scene defines the hosting scene
  34241. * @param updatable defines if the mesh must be flagged as updatable
  34242. * @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)
  34243. * @returns a new Mesh
  34244. */
  34245. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34246. if (scene === void 0) { scene = null; }
  34247. var options = {
  34248. points: points,
  34249. dashSize: dashSize,
  34250. gapSize: gapSize,
  34251. dashNb: dashNb,
  34252. updatable: updatable,
  34253. instance: instance
  34254. };
  34255. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34256. };
  34257. /**
  34258. * Creates a polygon mesh.
  34259. * Please consider using the same method from the MeshBuilder class instead.
  34260. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34261. * 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.
  34262. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34264. * Remember you can only change the shape positions, not their number when updating a polygon.
  34265. */
  34266. /**
  34267. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34268. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34269. * @param name defines the name of the mesh to create
  34270. * @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
  34271. * @param scene defines the hosting scene
  34272. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34273. * @param updatable defines if the mesh must be flagged as updatable
  34274. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34275. * @returns a new Mesh
  34276. */
  34277. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34278. var options = {
  34279. shape: shape,
  34280. holes: holes,
  34281. updatable: updatable,
  34282. sideOrientation: sideOrientation
  34283. };
  34284. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34285. };
  34286. /**
  34287. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34288. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34289. * @param name defines the name of the mesh to create
  34290. * @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
  34291. * @param depth defines the height of extrusion
  34292. * @param scene defines the hosting scene
  34293. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34294. * @param updatable defines if the mesh must be flagged as updatable
  34295. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34296. * @returns a new Mesh
  34297. */
  34298. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34299. var options = {
  34300. shape: shape,
  34301. holes: holes,
  34302. depth: depth,
  34303. updatable: updatable,
  34304. sideOrientation: sideOrientation
  34305. };
  34306. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34307. };
  34308. /**
  34309. * Creates an extruded shape mesh.
  34310. * 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
  34311. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34312. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34313. * @param name defines the name of the mesh to create
  34314. * @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
  34315. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34316. * @param scale is the value to scale the shape
  34317. * @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
  34318. * @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
  34319. * @param scene defines the hosting scene
  34320. * @param updatable defines if the mesh must be flagged as updatable
  34321. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34322. * @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)
  34323. * @returns a new Mesh
  34324. */
  34325. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34326. if (scene === void 0) { scene = null; }
  34327. var options = {
  34328. shape: shape,
  34329. path: path,
  34330. scale: scale,
  34331. rotation: rotation,
  34332. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34333. sideOrientation: sideOrientation,
  34334. instance: instance,
  34335. updatable: updatable
  34336. };
  34337. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34338. };
  34339. /**
  34340. * Creates an custom extruded shape mesh.
  34341. * The custom extrusion is a parametric shape.
  34342. * It has no predefined shape. Its final shape will depend on the input parameters.
  34343. * Please consider using the same method from the MeshBuilder class instead
  34344. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34345. * @param name defines the name of the mesh to create
  34346. * @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
  34347. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34348. * @param scaleFunction is a custom Javascript function called on each path point
  34349. * @param rotationFunction is a custom Javascript function called on each path point
  34350. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34351. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34352. * @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
  34353. * @param scene defines the hosting scene
  34354. * @param updatable defines if the mesh must be flagged as updatable
  34355. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34356. * @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)
  34357. * @returns a new Mesh
  34358. */
  34359. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34360. var options = {
  34361. shape: shape,
  34362. path: path,
  34363. scaleFunction: scaleFunction,
  34364. rotationFunction: rotationFunction,
  34365. ribbonCloseArray: ribbonCloseArray,
  34366. ribbonClosePath: ribbonClosePath,
  34367. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34368. sideOrientation: sideOrientation,
  34369. instance: instance,
  34370. updatable: updatable
  34371. };
  34372. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34373. };
  34374. /**
  34375. * Creates lathe mesh.
  34376. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34377. * Please consider using the same method from the MeshBuilder class instead
  34378. * @param name defines the name of the mesh to create
  34379. * @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
  34380. * @param radius is the radius value of the lathe
  34381. * @param tessellation is the side number of the lathe.
  34382. * @param scene defines the hosting scene
  34383. * @param updatable defines if the mesh must be flagged as updatable
  34384. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34385. * @returns a new Mesh
  34386. */
  34387. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34388. var options = {
  34389. shape: shape,
  34390. radius: radius,
  34391. tessellation: tessellation,
  34392. sideOrientation: sideOrientation,
  34393. updatable: updatable
  34394. };
  34395. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34396. };
  34397. /**
  34398. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  34399. * @param name defines the name of the mesh to create
  34400. * @param size sets the size (float) of both sides of the plane at once (default 1)
  34401. * @param scene defines the hosting scene
  34402. * @param updatable defines if the mesh must be flagged as updatable
  34403. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34404. * @returns a new Mesh
  34405. */
  34406. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34407. var options = {
  34408. size: size,
  34409. width: size,
  34410. height: size,
  34411. sideOrientation: sideOrientation,
  34412. updatable: updatable
  34413. };
  34414. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34415. };
  34416. /**
  34417. * Creates a ground mesh.
  34418. * Please consider using the same method from the MeshBuilder class instead
  34419. * @param name defines the name of the mesh to create
  34420. * @param width set the width of the ground
  34421. * @param height set the height of the ground
  34422. * @param subdivisions sets the number of subdivisions per side
  34423. * @param scene defines the hosting scene
  34424. * @param updatable defines if the mesh must be flagged as updatable
  34425. * @returns a new Mesh
  34426. */
  34427. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34428. var options = {
  34429. width: width,
  34430. height: height,
  34431. subdivisions: subdivisions,
  34432. updatable: updatable
  34433. };
  34434. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34435. };
  34436. /**
  34437. * Creates a tiled ground mesh.
  34438. * Please consider using the same method from the MeshBuilder class instead
  34439. * @param name defines the name of the mesh to create
  34440. * @param xmin set the ground minimum X coordinate
  34441. * @param zmin set the ground minimum Y coordinate
  34442. * @param xmax set the ground maximum X coordinate
  34443. * @param zmax set the ground maximum Z coordinate
  34444. * @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
  34445. * @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
  34446. * @param scene defines the hosting scene
  34447. * @param updatable defines if the mesh must be flagged as updatable
  34448. * @returns a new Mesh
  34449. */
  34450. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34451. var options = {
  34452. xmin: xmin,
  34453. zmin: zmin,
  34454. xmax: xmax,
  34455. zmax: zmax,
  34456. subdivisions: subdivisions,
  34457. precision: precision,
  34458. updatable: updatable
  34459. };
  34460. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34461. };
  34462. /**
  34463. * Creates a ground mesh from a height map.
  34464. * Please consider using the same method from the MeshBuilder class instead
  34465. * @see http://doc.babylonjs.com/babylon101/height_map
  34466. * @param name defines the name of the mesh to create
  34467. * @param url sets the URL of the height map image resource
  34468. * @param width set the ground width size
  34469. * @param height set the ground height size
  34470. * @param subdivisions sets the number of subdivision per side
  34471. * @param minHeight is the minimum altitude on the ground
  34472. * @param maxHeight is the maximum altitude on the ground
  34473. * @param scene defines the hosting scene
  34474. * @param updatable defines if the mesh must be flagged as updatable
  34475. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  34476. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  34477. * @returns a new Mesh
  34478. */
  34479. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  34480. var options = {
  34481. width: width,
  34482. height: height,
  34483. subdivisions: subdivisions,
  34484. minHeight: minHeight,
  34485. maxHeight: maxHeight,
  34486. updatable: updatable,
  34487. onReady: onReady,
  34488. alphaFilter: alphaFilter
  34489. };
  34490. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34491. };
  34492. /**
  34493. * Creates a tube mesh.
  34494. * The tube is a parametric shape.
  34495. * It has no predefined shape. Its final shape will depend on the input parameters.
  34496. * Please consider using the same method from the MeshBuilder class instead
  34497. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34498. * @param name defines the name of the mesh to create
  34499. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  34500. * @param radius sets the tube radius size
  34501. * @param tessellation is the number of sides on the tubular surface
  34502. * @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
  34503. * @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
  34504. * @param scene defines the hosting scene
  34505. * @param updatable defines if the mesh must be flagged as updatable
  34506. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34507. * @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)
  34508. * @returns a new Mesh
  34509. */
  34510. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34511. var options = {
  34512. path: path,
  34513. radius: radius,
  34514. tessellation: tessellation,
  34515. radiusFunction: radiusFunction,
  34516. arc: 1,
  34517. cap: cap,
  34518. updatable: updatable,
  34519. sideOrientation: sideOrientation,
  34520. instance: instance
  34521. };
  34522. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34523. };
  34524. /**
  34525. * Creates a polyhedron mesh.
  34526. * Please consider using the same method from the MeshBuilder class instead.
  34527. * * 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
  34528. * * The parameter `size` (positive float, default 1) sets the polygon size
  34529. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  34530. * * 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`
  34531. * * 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
  34532. * * 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)`)
  34533. * * 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
  34534. * * 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
  34535. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34536. * * 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
  34537. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34538. * @param name defines the name of the mesh to create
  34539. * @param options defines the options used to create the mesh
  34540. * @param scene defines the hosting scene
  34541. * @returns a new Mesh
  34542. */
  34543. Mesh.CreatePolyhedron = function (name, options, scene) {
  34544. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34545. };
  34546. /**
  34547. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  34548. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  34549. * * 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`)
  34550. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  34551. * * 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
  34552. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34553. * * 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
  34554. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34555. * @param name defines the name of the mesh
  34556. * @param options defines the options used to create the mesh
  34557. * @param scene defines the hosting scene
  34558. * @returns a new Mesh
  34559. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  34560. */
  34561. Mesh.CreateIcoSphere = function (name, options, scene) {
  34562. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34563. };
  34564. /**
  34565. * Creates a decal mesh.
  34566. * Please consider using the same method from the MeshBuilder class instead.
  34567. * A decal is a mesh usually applied as a model onto the surface of another mesh
  34568. * @param name defines the name of the mesh
  34569. * @param sourceMesh defines the mesh receiving the decal
  34570. * @param position sets the position of the decal in world coordinates
  34571. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  34572. * @param size sets the decal scaling
  34573. * @param angle sets the angle to rotate the decal
  34574. * @returns a new Mesh
  34575. */
  34576. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34577. var options = {
  34578. position: position,
  34579. normal: normal,
  34580. size: size,
  34581. angle: angle
  34582. };
  34583. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34584. };
  34585. // Skeletons
  34586. /**
  34587. * Prepare internal position array for software CPU skinning
  34588. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  34589. */
  34590. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34591. if (!this._sourcePositions) {
  34592. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34593. if (!source) {
  34594. return this._sourcePositions;
  34595. }
  34596. this._sourcePositions = new Float32Array(source);
  34597. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34598. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34599. }
  34600. }
  34601. return this._sourcePositions;
  34602. };
  34603. /**
  34604. * Prepare internal normal array for software CPU skinning
  34605. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34606. */
  34607. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34608. if (!this._sourceNormals) {
  34609. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34610. if (!source) {
  34611. return this._sourceNormals;
  34612. }
  34613. this._sourceNormals = new Float32Array(source);
  34614. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34615. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34616. }
  34617. }
  34618. return this._sourceNormals;
  34619. };
  34620. /**
  34621. * Updates the vertex buffer by applying transformation from the bones
  34622. * @param skeleton defines the skeleton to apply to current mesh
  34623. * @returns the current mesh
  34624. */
  34625. Mesh.prototype.applySkeleton = function (skeleton) {
  34626. if (!this.geometry) {
  34627. return this;
  34628. }
  34629. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  34630. return this;
  34631. }
  34632. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  34633. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34634. return this;
  34635. }
  34636. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34637. return this;
  34638. }
  34639. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34640. return this;
  34641. }
  34642. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34643. return this;
  34644. }
  34645. if (!this._sourcePositions) {
  34646. var submeshes = this.subMeshes.slice();
  34647. this.setPositionsForCPUSkinning();
  34648. this.subMeshes = submeshes;
  34649. }
  34650. if (!this._sourceNormals) {
  34651. this.setNormalsForCPUSkinning();
  34652. }
  34653. // positionsData checks for not being Float32Array will only pass at most once
  34654. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34655. if (!positionsData) {
  34656. return this;
  34657. }
  34658. if (!(positionsData instanceof Float32Array)) {
  34659. positionsData = new Float32Array(positionsData);
  34660. }
  34661. // normalsData checks for not being Float32Array will only pass at most once
  34662. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34663. if (!normalsData) {
  34664. return this;
  34665. }
  34666. if (!(normalsData instanceof Float32Array)) {
  34667. normalsData = new Float32Array(normalsData);
  34668. }
  34669. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34670. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34671. if (!matricesWeightsData || !matricesIndicesData) {
  34672. return this;
  34673. }
  34674. var needExtras = this.numBoneInfluencers > 4;
  34675. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34676. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34677. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34678. var tempVector3 = BABYLON.Vector3.Zero();
  34679. var finalMatrix = new BABYLON.Matrix();
  34680. var tempMatrix = new BABYLON.Matrix();
  34681. var matWeightIdx = 0;
  34682. var inf;
  34683. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34684. var weight;
  34685. for (inf = 0; inf < 4; inf++) {
  34686. weight = matricesWeightsData[matWeightIdx + inf];
  34687. if (weight > 0) {
  34688. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34689. finalMatrix.addToSelf(tempMatrix);
  34690. }
  34691. }
  34692. if (needExtras) {
  34693. for (inf = 0; inf < 4; inf++) {
  34694. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34695. if (weight > 0) {
  34696. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34697. finalMatrix.addToSelf(tempMatrix);
  34698. }
  34699. }
  34700. }
  34701. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34702. tempVector3.toArray(positionsData, index);
  34703. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34704. tempVector3.toArray(normalsData, index);
  34705. finalMatrix.reset();
  34706. }
  34707. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34708. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34709. return this;
  34710. };
  34711. // Tools
  34712. /**
  34713. * 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
  34714. * @param meshes defines the list of meshes to scan
  34715. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  34716. */
  34717. Mesh.MinMax = function (meshes) {
  34718. var minVector = null;
  34719. var maxVector = null;
  34720. meshes.forEach(function (mesh, index, array) {
  34721. var boundingInfo = mesh.getBoundingInfo();
  34722. var boundingBox = boundingInfo.boundingBox;
  34723. if (!minVector || !maxVector) {
  34724. minVector = boundingBox.minimumWorld;
  34725. maxVector = boundingBox.maximumWorld;
  34726. }
  34727. else {
  34728. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34729. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34730. }
  34731. });
  34732. if (!minVector || !maxVector) {
  34733. return {
  34734. min: BABYLON.Vector3.Zero(),
  34735. max: BABYLON.Vector3.Zero()
  34736. };
  34737. }
  34738. return {
  34739. min: minVector,
  34740. max: maxVector
  34741. };
  34742. };
  34743. /**
  34744. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  34745. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  34746. * @returns a vector3
  34747. */
  34748. Mesh.Center = function (meshesOrMinMaxVector) {
  34749. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34750. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34751. };
  34752. /**
  34753. * Merge the array of meshes into a single mesh for performance reasons.
  34754. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  34755. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  34756. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  34757. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34758. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  34759. * @returns a new mesh
  34760. */
  34761. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34762. if (disposeSource === void 0) { disposeSource = true; }
  34763. var index;
  34764. if (!allow32BitsIndices) {
  34765. var totalVertices = 0;
  34766. // Counting vertices
  34767. for (index = 0; index < meshes.length; index++) {
  34768. if (meshes[index]) {
  34769. totalVertices += meshes[index].getTotalVertices();
  34770. if (totalVertices > 65536) {
  34771. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34772. return null;
  34773. }
  34774. }
  34775. }
  34776. }
  34777. // Merge
  34778. var vertexData = null;
  34779. var otherVertexData;
  34780. var indiceArray = new Array();
  34781. var source = null;
  34782. for (index = 0; index < meshes.length; index++) {
  34783. if (meshes[index]) {
  34784. var wm = meshes[index].computeWorldMatrix(true);
  34785. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34786. otherVertexData.transform(wm);
  34787. if (vertexData) {
  34788. vertexData.merge(otherVertexData, allow32BitsIndices);
  34789. }
  34790. else {
  34791. vertexData = otherVertexData;
  34792. source = meshes[index];
  34793. }
  34794. if (subdivideWithSubMeshes) {
  34795. indiceArray.push(meshes[index].getTotalIndices());
  34796. }
  34797. }
  34798. }
  34799. source = source;
  34800. if (!meshSubclass) {
  34801. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34802. }
  34803. vertexData.applyToMesh(meshSubclass);
  34804. // Setting properties
  34805. meshSubclass.material = source.material;
  34806. meshSubclass.checkCollisions = source.checkCollisions;
  34807. // Cleaning
  34808. if (disposeSource) {
  34809. for (index = 0; index < meshes.length; index++) {
  34810. if (meshes[index]) {
  34811. meshes[index].dispose();
  34812. }
  34813. }
  34814. }
  34815. // Subdivide
  34816. if (subdivideWithSubMeshes) {
  34817. //-- removal of global submesh
  34818. meshSubclass.releaseSubMeshes();
  34819. index = 0;
  34820. var offset = 0;
  34821. //-- apply subdivision according to index table
  34822. while (index < indiceArray.length) {
  34823. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34824. offset += indiceArray[index];
  34825. index++;
  34826. }
  34827. }
  34828. return meshSubclass;
  34829. };
  34830. // Consts
  34831. /**
  34832. * Mesh side orientation : usually the external or front surface
  34833. */
  34834. Mesh.FRONTSIDE = 0;
  34835. /**
  34836. * Mesh side orientation : usually the internal or back surface
  34837. */
  34838. Mesh.BACKSIDE = 1;
  34839. /**
  34840. * Mesh side orientation : both internal and external or front and back surfaces
  34841. */
  34842. Mesh.DOUBLESIDE = 2;
  34843. /**
  34844. * Mesh side orientation : by default, `FRONTSIDE`
  34845. */
  34846. Mesh.DEFAULTSIDE = 0;
  34847. /**
  34848. * Mesh cap setting : no cap
  34849. */
  34850. Mesh.NO_CAP = 0;
  34851. /**
  34852. * Mesh cap setting : one cap at the beginning of the mesh
  34853. */
  34854. Mesh.CAP_START = 1;
  34855. /**
  34856. * Mesh cap setting : one cap at the end of the mesh
  34857. */
  34858. Mesh.CAP_END = 2;
  34859. /**
  34860. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34861. */
  34862. Mesh.CAP_ALL = 3;
  34863. return Mesh;
  34864. }(BABYLON.AbstractMesh));
  34865. BABYLON.Mesh = Mesh;
  34866. })(BABYLON || (BABYLON = {}));
  34867. //# sourceMappingURL=babylon.mesh.js.map
  34868. var BABYLON;
  34869. (function (BABYLON) {
  34870. /**
  34871. * Base class for submeshes
  34872. */
  34873. var BaseSubMesh = /** @class */ (function () {
  34874. function BaseSubMesh() {
  34875. }
  34876. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34877. /**
  34878. * Gets associated effect
  34879. */
  34880. get: function () {
  34881. return this._materialEffect;
  34882. },
  34883. enumerable: true,
  34884. configurable: true
  34885. });
  34886. /**
  34887. * Sets associated effect (effect used to render this submesh)
  34888. * @param effect defines the effect to associate with
  34889. * @param defines defines the set of defines used to compile this effect
  34890. */
  34891. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34892. if (defines === void 0) { defines = null; }
  34893. if (this._materialEffect === effect) {
  34894. if (!effect) {
  34895. this._materialDefines = null;
  34896. }
  34897. return;
  34898. }
  34899. this._materialDefines = defines;
  34900. this._materialEffect = effect;
  34901. };
  34902. return BaseSubMesh;
  34903. }());
  34904. BABYLON.BaseSubMesh = BaseSubMesh;
  34905. /**
  34906. * Defines a subdivision inside a mesh
  34907. */
  34908. var SubMesh = /** @class */ (function (_super) {
  34909. __extends(SubMesh, _super);
  34910. /**
  34911. * Creates a new submesh
  34912. * @param materialIndex defines the material index to use
  34913. * @param verticesStart defines vertex index start
  34914. * @param verticesCount defines vertices count
  34915. * @param indexStart defines index start
  34916. * @param indexCount defines indices count
  34917. * @param mesh defines the parent mesh
  34918. * @param renderingMesh defines an optional rendering mesh
  34919. * @param createBoundingBox defines if bounding box should be created for this submesh
  34920. */
  34921. function SubMesh(
  34922. /** the material index to use */
  34923. materialIndex,
  34924. /** vertex index start */
  34925. verticesStart,
  34926. /** vertices count */
  34927. verticesCount,
  34928. /** index start */
  34929. indexStart,
  34930. /** indices count */
  34931. indexCount, mesh, renderingMesh, createBoundingBox) {
  34932. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34933. var _this = _super.call(this) || this;
  34934. _this.materialIndex = materialIndex;
  34935. _this.verticesStart = verticesStart;
  34936. _this.verticesCount = verticesCount;
  34937. _this.indexStart = indexStart;
  34938. _this.indexCount = indexCount;
  34939. /** @hidden */
  34940. _this._renderId = 0;
  34941. _this._mesh = mesh;
  34942. _this._renderingMesh = renderingMesh || mesh;
  34943. mesh.subMeshes.push(_this);
  34944. _this._trianglePlanes = [];
  34945. _this._id = mesh.subMeshes.length - 1;
  34946. if (createBoundingBox) {
  34947. _this.refreshBoundingInfo();
  34948. mesh.computeWorldMatrix(true);
  34949. }
  34950. return _this;
  34951. }
  34952. /**
  34953. * Add a new submesh to a mesh
  34954. * @param materialIndex defines the material index to use
  34955. * @param verticesStart defines vertex index start
  34956. * @param verticesCount defines vertices count
  34957. * @param indexStart defines index start
  34958. * @param indexCount defines indices count
  34959. * @param mesh defines the parent mesh
  34960. * @param renderingMesh defines an optional rendering mesh
  34961. * @param createBoundingBox defines if bounding box should be created for this submesh
  34962. * @returns the new submesh
  34963. */
  34964. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34965. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34966. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34967. };
  34968. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34969. /**
  34970. * Returns true if this submesh covers the entire parent mesh
  34971. * @ignorenaming
  34972. */
  34973. get: function () {
  34974. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  34975. },
  34976. enumerable: true,
  34977. configurable: true
  34978. });
  34979. /**
  34980. * Returns the submesh BoudingInfo object
  34981. * @returns current bounding info (or mesh's one if the submesh is global)
  34982. */
  34983. SubMesh.prototype.getBoundingInfo = function () {
  34984. if (this.IsGlobal) {
  34985. return this._mesh.getBoundingInfo();
  34986. }
  34987. return this._boundingInfo;
  34988. };
  34989. /**
  34990. * Sets the submesh BoundingInfo
  34991. * @param boundingInfo defines the new bounding info to use
  34992. * @returns the SubMesh
  34993. */
  34994. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34995. this._boundingInfo = boundingInfo;
  34996. return this;
  34997. };
  34998. /**
  34999. * Returns the mesh of the current submesh
  35000. * @return the parent mesh
  35001. */
  35002. SubMesh.prototype.getMesh = function () {
  35003. return this._mesh;
  35004. };
  35005. /**
  35006. * Returns the rendering mesh of the submesh
  35007. * @returns the rendering mesh (could be different from parent mesh)
  35008. */
  35009. SubMesh.prototype.getRenderingMesh = function () {
  35010. return this._renderingMesh;
  35011. };
  35012. /**
  35013. * Returns the submesh material
  35014. * @returns null or the current material
  35015. */
  35016. SubMesh.prototype.getMaterial = function () {
  35017. var rootMaterial = this._renderingMesh.material;
  35018. if (rootMaterial === null || rootMaterial === undefined) {
  35019. return this._mesh.getScene().defaultMaterial;
  35020. }
  35021. else if (rootMaterial.getSubMaterial) {
  35022. var multiMaterial = rootMaterial;
  35023. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35024. if (this._currentMaterial !== effectiveMaterial) {
  35025. this._currentMaterial = effectiveMaterial;
  35026. this._materialDefines = null;
  35027. }
  35028. return effectiveMaterial;
  35029. }
  35030. return rootMaterial;
  35031. };
  35032. // Methods
  35033. /**
  35034. * Sets a new updated BoundingInfo object to the submesh
  35035. * @returns the SubMesh
  35036. */
  35037. SubMesh.prototype.refreshBoundingInfo = function () {
  35038. this._lastColliderWorldVertices = null;
  35039. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35040. return this;
  35041. }
  35042. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35043. if (!data) {
  35044. this._boundingInfo = this._mesh.getBoundingInfo();
  35045. return this;
  35046. }
  35047. var indices = this._renderingMesh.getIndices();
  35048. var extend;
  35049. //is this the only submesh?
  35050. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35051. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35052. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35053. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35054. }
  35055. else {
  35056. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35057. }
  35058. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35059. return this;
  35060. };
  35061. /** @hidden */
  35062. SubMesh.prototype._checkCollision = function (collider) {
  35063. var boundingInfo = this.getBoundingInfo();
  35064. return boundingInfo._checkCollision(collider);
  35065. };
  35066. /**
  35067. * Updates the submesh BoundingInfo
  35068. * @param world defines the world matrix to use to update the bounding info
  35069. * @returns the submesh
  35070. */
  35071. SubMesh.prototype.updateBoundingInfo = function (world) {
  35072. var boundingInfo = this.getBoundingInfo();
  35073. if (!boundingInfo) {
  35074. this.refreshBoundingInfo();
  35075. boundingInfo = this.getBoundingInfo();
  35076. }
  35077. boundingInfo.update(world);
  35078. return this;
  35079. };
  35080. /**
  35081. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35082. * @param frustumPlanes defines the frustum planes
  35083. * @returns true if the submesh is intersecting with the frustum
  35084. */
  35085. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35086. var boundingInfo = this.getBoundingInfo();
  35087. if (!boundingInfo) {
  35088. return false;
  35089. }
  35090. return boundingInfo.isInFrustum(frustumPlanes);
  35091. };
  35092. /**
  35093. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35094. * @param frustumPlanes defines the frustum planes
  35095. * @returns true if the submesh is inside the frustum
  35096. */
  35097. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35098. var boundingInfo = this.getBoundingInfo();
  35099. if (!boundingInfo) {
  35100. return false;
  35101. }
  35102. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35103. };
  35104. /**
  35105. * Renders the submesh
  35106. * @param enableAlphaMode defines if alpha needs to be used
  35107. * @returns the submesh
  35108. */
  35109. SubMesh.prototype.render = function (enableAlphaMode) {
  35110. this._renderingMesh.render(this, enableAlphaMode);
  35111. return this;
  35112. };
  35113. /**
  35114. * @hidden
  35115. */
  35116. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35117. if (!this._linesIndexBuffer) {
  35118. var linesIndices = [];
  35119. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35120. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35121. }
  35122. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35123. this._linesIndexCount = linesIndices.length;
  35124. }
  35125. return this._linesIndexBuffer;
  35126. };
  35127. /**
  35128. * Checks if the submesh intersects with a ray
  35129. * @param ray defines the ray to test
  35130. * @returns true is the passed ray intersects the submesh bounding box
  35131. */
  35132. SubMesh.prototype.canIntersects = function (ray) {
  35133. var boundingInfo = this.getBoundingInfo();
  35134. if (!boundingInfo) {
  35135. return false;
  35136. }
  35137. return ray.intersectsBox(boundingInfo.boundingBox);
  35138. };
  35139. /**
  35140. * Intersects current submesh with a ray
  35141. * @param ray defines the ray to test
  35142. * @param positions defines mesh's positions array
  35143. * @param indices defines mesh's indices array
  35144. * @param fastCheck defines if only bounding info should be used
  35145. * @returns intersection info or null if no intersection
  35146. */
  35147. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35148. var intersectInfo = null;
  35149. var material = this.getMaterial();
  35150. if (!material) {
  35151. return null;
  35152. }
  35153. switch (material.fillMode) {
  35154. case BABYLON.Material.PointListDrawMode:
  35155. case BABYLON.Material.LineListDrawMode:
  35156. case BABYLON.Material.LineLoopDrawMode:
  35157. case BABYLON.Material.LineStripDrawMode:
  35158. case BABYLON.Material.TriangleFanDrawMode:
  35159. case BABYLON.Material.TriangleStripDrawMode:
  35160. return null;
  35161. }
  35162. // LineMesh first as it's also a Mesh...
  35163. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  35164. var lineMesh = this._mesh;
  35165. // Line test
  35166. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35167. var p0 = positions[indices[index]];
  35168. var p1 = positions[indices[index + 1]];
  35169. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  35170. if (length < 0) {
  35171. continue;
  35172. }
  35173. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35174. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35175. if (fastCheck) {
  35176. break;
  35177. }
  35178. }
  35179. }
  35180. }
  35181. else {
  35182. // Triangles test
  35183. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35184. var p0 = positions[indices[index]];
  35185. var p1 = positions[indices[index + 1]];
  35186. var p2 = positions[indices[index + 2]];
  35187. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35188. if (currentIntersectInfo) {
  35189. if (currentIntersectInfo.distance < 0) {
  35190. continue;
  35191. }
  35192. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35193. intersectInfo = currentIntersectInfo;
  35194. intersectInfo.faceId = index / 3;
  35195. if (fastCheck) {
  35196. break;
  35197. }
  35198. }
  35199. }
  35200. }
  35201. }
  35202. return intersectInfo;
  35203. };
  35204. /** @hidden */
  35205. SubMesh.prototype._rebuild = function () {
  35206. if (this._linesIndexBuffer) {
  35207. this._linesIndexBuffer = null;
  35208. }
  35209. };
  35210. // Clone
  35211. /**
  35212. * Creates a new submesh from the passed mesh
  35213. * @param newMesh defines the new hosting mesh
  35214. * @param newRenderingMesh defines an optional rendering mesh
  35215. * @returns the new submesh
  35216. */
  35217. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35218. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35219. if (!this.IsGlobal) {
  35220. var boundingInfo = this.getBoundingInfo();
  35221. if (!boundingInfo) {
  35222. return result;
  35223. }
  35224. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35225. }
  35226. return result;
  35227. };
  35228. // Dispose
  35229. /**
  35230. * Release associated resources
  35231. */
  35232. SubMesh.prototype.dispose = function () {
  35233. if (this._linesIndexBuffer) {
  35234. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35235. this._linesIndexBuffer = null;
  35236. }
  35237. // Remove from mesh
  35238. var index = this._mesh.subMeshes.indexOf(this);
  35239. this._mesh.subMeshes.splice(index, 1);
  35240. };
  35241. // Statics
  35242. /**
  35243. * Creates a new submesh from indices data
  35244. * @param materialIndex the index of the main mesh material
  35245. * @param startIndex the index where to start the copy in the mesh indices array
  35246. * @param indexCount the number of indices to copy then from the startIndex
  35247. * @param mesh the main mesh to create the submesh from
  35248. * @param renderingMesh the optional rendering mesh
  35249. * @returns a new submesh
  35250. */
  35251. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35252. var minVertexIndex = Number.MAX_VALUE;
  35253. var maxVertexIndex = -Number.MAX_VALUE;
  35254. renderingMesh = (renderingMesh || mesh);
  35255. var indices = renderingMesh.getIndices();
  35256. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35257. var vertexIndex = indices[index];
  35258. if (vertexIndex < minVertexIndex)
  35259. minVertexIndex = vertexIndex;
  35260. if (vertexIndex > maxVertexIndex)
  35261. maxVertexIndex = vertexIndex;
  35262. }
  35263. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35264. };
  35265. return SubMesh;
  35266. }(BaseSubMesh));
  35267. BABYLON.SubMesh = SubMesh;
  35268. })(BABYLON || (BABYLON = {}));
  35269. //# sourceMappingURL=babylon.subMesh.js.map
  35270. var __assign = (this && this.__assign) || function () {
  35271. __assign = Object.assign || function(t) {
  35272. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35273. s = arguments[i];
  35274. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35275. t[p] = s[p];
  35276. }
  35277. return t;
  35278. };
  35279. return __assign.apply(this, arguments);
  35280. };
  35281. var BABYLON;
  35282. (function (BABYLON) {
  35283. /**
  35284. * Manages the defines for the Material
  35285. */
  35286. var MaterialDefines = /** @class */ (function () {
  35287. function MaterialDefines() {
  35288. this._isDirty = true;
  35289. /** @hidden */
  35290. this._areLightsDirty = true;
  35291. /** @hidden */
  35292. this._areAttributesDirty = true;
  35293. /** @hidden */
  35294. this._areTexturesDirty = true;
  35295. /** @hidden */
  35296. this._areFresnelDirty = true;
  35297. /** @hidden */
  35298. this._areMiscDirty = true;
  35299. /** @hidden */
  35300. this._areImageProcessingDirty = true;
  35301. /** @hidden */
  35302. this._normals = false;
  35303. /** @hidden */
  35304. this._uvs = false;
  35305. /** @hidden */
  35306. this._needNormals = false;
  35307. /** @hidden */
  35308. this._needUVs = false;
  35309. }
  35310. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35311. /**
  35312. * Specifies if the material needs to be re-calculated
  35313. */
  35314. get: function () {
  35315. return this._isDirty;
  35316. },
  35317. enumerable: true,
  35318. configurable: true
  35319. });
  35320. /**
  35321. * Marks the material to indicate that it has been re-calculated
  35322. */
  35323. MaterialDefines.prototype.markAsProcessed = function () {
  35324. this._isDirty = false;
  35325. this._areAttributesDirty = false;
  35326. this._areTexturesDirty = false;
  35327. this._areFresnelDirty = false;
  35328. this._areLightsDirty = false;
  35329. this._areMiscDirty = false;
  35330. this._areImageProcessingDirty = false;
  35331. };
  35332. /**
  35333. * Marks the material to indicate that it needs to be re-calculated
  35334. */
  35335. MaterialDefines.prototype.markAsUnprocessed = function () {
  35336. this._isDirty = true;
  35337. };
  35338. /**
  35339. * Marks the material to indicate all of its defines need to be re-calculated
  35340. */
  35341. MaterialDefines.prototype.markAllAsDirty = function () {
  35342. this._areTexturesDirty = true;
  35343. this._areAttributesDirty = true;
  35344. this._areLightsDirty = true;
  35345. this._areFresnelDirty = true;
  35346. this._areMiscDirty = true;
  35347. this._areImageProcessingDirty = true;
  35348. this._isDirty = true;
  35349. };
  35350. /**
  35351. * Marks the material to indicate that image processing needs to be re-calculated
  35352. */
  35353. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35354. this._areImageProcessingDirty = true;
  35355. this._isDirty = true;
  35356. };
  35357. /**
  35358. * Marks the material to indicate the lights need to be re-calculated
  35359. */
  35360. MaterialDefines.prototype.markAsLightDirty = function () {
  35361. this._areLightsDirty = true;
  35362. this._isDirty = true;
  35363. };
  35364. /**
  35365. * Marks the attribute state as changed
  35366. */
  35367. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35368. this._areAttributesDirty = true;
  35369. this._isDirty = true;
  35370. };
  35371. /**
  35372. * Marks the texture state as changed
  35373. */
  35374. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35375. this._areTexturesDirty = true;
  35376. this._isDirty = true;
  35377. };
  35378. /**
  35379. * Marks the fresnel state as changed
  35380. */
  35381. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35382. this._areFresnelDirty = true;
  35383. this._isDirty = true;
  35384. };
  35385. /**
  35386. * Marks the misc state as changed
  35387. */
  35388. MaterialDefines.prototype.markAsMiscDirty = function () {
  35389. this._areMiscDirty = true;
  35390. this._isDirty = true;
  35391. };
  35392. /**
  35393. * Rebuilds the material defines
  35394. */
  35395. MaterialDefines.prototype.rebuild = function () {
  35396. if (this._keys) {
  35397. delete this._keys;
  35398. }
  35399. this._keys = [];
  35400. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35401. var key = _a[_i];
  35402. if (key[0] === "_") {
  35403. continue;
  35404. }
  35405. this._keys.push(key);
  35406. }
  35407. };
  35408. /**
  35409. * Specifies if two material defines are equal
  35410. * @param other - A material define instance to compare to
  35411. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35412. */
  35413. MaterialDefines.prototype.isEqual = function (other) {
  35414. if (this._keys.length !== other._keys.length) {
  35415. return false;
  35416. }
  35417. for (var index = 0; index < this._keys.length; index++) {
  35418. var prop = this._keys[index];
  35419. if (this[prop] !== other[prop]) {
  35420. return false;
  35421. }
  35422. }
  35423. return true;
  35424. };
  35425. /**
  35426. * Clones this instance's defines to another instance
  35427. * @param other - material defines to clone values to
  35428. */
  35429. MaterialDefines.prototype.cloneTo = function (other) {
  35430. if (this._keys.length !== other._keys.length) {
  35431. other._keys = this._keys.slice(0);
  35432. }
  35433. for (var index = 0; index < this._keys.length; index++) {
  35434. var prop = this._keys[index];
  35435. other[prop] = this[prop];
  35436. }
  35437. };
  35438. /**
  35439. * Resets the material define values
  35440. */
  35441. MaterialDefines.prototype.reset = function () {
  35442. for (var index = 0; index < this._keys.length; index++) {
  35443. var prop = this._keys[index];
  35444. var type = typeof this[prop];
  35445. switch (type) {
  35446. case "number":
  35447. this[prop] = 0;
  35448. break;
  35449. case "string":
  35450. this[prop] = "";
  35451. break;
  35452. default:
  35453. this[prop] = false;
  35454. break;
  35455. }
  35456. }
  35457. };
  35458. /**
  35459. * Converts the material define values to a string
  35460. * @returns - String of material define information
  35461. */
  35462. MaterialDefines.prototype.toString = function () {
  35463. var result = "";
  35464. for (var index = 0; index < this._keys.length; index++) {
  35465. var prop = this._keys[index];
  35466. var value = this[prop];
  35467. var type = typeof value;
  35468. switch (type) {
  35469. case "number":
  35470. case "string":
  35471. result += "#define " + prop + " " + value + "\n";
  35472. break;
  35473. default:
  35474. if (value) {
  35475. result += "#define " + prop + "\n";
  35476. }
  35477. break;
  35478. }
  35479. }
  35480. return result;
  35481. };
  35482. return MaterialDefines;
  35483. }());
  35484. BABYLON.MaterialDefines = MaterialDefines;
  35485. /**
  35486. * Base class for the main features of a material in Babylon.js
  35487. */
  35488. var Material = /** @class */ (function () {
  35489. /**
  35490. * Creates a material instance
  35491. * @param name defines the name of the material
  35492. * @param scene defines the scene to reference
  35493. * @param doNotAdd specifies if the material should be added to the scene
  35494. */
  35495. function Material(name, scene, doNotAdd) {
  35496. /**
  35497. * Specifies if the ready state should be checked on each call
  35498. */
  35499. this.checkReadyOnEveryCall = false;
  35500. /**
  35501. * Specifies if the ready state should be checked once
  35502. */
  35503. this.checkReadyOnlyOnce = false;
  35504. /**
  35505. * The state of the material
  35506. */
  35507. this.state = "";
  35508. /**
  35509. * The alpha value of the material
  35510. */
  35511. this._alpha = 1.0;
  35512. /**
  35513. * Specifies if back face culling is enabled
  35514. */
  35515. this._backFaceCulling = true;
  35516. /**
  35517. * Specifies if the material should be serialized
  35518. */
  35519. this.doNotSerialize = false;
  35520. /**
  35521. * Specifies if the effect should be stored on sub meshes
  35522. */
  35523. this.storeEffectOnSubMeshes = false;
  35524. /**
  35525. * An event triggered when the material is disposed
  35526. */
  35527. this.onDisposeObservable = new BABYLON.Observable();
  35528. /**
  35529. * Stores the value of the alpha mode
  35530. */
  35531. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35532. /**
  35533. * Stores the state of the need depth pre-pass value
  35534. */
  35535. this._needDepthPrePass = false;
  35536. /**
  35537. * Specifies if depth writing should be disabled
  35538. */
  35539. this.disableDepthWrite = false;
  35540. /**
  35541. * Specifies if depth writing should be forced
  35542. */
  35543. this.forceDepthWrite = false;
  35544. /**
  35545. * Specifies if there should be a separate pass for culling
  35546. */
  35547. this.separateCullingPass = false;
  35548. /**
  35549. * Stores the state specifing if fog should be enabled
  35550. */
  35551. this._fogEnabled = true;
  35552. /**
  35553. * Stores the size of points
  35554. */
  35555. this.pointSize = 1.0;
  35556. /**
  35557. * Stores the z offset value
  35558. */
  35559. this.zOffset = 0;
  35560. /**
  35561. * @hidden
  35562. * Specifies if the material was previously ready
  35563. */
  35564. this._wasPreviouslyReady = false;
  35565. /**
  35566. * Stores the fill mode state
  35567. */
  35568. this._fillMode = Material.TriangleFillMode;
  35569. this.name = name;
  35570. this.id = name || BABYLON.Tools.RandomId();
  35571. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35572. this.uniqueId = this._scene.getUniqueId();
  35573. if (this._scene.useRightHandedSystem) {
  35574. this.sideOrientation = Material.ClockWiseSideOrientation;
  35575. }
  35576. else {
  35577. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35578. }
  35579. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35580. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35581. if (!doNotAdd) {
  35582. this._scene.materials.push(this);
  35583. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  35584. }
  35585. }
  35586. Object.defineProperty(Material, "TriangleFillMode", {
  35587. /**
  35588. * Returns the triangle fill mode
  35589. */
  35590. get: function () {
  35591. return Material._TriangleFillMode;
  35592. },
  35593. enumerable: true,
  35594. configurable: true
  35595. });
  35596. Object.defineProperty(Material, "WireFrameFillMode", {
  35597. /**
  35598. * Returns the wireframe mode
  35599. */
  35600. get: function () {
  35601. return Material._WireFrameFillMode;
  35602. },
  35603. enumerable: true,
  35604. configurable: true
  35605. });
  35606. Object.defineProperty(Material, "PointFillMode", {
  35607. /**
  35608. * Returns the point fill mode
  35609. */
  35610. get: function () {
  35611. return Material._PointFillMode;
  35612. },
  35613. enumerable: true,
  35614. configurable: true
  35615. });
  35616. Object.defineProperty(Material, "PointListDrawMode", {
  35617. /**
  35618. * Returns the point list draw mode
  35619. */
  35620. get: function () {
  35621. return Material._PointListDrawMode;
  35622. },
  35623. enumerable: true,
  35624. configurable: true
  35625. });
  35626. Object.defineProperty(Material, "LineListDrawMode", {
  35627. /**
  35628. * Returns the line list draw mode
  35629. */
  35630. get: function () {
  35631. return Material._LineListDrawMode;
  35632. },
  35633. enumerable: true,
  35634. configurable: true
  35635. });
  35636. Object.defineProperty(Material, "LineLoopDrawMode", {
  35637. /**
  35638. * Returns the line loop draw mode
  35639. */
  35640. get: function () {
  35641. return Material._LineLoopDrawMode;
  35642. },
  35643. enumerable: true,
  35644. configurable: true
  35645. });
  35646. Object.defineProperty(Material, "LineStripDrawMode", {
  35647. /**
  35648. * Returns the line strip draw mode
  35649. */
  35650. get: function () {
  35651. return Material._LineStripDrawMode;
  35652. },
  35653. enumerable: true,
  35654. configurable: true
  35655. });
  35656. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35657. /**
  35658. * Returns the triangle strip draw mode
  35659. */
  35660. get: function () {
  35661. return Material._TriangleStripDrawMode;
  35662. },
  35663. enumerable: true,
  35664. configurable: true
  35665. });
  35666. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35667. /**
  35668. * Returns the triangle fan draw mode
  35669. */
  35670. get: function () {
  35671. return Material._TriangleFanDrawMode;
  35672. },
  35673. enumerable: true,
  35674. configurable: true
  35675. });
  35676. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35677. /**
  35678. * Returns the clock-wise side orientation
  35679. */
  35680. get: function () {
  35681. return Material._ClockWiseSideOrientation;
  35682. },
  35683. enumerable: true,
  35684. configurable: true
  35685. });
  35686. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35687. /**
  35688. * Returns the counter clock-wise side orientation
  35689. */
  35690. get: function () {
  35691. return Material._CounterClockWiseSideOrientation;
  35692. },
  35693. enumerable: true,
  35694. configurable: true
  35695. });
  35696. Object.defineProperty(Material.prototype, "alpha", {
  35697. /**
  35698. * Gets the alpha value of the material
  35699. */
  35700. get: function () {
  35701. return this._alpha;
  35702. },
  35703. /**
  35704. * Sets the alpha value of the material
  35705. */
  35706. set: function (value) {
  35707. if (this._alpha === value) {
  35708. return;
  35709. }
  35710. this._alpha = value;
  35711. this.markAsDirty(Material.MiscDirtyFlag);
  35712. },
  35713. enumerable: true,
  35714. configurable: true
  35715. });
  35716. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35717. /**
  35718. * Gets the back-face culling state
  35719. */
  35720. get: function () {
  35721. return this._backFaceCulling;
  35722. },
  35723. /**
  35724. * Sets the back-face culling state
  35725. */
  35726. set: function (value) {
  35727. if (this._backFaceCulling === value) {
  35728. return;
  35729. }
  35730. this._backFaceCulling = value;
  35731. this.markAsDirty(Material.TextureDirtyFlag);
  35732. },
  35733. enumerable: true,
  35734. configurable: true
  35735. });
  35736. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  35737. /**
  35738. * Gets a boolean indicating that current material needs to register RTT
  35739. */
  35740. get: function () {
  35741. return false;
  35742. },
  35743. enumerable: true,
  35744. configurable: true
  35745. });
  35746. Object.defineProperty(Material.prototype, "onDispose", {
  35747. /**
  35748. * Called during a dispose event
  35749. */
  35750. set: function (callback) {
  35751. if (this._onDisposeObserver) {
  35752. this.onDisposeObservable.remove(this._onDisposeObserver);
  35753. }
  35754. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35755. },
  35756. enumerable: true,
  35757. configurable: true
  35758. });
  35759. Object.defineProperty(Material.prototype, "onBindObservable", {
  35760. /**
  35761. * An event triggered when the material is bound
  35762. */
  35763. get: function () {
  35764. if (!this._onBindObservable) {
  35765. this._onBindObservable = new BABYLON.Observable();
  35766. }
  35767. return this._onBindObservable;
  35768. },
  35769. enumerable: true,
  35770. configurable: true
  35771. });
  35772. Object.defineProperty(Material.prototype, "onBind", {
  35773. /**
  35774. * Called during a bind event
  35775. */
  35776. set: function (callback) {
  35777. if (this._onBindObserver) {
  35778. this.onBindObservable.remove(this._onBindObserver);
  35779. }
  35780. this._onBindObserver = this.onBindObservable.add(callback);
  35781. },
  35782. enumerable: true,
  35783. configurable: true
  35784. });
  35785. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35786. /**
  35787. * An event triggered when the material is unbound
  35788. */
  35789. get: function () {
  35790. if (!this._onUnBindObservable) {
  35791. this._onUnBindObservable = new BABYLON.Observable();
  35792. }
  35793. return this._onUnBindObservable;
  35794. },
  35795. enumerable: true,
  35796. configurable: true
  35797. });
  35798. Object.defineProperty(Material.prototype, "alphaMode", {
  35799. /**
  35800. * Gets the value of the alpha mode
  35801. */
  35802. get: function () {
  35803. return this._alphaMode;
  35804. },
  35805. /**
  35806. * Sets the value of the alpha mode.
  35807. *
  35808. * | Value | Type | Description |
  35809. * | --- | --- | --- |
  35810. * | 0 | ALPHA_DISABLE | |
  35811. * | 1 | ALPHA_ADD | |
  35812. * | 2 | ALPHA_COMBINE | |
  35813. * | 3 | ALPHA_SUBTRACT | |
  35814. * | 4 | ALPHA_MULTIPLY | |
  35815. * | 5 | ALPHA_MAXIMIZED | |
  35816. * | 6 | ALPHA_ONEONE | |
  35817. * | 7 | ALPHA_PREMULTIPLIED | |
  35818. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35819. * | 9 | ALPHA_INTERPOLATE | |
  35820. * | 10 | ALPHA_SCREENMODE | |
  35821. *
  35822. */
  35823. set: function (value) {
  35824. if (this._alphaMode === value) {
  35825. return;
  35826. }
  35827. this._alphaMode = value;
  35828. this.markAsDirty(Material.TextureDirtyFlag);
  35829. },
  35830. enumerable: true,
  35831. configurable: true
  35832. });
  35833. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35834. /**
  35835. * Gets the depth pre-pass value
  35836. */
  35837. get: function () {
  35838. return this._needDepthPrePass;
  35839. },
  35840. /**
  35841. * Sets the need depth pre-pass value
  35842. */
  35843. set: function (value) {
  35844. if (this._needDepthPrePass === value) {
  35845. return;
  35846. }
  35847. this._needDepthPrePass = value;
  35848. if (this._needDepthPrePass) {
  35849. this.checkReadyOnEveryCall = true;
  35850. }
  35851. },
  35852. enumerable: true,
  35853. configurable: true
  35854. });
  35855. Object.defineProperty(Material.prototype, "fogEnabled", {
  35856. /**
  35857. * Gets the value of the fog enabled state
  35858. */
  35859. get: function () {
  35860. return this._fogEnabled;
  35861. },
  35862. /**
  35863. * Sets the state for enabling fog
  35864. */
  35865. set: function (value) {
  35866. if (this._fogEnabled === value) {
  35867. return;
  35868. }
  35869. this._fogEnabled = value;
  35870. this.markAsDirty(Material.MiscDirtyFlag);
  35871. },
  35872. enumerable: true,
  35873. configurable: true
  35874. });
  35875. Object.defineProperty(Material.prototype, "wireframe", {
  35876. /**
  35877. * Gets a value specifying if wireframe mode is enabled
  35878. */
  35879. get: function () {
  35880. switch (this._fillMode) {
  35881. case Material.WireFrameFillMode:
  35882. case Material.LineListDrawMode:
  35883. case Material.LineLoopDrawMode:
  35884. case Material.LineStripDrawMode:
  35885. return true;
  35886. }
  35887. return this._scene.forceWireframe;
  35888. },
  35889. /**
  35890. * Sets the state of wireframe mode
  35891. */
  35892. set: function (value) {
  35893. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35894. },
  35895. enumerable: true,
  35896. configurable: true
  35897. });
  35898. Object.defineProperty(Material.prototype, "pointsCloud", {
  35899. /**
  35900. * Gets the value specifying if point clouds are enabled
  35901. */
  35902. get: function () {
  35903. switch (this._fillMode) {
  35904. case Material.PointFillMode:
  35905. case Material.PointListDrawMode:
  35906. return true;
  35907. }
  35908. return this._scene.forcePointsCloud;
  35909. },
  35910. /**
  35911. * Sets the state of point cloud mode
  35912. */
  35913. set: function (value) {
  35914. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35915. },
  35916. enumerable: true,
  35917. configurable: true
  35918. });
  35919. Object.defineProperty(Material.prototype, "fillMode", {
  35920. /**
  35921. * Gets the material fill mode
  35922. */
  35923. get: function () {
  35924. return this._fillMode;
  35925. },
  35926. /**
  35927. * Sets the material fill mode
  35928. */
  35929. set: function (value) {
  35930. if (this._fillMode === value) {
  35931. return;
  35932. }
  35933. this._fillMode = value;
  35934. this.markAsDirty(Material.MiscDirtyFlag);
  35935. },
  35936. enumerable: true,
  35937. configurable: true
  35938. });
  35939. /**
  35940. * Returns a string representation of the current material
  35941. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35942. * @returns a string with material information
  35943. */
  35944. Material.prototype.toString = function (fullDetails) {
  35945. var ret = "Name: " + this.name;
  35946. if (fullDetails) {
  35947. }
  35948. return ret;
  35949. };
  35950. /**
  35951. * Gets the class name of the material
  35952. * @returns a string with the class name of the material
  35953. */
  35954. Material.prototype.getClassName = function () {
  35955. return "Material";
  35956. };
  35957. Object.defineProperty(Material.prototype, "isFrozen", {
  35958. /**
  35959. * Specifies if updates for the material been locked
  35960. */
  35961. get: function () {
  35962. return this.checkReadyOnlyOnce;
  35963. },
  35964. enumerable: true,
  35965. configurable: true
  35966. });
  35967. /**
  35968. * Locks updates for the material
  35969. */
  35970. Material.prototype.freeze = function () {
  35971. this.checkReadyOnlyOnce = true;
  35972. };
  35973. /**
  35974. * Unlocks updates for the material
  35975. */
  35976. Material.prototype.unfreeze = function () {
  35977. this.checkReadyOnlyOnce = false;
  35978. };
  35979. /**
  35980. * Specifies if the material is ready to be used
  35981. * @param mesh defines the mesh to check
  35982. * @param useInstances specifies if instances should be used
  35983. * @returns a boolean indicating if the material is ready to be used
  35984. */
  35985. Material.prototype.isReady = function (mesh, useInstances) {
  35986. return true;
  35987. };
  35988. /**
  35989. * Specifies that the submesh is ready to be used
  35990. * @param mesh defines the mesh to check
  35991. * @param subMesh defines which submesh to check
  35992. * @param useInstances specifies that instances should be used
  35993. * @returns a boolean indicating that the submesh is ready or not
  35994. */
  35995. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35996. return false;
  35997. };
  35998. /**
  35999. * Returns the material effect
  36000. * @returns the effect associated with the material
  36001. */
  36002. Material.prototype.getEffect = function () {
  36003. return this._effect;
  36004. };
  36005. /**
  36006. * Returns the current scene
  36007. * @returns a Scene
  36008. */
  36009. Material.prototype.getScene = function () {
  36010. return this._scene;
  36011. };
  36012. /**
  36013. * Specifies if the material will require alpha blending
  36014. * @returns a boolean specifying if alpha blending is needed
  36015. */
  36016. Material.prototype.needAlphaBlending = function () {
  36017. return (this.alpha < 1.0);
  36018. };
  36019. /**
  36020. * Specifies if the mesh will require alpha blending
  36021. * @param mesh defines the mesh to check
  36022. * @returns a boolean specifying if alpha blending is needed for the mesh
  36023. */
  36024. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36025. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36026. };
  36027. /**
  36028. * Specifies if this material should be rendered in alpha test mode
  36029. * @returns a boolean specifying if an alpha test is needed.
  36030. */
  36031. Material.prototype.needAlphaTesting = function () {
  36032. return false;
  36033. };
  36034. /**
  36035. * Gets the texture used for the alpha test
  36036. * @returns the texture to use for alpha testing
  36037. */
  36038. Material.prototype.getAlphaTestTexture = function () {
  36039. return null;
  36040. };
  36041. /**
  36042. * Marks the material to indicate that it needs to be re-calculated
  36043. */
  36044. Material.prototype.markDirty = function () {
  36045. this._wasPreviouslyReady = false;
  36046. };
  36047. /** @hidden */
  36048. Material.prototype._preBind = function (effect, overrideOrientation) {
  36049. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36050. var engine = this._scene.getEngine();
  36051. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36052. var reverse = orientation === Material.ClockWiseSideOrientation;
  36053. engine.enableEffect(effect ? effect : this._effect);
  36054. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36055. return reverse;
  36056. };
  36057. /**
  36058. * Binds the material to the mesh
  36059. * @param world defines the world transformation matrix
  36060. * @param mesh defines the mesh to bind the material to
  36061. */
  36062. Material.prototype.bind = function (world, mesh) {
  36063. };
  36064. /**
  36065. * Binds the submesh to the material
  36066. * @param world defines the world transformation matrix
  36067. * @param mesh defines the mesh containing the submesh
  36068. * @param subMesh defines the submesh to bind the material to
  36069. */
  36070. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36071. };
  36072. /**
  36073. * Binds the world matrix to the material
  36074. * @param world defines the world transformation matrix
  36075. */
  36076. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36077. };
  36078. /**
  36079. * Binds the scene's uniform buffer to the effect.
  36080. * @param effect defines the effect to bind to the scene uniform buffer
  36081. * @param sceneUbo defines the uniform buffer storing scene data
  36082. */
  36083. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36084. sceneUbo.bindToEffect(effect, "Scene");
  36085. };
  36086. /**
  36087. * Binds the view matrix to the effect
  36088. * @param effect defines the effect to bind the view matrix to
  36089. */
  36090. Material.prototype.bindView = function (effect) {
  36091. if (!this._useUBO) {
  36092. effect.setMatrix("view", this.getScene().getViewMatrix());
  36093. }
  36094. else {
  36095. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36096. }
  36097. };
  36098. /**
  36099. * Binds the view projection matrix to the effect
  36100. * @param effect defines the effect to bind the view projection matrix to
  36101. */
  36102. Material.prototype.bindViewProjection = function (effect) {
  36103. if (!this._useUBO) {
  36104. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36105. }
  36106. else {
  36107. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36108. }
  36109. };
  36110. /**
  36111. * Specifies if material alpha testing should be turned on for the mesh
  36112. * @param mesh defines the mesh to check
  36113. */
  36114. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36115. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36116. };
  36117. /**
  36118. * Processes to execute after binding the material to a mesh
  36119. * @param mesh defines the rendered mesh
  36120. */
  36121. Material.prototype._afterBind = function (mesh) {
  36122. this._scene._cachedMaterial = this;
  36123. if (mesh) {
  36124. this._scene._cachedVisibility = mesh.visibility;
  36125. }
  36126. else {
  36127. this._scene._cachedVisibility = 1;
  36128. }
  36129. if (this._onBindObservable && mesh) {
  36130. this._onBindObservable.notifyObservers(mesh);
  36131. }
  36132. if (this.disableDepthWrite) {
  36133. var engine = this._scene.getEngine();
  36134. this._cachedDepthWriteState = engine.getDepthWrite();
  36135. engine.setDepthWrite(false);
  36136. }
  36137. };
  36138. /**
  36139. * Unbinds the material from the mesh
  36140. */
  36141. Material.prototype.unbind = function () {
  36142. if (this._onUnBindObservable) {
  36143. this._onUnBindObservable.notifyObservers(this);
  36144. }
  36145. if (this.disableDepthWrite) {
  36146. var engine = this._scene.getEngine();
  36147. engine.setDepthWrite(this._cachedDepthWriteState);
  36148. }
  36149. };
  36150. /**
  36151. * Gets the active textures from the material
  36152. * @returns an array of textures
  36153. */
  36154. Material.prototype.getActiveTextures = function () {
  36155. return [];
  36156. };
  36157. /**
  36158. * Specifies if the material uses a texture
  36159. * @param texture defines the texture to check against the material
  36160. * @returns a boolean specifying if the material uses the texture
  36161. */
  36162. Material.prototype.hasTexture = function (texture) {
  36163. return false;
  36164. };
  36165. /**
  36166. * Makes a duplicate of the material, and gives it a new name
  36167. * @param name defines the new name for the duplicated material
  36168. * @returns the cloned material
  36169. */
  36170. Material.prototype.clone = function (name) {
  36171. return null;
  36172. };
  36173. /**
  36174. * Gets the meshes bound to the material
  36175. * @returns an array of meshes bound to the material
  36176. */
  36177. Material.prototype.getBindedMeshes = function () {
  36178. var result = new Array();
  36179. for (var index = 0; index < this._scene.meshes.length; index++) {
  36180. var mesh = this._scene.meshes[index];
  36181. if (mesh.material === this) {
  36182. result.push(mesh);
  36183. }
  36184. }
  36185. return result;
  36186. };
  36187. /**
  36188. * Force shader compilation
  36189. * @param mesh defines the mesh associated with this material
  36190. * @param onCompiled defines a function to execute once the material is compiled
  36191. * @param options defines the options to configure the compilation
  36192. */
  36193. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36194. var _this = this;
  36195. var localOptions = __assign({ clipPlane: false }, options);
  36196. var subMesh = new BABYLON.BaseSubMesh();
  36197. var scene = this.getScene();
  36198. var checkReady = function () {
  36199. if (!_this._scene || !_this._scene.getEngine()) {
  36200. return;
  36201. }
  36202. if (subMesh._materialDefines) {
  36203. subMesh._materialDefines._renderId = -1;
  36204. }
  36205. var clipPlaneState = scene.clipPlane;
  36206. if (localOptions.clipPlane) {
  36207. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36208. }
  36209. if (_this.storeEffectOnSubMeshes) {
  36210. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36211. if (onCompiled) {
  36212. onCompiled(_this);
  36213. }
  36214. }
  36215. else {
  36216. setTimeout(checkReady, 16);
  36217. }
  36218. }
  36219. else {
  36220. if (_this.isReady(mesh)) {
  36221. if (onCompiled) {
  36222. onCompiled(_this);
  36223. }
  36224. }
  36225. else {
  36226. setTimeout(checkReady, 16);
  36227. }
  36228. }
  36229. if (localOptions.clipPlane) {
  36230. scene.clipPlane = clipPlaneState;
  36231. }
  36232. };
  36233. checkReady();
  36234. };
  36235. /**
  36236. * Force shader compilation
  36237. * @param mesh defines the mesh that will use this material
  36238. * @param options defines additional options for compiling the shaders
  36239. * @returns a promise that resolves when the compilation completes
  36240. */
  36241. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36242. var _this = this;
  36243. return new Promise(function (resolve) {
  36244. _this.forceCompilation(mesh, function () {
  36245. resolve();
  36246. }, options);
  36247. });
  36248. };
  36249. /**
  36250. * Marks a define in the material to indicate that it needs to be re-computed
  36251. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36252. */
  36253. Material.prototype.markAsDirty = function (flag) {
  36254. if (flag & Material.TextureDirtyFlag) {
  36255. this._markAllSubMeshesAsTexturesDirty();
  36256. }
  36257. if (flag & Material.LightDirtyFlag) {
  36258. this._markAllSubMeshesAsLightsDirty();
  36259. }
  36260. if (flag & Material.FresnelDirtyFlag) {
  36261. this._markAllSubMeshesAsFresnelDirty();
  36262. }
  36263. if (flag & Material.AttributesDirtyFlag) {
  36264. this._markAllSubMeshesAsAttributesDirty();
  36265. }
  36266. if (flag & Material.MiscDirtyFlag) {
  36267. this._markAllSubMeshesAsMiscDirty();
  36268. }
  36269. this.getScene().resetCachedMaterial();
  36270. };
  36271. /**
  36272. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36273. * @param func defines a function which checks material defines against the submeshes
  36274. */
  36275. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36276. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36277. var mesh = _a[_i];
  36278. if (!mesh.subMeshes) {
  36279. continue;
  36280. }
  36281. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36282. var subMesh = _c[_b];
  36283. if (subMesh.getMaterial() !== this) {
  36284. continue;
  36285. }
  36286. if (!subMesh._materialDefines) {
  36287. continue;
  36288. }
  36289. func(subMesh._materialDefines);
  36290. }
  36291. }
  36292. };
  36293. /**
  36294. * Indicates that image processing needs to be re-calculated for all submeshes
  36295. */
  36296. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36297. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36298. };
  36299. /**
  36300. * Indicates that textures need to be re-calculated for all submeshes
  36301. */
  36302. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36303. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36304. };
  36305. /**
  36306. * Indicates that fresnel needs to be re-calculated for all submeshes
  36307. */
  36308. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36309. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36310. };
  36311. /**
  36312. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36313. */
  36314. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36315. this._markAllSubMeshesAsDirty(function (defines) {
  36316. defines.markAsFresnelDirty();
  36317. defines.markAsMiscDirty();
  36318. });
  36319. };
  36320. /**
  36321. * Indicates that lights need to be re-calculated for all submeshes
  36322. */
  36323. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36324. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36325. };
  36326. /**
  36327. * Indicates that attributes need to be re-calculated for all submeshes
  36328. */
  36329. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36330. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36331. };
  36332. /**
  36333. * Indicates that misc needs to be re-calculated for all submeshes
  36334. */
  36335. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36336. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36337. };
  36338. /**
  36339. * Indicates that textures and misc need to be re-calculated for all submeshes
  36340. */
  36341. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36342. this._markAllSubMeshesAsDirty(function (defines) {
  36343. defines.markAsTexturesDirty();
  36344. defines.markAsMiscDirty();
  36345. });
  36346. };
  36347. /**
  36348. * Disposes the material
  36349. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36350. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36351. */
  36352. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36353. // Animations
  36354. this.getScene().stopAnimation(this);
  36355. this.getScene().freeProcessedMaterials();
  36356. // Remove from scene
  36357. var index = this._scene.materials.indexOf(this);
  36358. if (index >= 0) {
  36359. this._scene.materials.splice(index, 1);
  36360. }
  36361. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36362. // Remove from meshes
  36363. for (index = 0; index < this._scene.meshes.length; index++) {
  36364. var mesh = this._scene.meshes[index];
  36365. if (mesh.material === this) {
  36366. mesh.material = null;
  36367. if (mesh.geometry) {
  36368. var geometry = (mesh.geometry);
  36369. if (this.storeEffectOnSubMeshes) {
  36370. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36371. var subMesh = _a[_i];
  36372. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36373. if (forceDisposeEffect && subMesh._materialEffect) {
  36374. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36375. }
  36376. }
  36377. }
  36378. else {
  36379. geometry._releaseVertexArrayObject(this._effect);
  36380. }
  36381. }
  36382. }
  36383. }
  36384. this._uniformBuffer.dispose();
  36385. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36386. if (forceDisposeEffect && this._effect) {
  36387. if (!this.storeEffectOnSubMeshes) {
  36388. this._scene.getEngine()._releaseEffect(this._effect);
  36389. }
  36390. this._effect = null;
  36391. }
  36392. // Callback
  36393. this.onDisposeObservable.notifyObservers(this);
  36394. this.onDisposeObservable.clear();
  36395. if (this._onBindObservable) {
  36396. this._onBindObservable.clear();
  36397. }
  36398. if (this._onUnBindObservable) {
  36399. this._onUnBindObservable.clear();
  36400. }
  36401. };
  36402. /**
  36403. * Serializes this material
  36404. * @returns the serialized material object
  36405. */
  36406. Material.prototype.serialize = function () {
  36407. return BABYLON.SerializationHelper.Serialize(this);
  36408. };
  36409. /**
  36410. * Creates a MultiMaterial from parsed MultiMaterial data.
  36411. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36412. * @param scene defines the hosting scene
  36413. * @returns a new MultiMaterial
  36414. */
  36415. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36416. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36417. multiMaterial.id = parsedMultiMaterial.id;
  36418. if (BABYLON.Tags) {
  36419. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36420. }
  36421. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36422. var subMatId = parsedMultiMaterial.materials[matIndex];
  36423. if (subMatId) {
  36424. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36425. }
  36426. else {
  36427. multiMaterial.subMaterials.push(null);
  36428. }
  36429. }
  36430. return multiMaterial;
  36431. };
  36432. /**
  36433. * Creates a material from parsed material data
  36434. * @param parsedMaterial defines parsed material data
  36435. * @param scene defines the hosting scene
  36436. * @param rootUrl defines the root URL to use to load textures
  36437. * @returns a new material
  36438. */
  36439. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36440. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36441. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36442. }
  36443. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36444. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36445. if (!BABYLON.LegacyPBRMaterial) {
  36446. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36447. return;
  36448. }
  36449. }
  36450. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36451. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36452. };
  36453. // Triangle views
  36454. Material._TriangleFillMode = 0;
  36455. Material._WireFrameFillMode = 1;
  36456. Material._PointFillMode = 2;
  36457. // Draw modes
  36458. Material._PointListDrawMode = 3;
  36459. Material._LineListDrawMode = 4;
  36460. Material._LineLoopDrawMode = 5;
  36461. Material._LineStripDrawMode = 6;
  36462. Material._TriangleStripDrawMode = 7;
  36463. Material._TriangleFanDrawMode = 8;
  36464. /**
  36465. * Stores the clock-wise side orientation
  36466. */
  36467. Material._ClockWiseSideOrientation = 0;
  36468. /**
  36469. * Stores the counter clock-wise side orientation
  36470. */
  36471. Material._CounterClockWiseSideOrientation = 1;
  36472. /**
  36473. * The dirty texture flag value
  36474. */
  36475. Material.TextureDirtyFlag = 1;
  36476. /**
  36477. * The dirty light flag value
  36478. */
  36479. Material.LightDirtyFlag = 2;
  36480. /**
  36481. * The dirty fresnel flag value
  36482. */
  36483. Material.FresnelDirtyFlag = 4;
  36484. /**
  36485. * The dirty attribute flag value
  36486. */
  36487. Material.AttributesDirtyFlag = 8;
  36488. /**
  36489. * The dirty misc flag value
  36490. */
  36491. Material.MiscDirtyFlag = 16;
  36492. /**
  36493. * The all dirty flag value
  36494. */
  36495. Material.AllDirtyFlag = 31;
  36496. __decorate([
  36497. BABYLON.serialize()
  36498. ], Material.prototype, "id", void 0);
  36499. __decorate([
  36500. BABYLON.serialize()
  36501. ], Material.prototype, "uniqueId", void 0);
  36502. __decorate([
  36503. BABYLON.serialize()
  36504. ], Material.prototype, "name", void 0);
  36505. __decorate([
  36506. BABYLON.serialize()
  36507. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36508. __decorate([
  36509. BABYLON.serialize()
  36510. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36511. __decorate([
  36512. BABYLON.serialize()
  36513. ], Material.prototype, "state", void 0);
  36514. __decorate([
  36515. BABYLON.serialize("alpha")
  36516. ], Material.prototype, "_alpha", void 0);
  36517. __decorate([
  36518. BABYLON.serialize("backFaceCulling")
  36519. ], Material.prototype, "_backFaceCulling", void 0);
  36520. __decorate([
  36521. BABYLON.serialize()
  36522. ], Material.prototype, "sideOrientation", void 0);
  36523. __decorate([
  36524. BABYLON.serialize("alphaMode")
  36525. ], Material.prototype, "_alphaMode", void 0);
  36526. __decorate([
  36527. BABYLON.serialize()
  36528. ], Material.prototype, "_needDepthPrePass", void 0);
  36529. __decorate([
  36530. BABYLON.serialize()
  36531. ], Material.prototype, "disableDepthWrite", void 0);
  36532. __decorate([
  36533. BABYLON.serialize()
  36534. ], Material.prototype, "forceDepthWrite", void 0);
  36535. __decorate([
  36536. BABYLON.serialize()
  36537. ], Material.prototype, "separateCullingPass", void 0);
  36538. __decorate([
  36539. BABYLON.serialize("fogEnabled")
  36540. ], Material.prototype, "_fogEnabled", void 0);
  36541. __decorate([
  36542. BABYLON.serialize()
  36543. ], Material.prototype, "pointSize", void 0);
  36544. __decorate([
  36545. BABYLON.serialize()
  36546. ], Material.prototype, "zOffset", void 0);
  36547. __decorate([
  36548. BABYLON.serialize()
  36549. ], Material.prototype, "wireframe", null);
  36550. __decorate([
  36551. BABYLON.serialize()
  36552. ], Material.prototype, "pointsCloud", null);
  36553. __decorate([
  36554. BABYLON.serialize()
  36555. ], Material.prototype, "fillMode", null);
  36556. return Material;
  36557. }());
  36558. BABYLON.Material = Material;
  36559. })(BABYLON || (BABYLON = {}));
  36560. //# sourceMappingURL=babylon.material.js.map
  36561. var BABYLON;
  36562. (function (BABYLON) {
  36563. /**
  36564. * Uniform buffer objects.
  36565. *
  36566. * Handles blocks of uniform on the GPU.
  36567. *
  36568. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36569. *
  36570. * For more information, please refer to :
  36571. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36572. */
  36573. var UniformBuffer = /** @class */ (function () {
  36574. /**
  36575. * Instantiates a new Uniform buffer objects.
  36576. *
  36577. * Handles blocks of uniform on the GPU.
  36578. *
  36579. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36580. *
  36581. * For more information, please refer to :
  36582. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36583. * @param engine Define the engine the buffer is associated with
  36584. * @param data Define the data contained in the buffer
  36585. * @param dynamic Define if the buffer is updatable
  36586. */
  36587. function UniformBuffer(engine, data, dynamic) {
  36588. this._engine = engine;
  36589. this._noUBO = !engine.supportsUniformBuffers;
  36590. this._dynamic = dynamic;
  36591. this._data = data || [];
  36592. this._uniformLocations = {};
  36593. this._uniformSizes = {};
  36594. this._uniformLocationPointer = 0;
  36595. this._needSync = false;
  36596. if (this._noUBO) {
  36597. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36598. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36599. this.updateFloat = this._updateFloatForEffect;
  36600. this.updateFloat2 = this._updateFloat2ForEffect;
  36601. this.updateFloat3 = this._updateFloat3ForEffect;
  36602. this.updateFloat4 = this._updateFloat4ForEffect;
  36603. this.updateMatrix = this._updateMatrixForEffect;
  36604. this.updateVector3 = this._updateVector3ForEffect;
  36605. this.updateVector4 = this._updateVector4ForEffect;
  36606. this.updateColor3 = this._updateColor3ForEffect;
  36607. this.updateColor4 = this._updateColor4ForEffect;
  36608. }
  36609. else {
  36610. this._engine._uniformBuffers.push(this);
  36611. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36612. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36613. this.updateFloat = this._updateFloatForUniform;
  36614. this.updateFloat2 = this._updateFloat2ForUniform;
  36615. this.updateFloat3 = this._updateFloat3ForUniform;
  36616. this.updateFloat4 = this._updateFloat4ForUniform;
  36617. this.updateMatrix = this._updateMatrixForUniform;
  36618. this.updateVector3 = this._updateVector3ForUniform;
  36619. this.updateVector4 = this._updateVector4ForUniform;
  36620. this.updateColor3 = this._updateColor3ForUniform;
  36621. this.updateColor4 = this._updateColor4ForUniform;
  36622. }
  36623. }
  36624. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36625. /**
  36626. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36627. * or just falling back on setUniformXXX calls.
  36628. */
  36629. get: function () {
  36630. return !this._noUBO;
  36631. },
  36632. enumerable: true,
  36633. configurable: true
  36634. });
  36635. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36636. /**
  36637. * Indicates if the WebGL underlying uniform buffer is in sync
  36638. * with the javascript cache data.
  36639. */
  36640. get: function () {
  36641. return !this._needSync;
  36642. },
  36643. enumerable: true,
  36644. configurable: true
  36645. });
  36646. /**
  36647. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36648. * Also, a dynamic UniformBuffer will disable cache verification and always
  36649. * update the underlying WebGL uniform buffer to the GPU.
  36650. * @returns if Dynamic, otherwise false
  36651. */
  36652. UniformBuffer.prototype.isDynamic = function () {
  36653. return this._dynamic !== undefined;
  36654. };
  36655. /**
  36656. * The data cache on JS side.
  36657. * @returns the underlying data as a float array
  36658. */
  36659. UniformBuffer.prototype.getData = function () {
  36660. return this._bufferData;
  36661. };
  36662. /**
  36663. * The underlying WebGL Uniform buffer.
  36664. * @returns the webgl buffer
  36665. */
  36666. UniformBuffer.prototype.getBuffer = function () {
  36667. return this._buffer;
  36668. };
  36669. /**
  36670. * std140 layout specifies how to align data within an UBO structure.
  36671. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36672. * for specs.
  36673. */
  36674. UniformBuffer.prototype._fillAlignment = function (size) {
  36675. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36676. // and 4x4 matrices
  36677. // TODO : change if other types are used
  36678. var alignment;
  36679. if (size <= 2) {
  36680. alignment = size;
  36681. }
  36682. else {
  36683. alignment = 4;
  36684. }
  36685. if ((this._uniformLocationPointer % alignment) !== 0) {
  36686. var oldPointer = this._uniformLocationPointer;
  36687. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36688. var diff = this._uniformLocationPointer - oldPointer;
  36689. for (var i = 0; i < diff; i++) {
  36690. this._data.push(0);
  36691. }
  36692. }
  36693. };
  36694. /**
  36695. * Adds an uniform in the buffer.
  36696. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36697. * for the layout to be correct !
  36698. * @param name Name of the uniform, as used in the uniform block in the shader.
  36699. * @param size Data size, or data directly.
  36700. */
  36701. UniformBuffer.prototype.addUniform = function (name, size) {
  36702. if (this._noUBO) {
  36703. return;
  36704. }
  36705. if (this._uniformLocations[name] !== undefined) {
  36706. // Already existing uniform
  36707. return;
  36708. }
  36709. // This function must be called in the order of the shader layout !
  36710. // size can be the size of the uniform, or data directly
  36711. var data;
  36712. if (size instanceof Array) {
  36713. data = size;
  36714. size = data.length;
  36715. }
  36716. else {
  36717. size = size;
  36718. data = [];
  36719. // Fill with zeros
  36720. for (var i = 0; i < size; i++) {
  36721. data.push(0);
  36722. }
  36723. }
  36724. this._fillAlignment(size);
  36725. this._uniformSizes[name] = size;
  36726. this._uniformLocations[name] = this._uniformLocationPointer;
  36727. this._uniformLocationPointer += size;
  36728. for (var i = 0; i < size; i++) {
  36729. this._data.push(data[i]);
  36730. }
  36731. this._needSync = true;
  36732. };
  36733. /**
  36734. * Adds a Matrix 4x4 to the uniform buffer.
  36735. * @param name Name of the uniform, as used in the uniform block in the shader.
  36736. * @param mat A 4x4 matrix.
  36737. */
  36738. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36739. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36740. };
  36741. /**
  36742. * Adds a vec2 to the uniform buffer.
  36743. * @param name Name of the uniform, as used in the uniform block in the shader.
  36744. * @param x Define the x component value of the vec2
  36745. * @param y Define the y component value of the vec2
  36746. */
  36747. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36748. var temp = [x, y];
  36749. this.addUniform(name, temp);
  36750. };
  36751. /**
  36752. * Adds a vec3 to the uniform buffer.
  36753. * @param name Name of the uniform, as used in the uniform block in the shader.
  36754. * @param x Define the x component value of the vec3
  36755. * @param y Define the y component value of the vec3
  36756. * @param z Define the z component value of the vec3
  36757. */
  36758. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36759. var temp = [x, y, z];
  36760. this.addUniform(name, temp);
  36761. };
  36762. /**
  36763. * Adds a vec3 to the uniform buffer.
  36764. * @param name Name of the uniform, as used in the uniform block in the shader.
  36765. * @param color Define the vec3 from a Color
  36766. */
  36767. UniformBuffer.prototype.addColor3 = function (name, color) {
  36768. var temp = new Array();
  36769. color.toArray(temp);
  36770. this.addUniform(name, temp);
  36771. };
  36772. /**
  36773. * Adds a vec4 to the uniform buffer.
  36774. * @param name Name of the uniform, as used in the uniform block in the shader.
  36775. * @param color Define the rgb components from a Color
  36776. * @param alpha Define the a component of the vec4
  36777. */
  36778. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36779. var temp = new Array();
  36780. color.toArray(temp);
  36781. temp.push(alpha);
  36782. this.addUniform(name, temp);
  36783. };
  36784. /**
  36785. * Adds a vec3 to the uniform buffer.
  36786. * @param name Name of the uniform, as used in the uniform block in the shader.
  36787. * @param vector Define the vec3 components from a Vector
  36788. */
  36789. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36790. var temp = new Array();
  36791. vector.toArray(temp);
  36792. this.addUniform(name, temp);
  36793. };
  36794. /**
  36795. * Adds a Matrix 3x3 to the uniform buffer.
  36796. * @param name Name of the uniform, as used in the uniform block in the shader.
  36797. */
  36798. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36799. this.addUniform(name, 12);
  36800. };
  36801. /**
  36802. * Adds a Matrix 2x2 to the uniform buffer.
  36803. * @param name Name of the uniform, as used in the uniform block in the shader.
  36804. */
  36805. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36806. this.addUniform(name, 8);
  36807. };
  36808. /**
  36809. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36810. */
  36811. UniformBuffer.prototype.create = function () {
  36812. if (this._noUBO) {
  36813. return;
  36814. }
  36815. if (this._buffer) {
  36816. return; // nothing to do
  36817. }
  36818. // See spec, alignment must be filled as a vec4
  36819. this._fillAlignment(4);
  36820. this._bufferData = new Float32Array(this._data);
  36821. this._rebuild();
  36822. this._needSync = true;
  36823. };
  36824. /** @hidden */
  36825. UniformBuffer.prototype._rebuild = function () {
  36826. if (this._noUBO) {
  36827. return;
  36828. }
  36829. if (this._dynamic) {
  36830. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36831. }
  36832. else {
  36833. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36834. }
  36835. };
  36836. /**
  36837. * Updates the WebGL Uniform Buffer on the GPU.
  36838. * If the `dynamic` flag is set to true, no cache comparison is done.
  36839. * Otherwise, the buffer will be updated only if the cache differs.
  36840. */
  36841. UniformBuffer.prototype.update = function () {
  36842. if (!this._buffer) {
  36843. this.create();
  36844. return;
  36845. }
  36846. if (!this._dynamic && !this._needSync) {
  36847. return;
  36848. }
  36849. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36850. this._needSync = false;
  36851. };
  36852. /**
  36853. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36854. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  36855. * @param data Define the flattened data
  36856. * @param size Define the size of the data.
  36857. */
  36858. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36859. var location = this._uniformLocations[uniformName];
  36860. if (location === undefined) {
  36861. if (this._buffer) {
  36862. // Cannot add an uniform if the buffer is already created
  36863. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36864. return;
  36865. }
  36866. this.addUniform(uniformName, size);
  36867. location = this._uniformLocations[uniformName];
  36868. }
  36869. if (!this._buffer) {
  36870. this.create();
  36871. }
  36872. if (!this._dynamic) {
  36873. // Cache for static uniform buffers
  36874. var changed = false;
  36875. for (var i = 0; i < size; i++) {
  36876. if (this._bufferData[location + i] !== data[i]) {
  36877. changed = true;
  36878. this._bufferData[location + i] = data[i];
  36879. }
  36880. }
  36881. this._needSync = this._needSync || changed;
  36882. }
  36883. else {
  36884. // No cache for dynamic
  36885. for (var i = 0; i < size; i++) {
  36886. this._bufferData[location + i] = data[i];
  36887. }
  36888. }
  36889. };
  36890. // Update methods
  36891. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36892. // To match std140, matrix must be realigned
  36893. for (var i = 0; i < 3; i++) {
  36894. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36895. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36896. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36897. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36898. }
  36899. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36900. };
  36901. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36902. this._currentEffect.setMatrix3x3(name, matrix);
  36903. };
  36904. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36905. this._currentEffect.setMatrix2x2(name, matrix);
  36906. };
  36907. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36908. // To match std140, matrix must be realigned
  36909. for (var i = 0; i < 2; i++) {
  36910. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36911. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36912. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36913. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36914. }
  36915. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36916. };
  36917. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36918. this._currentEffect.setFloat(name, x);
  36919. };
  36920. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36921. UniformBuffer._tempBuffer[0] = x;
  36922. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36923. };
  36924. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36925. if (suffix === void 0) { suffix = ""; }
  36926. this._currentEffect.setFloat2(name + suffix, x, y);
  36927. };
  36928. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36929. if (suffix === void 0) { suffix = ""; }
  36930. UniformBuffer._tempBuffer[0] = x;
  36931. UniformBuffer._tempBuffer[1] = y;
  36932. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36933. };
  36934. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36935. if (suffix === void 0) { suffix = ""; }
  36936. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36937. };
  36938. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36939. if (suffix === void 0) { suffix = ""; }
  36940. UniformBuffer._tempBuffer[0] = x;
  36941. UniformBuffer._tempBuffer[1] = y;
  36942. UniformBuffer._tempBuffer[2] = z;
  36943. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36944. };
  36945. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36946. if (suffix === void 0) { suffix = ""; }
  36947. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36948. };
  36949. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36950. if (suffix === void 0) { suffix = ""; }
  36951. UniformBuffer._tempBuffer[0] = x;
  36952. UniformBuffer._tempBuffer[1] = y;
  36953. UniformBuffer._tempBuffer[2] = z;
  36954. UniformBuffer._tempBuffer[3] = w;
  36955. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36956. };
  36957. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36958. this._currentEffect.setMatrix(name, mat);
  36959. };
  36960. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36961. this.updateUniform(name, mat.toArray(), 16);
  36962. };
  36963. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36964. this._currentEffect.setVector3(name, vector);
  36965. };
  36966. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36967. vector.toArray(UniformBuffer._tempBuffer);
  36968. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36969. };
  36970. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36971. this._currentEffect.setVector4(name, vector);
  36972. };
  36973. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36974. vector.toArray(UniformBuffer._tempBuffer);
  36975. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36976. };
  36977. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36978. if (suffix === void 0) { suffix = ""; }
  36979. this._currentEffect.setColor3(name + suffix, color);
  36980. };
  36981. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36982. if (suffix === void 0) { suffix = ""; }
  36983. color.toArray(UniformBuffer._tempBuffer);
  36984. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36985. };
  36986. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36987. if (suffix === void 0) { suffix = ""; }
  36988. this._currentEffect.setColor4(name + suffix, color, alpha);
  36989. };
  36990. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36991. if (suffix === void 0) { suffix = ""; }
  36992. color.toArray(UniformBuffer._tempBuffer);
  36993. UniformBuffer._tempBuffer[3] = alpha;
  36994. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36995. };
  36996. /**
  36997. * Sets a sampler uniform on the effect.
  36998. * @param name Define the name of the sampler.
  36999. * @param texture Define the texture to set in the sampler
  37000. */
  37001. UniformBuffer.prototype.setTexture = function (name, texture) {
  37002. this._currentEffect.setTexture(name, texture);
  37003. };
  37004. /**
  37005. * Directly updates the value of the uniform in the cache AND on the GPU.
  37006. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37007. * @param data Define the flattened data
  37008. */
  37009. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37010. this.updateUniform(uniformName, data, data.length);
  37011. this.update();
  37012. };
  37013. /**
  37014. * Binds this uniform buffer to an effect.
  37015. * @param effect Define the effect to bind the buffer to
  37016. * @param name Name of the uniform block in the shader.
  37017. */
  37018. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37019. this._currentEffect = effect;
  37020. if (this._noUBO || !this._buffer) {
  37021. return;
  37022. }
  37023. effect.bindUniformBuffer(this._buffer, name);
  37024. };
  37025. /**
  37026. * Disposes the uniform buffer.
  37027. */
  37028. UniformBuffer.prototype.dispose = function () {
  37029. if (this._noUBO) {
  37030. return;
  37031. }
  37032. var index = this._engine._uniformBuffers.indexOf(this);
  37033. if (index !== -1) {
  37034. this._engine._uniformBuffers.splice(index, 1);
  37035. }
  37036. if (!this._buffer) {
  37037. return;
  37038. }
  37039. if (this._engine._releaseBuffer(this._buffer)) {
  37040. this._buffer = null;
  37041. }
  37042. };
  37043. // Pool for avoiding memory leaks
  37044. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37045. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37046. return UniformBuffer;
  37047. }());
  37048. BABYLON.UniformBuffer = UniformBuffer;
  37049. })(BABYLON || (BABYLON = {}));
  37050. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37051. var BABYLON;
  37052. (function (BABYLON) {
  37053. /**
  37054. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37055. */
  37056. var VertexData = /** @class */ (function () {
  37057. function VertexData() {
  37058. }
  37059. /**
  37060. * Uses the passed data array to set the set the values for the specified kind of data
  37061. * @param data a linear array of floating numbers
  37062. * @param kind the type of data that is being set, eg positions, colors etc
  37063. */
  37064. VertexData.prototype.set = function (data, kind) {
  37065. switch (kind) {
  37066. case BABYLON.VertexBuffer.PositionKind:
  37067. this.positions = data;
  37068. break;
  37069. case BABYLON.VertexBuffer.NormalKind:
  37070. this.normals = data;
  37071. break;
  37072. case BABYLON.VertexBuffer.TangentKind:
  37073. this.tangents = data;
  37074. break;
  37075. case BABYLON.VertexBuffer.UVKind:
  37076. this.uvs = data;
  37077. break;
  37078. case BABYLON.VertexBuffer.UV2Kind:
  37079. this.uvs2 = data;
  37080. break;
  37081. case BABYLON.VertexBuffer.UV3Kind:
  37082. this.uvs3 = data;
  37083. break;
  37084. case BABYLON.VertexBuffer.UV4Kind:
  37085. this.uvs4 = data;
  37086. break;
  37087. case BABYLON.VertexBuffer.UV5Kind:
  37088. this.uvs5 = data;
  37089. break;
  37090. case BABYLON.VertexBuffer.UV6Kind:
  37091. this.uvs6 = data;
  37092. break;
  37093. case BABYLON.VertexBuffer.ColorKind:
  37094. this.colors = data;
  37095. break;
  37096. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37097. this.matricesIndices = data;
  37098. break;
  37099. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37100. this.matricesWeights = data;
  37101. break;
  37102. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37103. this.matricesIndicesExtra = data;
  37104. break;
  37105. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37106. this.matricesWeightsExtra = data;
  37107. break;
  37108. }
  37109. };
  37110. /**
  37111. * Associates the vertexData to the passed Mesh.
  37112. * Sets it as updatable or not (default `false`)
  37113. * @param mesh the mesh the vertexData is applied to
  37114. * @param updatable when used and having the value true allows new data to update the vertexData
  37115. * @returns the VertexData
  37116. */
  37117. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37118. this._applyTo(mesh, updatable);
  37119. return this;
  37120. };
  37121. /**
  37122. * Associates the vertexData to the passed Geometry.
  37123. * Sets it as updatable or not (default `false`)
  37124. * @param geometry the geometry the vertexData is applied to
  37125. * @param updatable when used and having the value true allows new data to update the vertexData
  37126. * @returns VertexData
  37127. */
  37128. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37129. this._applyTo(geometry, updatable);
  37130. return this;
  37131. };
  37132. /**
  37133. * Updates the associated mesh
  37134. * @param mesh the mesh to be updated
  37135. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37136. * @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
  37137. * @returns VertexData
  37138. */
  37139. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37140. this._update(mesh);
  37141. return this;
  37142. };
  37143. /**
  37144. * Updates the associated geometry
  37145. * @param geometry the geometry to be updated
  37146. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37147. * @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
  37148. * @returns VertexData.
  37149. */
  37150. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37151. this._update(geometry);
  37152. return this;
  37153. };
  37154. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37155. if (updatable === void 0) { updatable = false; }
  37156. if (this.positions) {
  37157. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37158. }
  37159. if (this.normals) {
  37160. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37161. }
  37162. if (this.tangents) {
  37163. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37164. }
  37165. if (this.uvs) {
  37166. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37167. }
  37168. if (this.uvs2) {
  37169. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37170. }
  37171. if (this.uvs3) {
  37172. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37173. }
  37174. if (this.uvs4) {
  37175. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37176. }
  37177. if (this.uvs5) {
  37178. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37179. }
  37180. if (this.uvs6) {
  37181. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37182. }
  37183. if (this.colors) {
  37184. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37185. }
  37186. if (this.matricesIndices) {
  37187. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37188. }
  37189. if (this.matricesWeights) {
  37190. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37191. }
  37192. if (this.matricesIndicesExtra) {
  37193. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37194. }
  37195. if (this.matricesWeightsExtra) {
  37196. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37197. }
  37198. if (this.indices) {
  37199. meshOrGeometry.setIndices(this.indices, null, updatable);
  37200. }
  37201. else {
  37202. meshOrGeometry.setIndices([], null);
  37203. }
  37204. return this;
  37205. };
  37206. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37207. if (this.positions) {
  37208. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37209. }
  37210. if (this.normals) {
  37211. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37212. }
  37213. if (this.tangents) {
  37214. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37215. }
  37216. if (this.uvs) {
  37217. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37218. }
  37219. if (this.uvs2) {
  37220. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37221. }
  37222. if (this.uvs3) {
  37223. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37224. }
  37225. if (this.uvs4) {
  37226. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37227. }
  37228. if (this.uvs5) {
  37229. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37230. }
  37231. if (this.uvs6) {
  37232. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37233. }
  37234. if (this.colors) {
  37235. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37236. }
  37237. if (this.matricesIndices) {
  37238. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37239. }
  37240. if (this.matricesWeights) {
  37241. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37242. }
  37243. if (this.matricesIndicesExtra) {
  37244. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37245. }
  37246. if (this.matricesWeightsExtra) {
  37247. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37248. }
  37249. if (this.indices) {
  37250. meshOrGeometry.setIndices(this.indices, null);
  37251. }
  37252. return this;
  37253. };
  37254. /**
  37255. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37256. * @param matrix the transforming matrix
  37257. * @returns the VertexData
  37258. */
  37259. VertexData.prototype.transform = function (matrix) {
  37260. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37261. var transformed = BABYLON.Vector3.Zero();
  37262. var index;
  37263. if (this.positions) {
  37264. var position = BABYLON.Vector3.Zero();
  37265. for (index = 0; index < this.positions.length; index += 3) {
  37266. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37267. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37268. this.positions[index] = transformed.x;
  37269. this.positions[index + 1] = transformed.y;
  37270. this.positions[index + 2] = transformed.z;
  37271. }
  37272. }
  37273. if (this.normals) {
  37274. var normal = BABYLON.Vector3.Zero();
  37275. for (index = 0; index < this.normals.length; index += 3) {
  37276. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37277. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37278. this.normals[index] = transformed.x;
  37279. this.normals[index + 1] = transformed.y;
  37280. this.normals[index + 2] = transformed.z;
  37281. }
  37282. }
  37283. if (this.tangents) {
  37284. var tangent = BABYLON.Vector4.Zero();
  37285. var tangentTransformed = BABYLON.Vector4.Zero();
  37286. for (index = 0; index < this.tangents.length; index += 4) {
  37287. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37288. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37289. this.tangents[index] = tangentTransformed.x;
  37290. this.tangents[index + 1] = tangentTransformed.y;
  37291. this.tangents[index + 2] = tangentTransformed.z;
  37292. this.tangents[index + 3] = tangentTransformed.w;
  37293. }
  37294. }
  37295. if (flip && this.indices) {
  37296. for (index = 0; index < this.indices.length; index += 3) {
  37297. var tmp = this.indices[index + 1];
  37298. this.indices[index + 1] = this.indices[index + 2];
  37299. this.indices[index + 2] = tmp;
  37300. }
  37301. }
  37302. return this;
  37303. };
  37304. /**
  37305. * Merges the passed VertexData into the current one
  37306. * @param other the VertexData to be merged into the current one
  37307. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37308. * @returns the modified VertexData
  37309. */
  37310. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37311. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37312. this._validate();
  37313. other._validate();
  37314. if (!this.normals !== !other.normals ||
  37315. !this.tangents !== !other.tangents ||
  37316. !this.uvs !== !other.uvs ||
  37317. !this.uvs2 !== !other.uvs2 ||
  37318. !this.uvs3 !== !other.uvs3 ||
  37319. !this.uvs4 !== !other.uvs4 ||
  37320. !this.uvs5 !== !other.uvs5 ||
  37321. !this.uvs6 !== !other.uvs6 ||
  37322. !this.colors !== !other.colors ||
  37323. !this.matricesIndices !== !other.matricesIndices ||
  37324. !this.matricesWeights !== !other.matricesWeights ||
  37325. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37326. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37327. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37328. }
  37329. if (other.indices) {
  37330. if (!this.indices) {
  37331. this.indices = [];
  37332. }
  37333. var offset = this.positions ? this.positions.length / 3 : 0;
  37334. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37335. if (isSrcTypedArray) {
  37336. var len = this.indices.length + other.indices.length;
  37337. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37338. temp.set(this.indices);
  37339. var decal = this.indices.length;
  37340. for (var index = 0; index < other.indices.length; index++) {
  37341. temp[decal + index] = other.indices[index] + offset;
  37342. }
  37343. this.indices = temp;
  37344. }
  37345. else {
  37346. for (var index = 0; index < other.indices.length; index++) {
  37347. this.indices.push(other.indices[index] + offset);
  37348. }
  37349. }
  37350. }
  37351. this.positions = this._mergeElement(this.positions, other.positions);
  37352. this.normals = this._mergeElement(this.normals, other.normals);
  37353. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37354. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37355. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37356. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37357. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37358. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37359. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37360. this.colors = this._mergeElement(this.colors, other.colors);
  37361. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37362. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37363. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37364. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37365. return this;
  37366. };
  37367. VertexData.prototype._mergeElement = function (source, other) {
  37368. if (!source) {
  37369. return other;
  37370. }
  37371. if (!other) {
  37372. return source;
  37373. }
  37374. var len = other.length + source.length;
  37375. var isSrcTypedArray = source instanceof Float32Array;
  37376. var isOthTypedArray = other instanceof Float32Array;
  37377. // use non-loop method when the source is Float32Array
  37378. if (isSrcTypedArray) {
  37379. var ret32 = new Float32Array(len);
  37380. ret32.set(source);
  37381. ret32.set(other, source.length);
  37382. return ret32;
  37383. // source is number[], when other is also use concat
  37384. }
  37385. else if (!isOthTypedArray) {
  37386. return source.concat(other);
  37387. // source is a number[], but other is a Float32Array, loop required
  37388. }
  37389. else {
  37390. var ret = source.slice(0); // copy source to a separate array
  37391. for (var i = 0, len = other.length; i < len; i++) {
  37392. ret.push(other[i]);
  37393. }
  37394. return ret;
  37395. }
  37396. };
  37397. VertexData.prototype._validate = function () {
  37398. if (!this.positions) {
  37399. throw new Error("Positions are required");
  37400. }
  37401. var getElementCount = function (kind, values) {
  37402. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37403. if ((values.length % stride) !== 0) {
  37404. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37405. }
  37406. return values.length / stride;
  37407. };
  37408. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  37409. var validateElementCount = function (kind, values) {
  37410. var elementCount = getElementCount(kind, values);
  37411. if (elementCount !== positionsElementCount) {
  37412. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  37413. }
  37414. };
  37415. if (this.normals)
  37416. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  37417. if (this.tangents)
  37418. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37419. if (this.uvs)
  37420. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37421. if (this.uvs2)
  37422. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37423. if (this.uvs3)
  37424. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37425. if (this.uvs4)
  37426. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37427. if (this.uvs5)
  37428. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37429. if (this.uvs6)
  37430. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37431. if (this.colors)
  37432. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37433. if (this.matricesIndices)
  37434. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37435. if (this.matricesWeights)
  37436. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37437. if (this.matricesIndicesExtra)
  37438. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37439. if (this.matricesWeightsExtra)
  37440. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37441. };
  37442. /**
  37443. * Serializes the VertexData
  37444. * @returns a serialized object
  37445. */
  37446. VertexData.prototype.serialize = function () {
  37447. var serializationObject = this.serialize();
  37448. if (this.positions) {
  37449. serializationObject.positions = this.positions;
  37450. }
  37451. if (this.normals) {
  37452. serializationObject.normals = this.normals;
  37453. }
  37454. if (this.tangents) {
  37455. serializationObject.tangents = this.tangents;
  37456. }
  37457. if (this.uvs) {
  37458. serializationObject.uvs = this.uvs;
  37459. }
  37460. if (this.uvs2) {
  37461. serializationObject.uvs2 = this.uvs2;
  37462. }
  37463. if (this.uvs3) {
  37464. serializationObject.uvs3 = this.uvs3;
  37465. }
  37466. if (this.uvs4) {
  37467. serializationObject.uvs4 = this.uvs4;
  37468. }
  37469. if (this.uvs5) {
  37470. serializationObject.uvs5 = this.uvs5;
  37471. }
  37472. if (this.uvs6) {
  37473. serializationObject.uvs6 = this.uvs6;
  37474. }
  37475. if (this.colors) {
  37476. serializationObject.colors = this.colors;
  37477. }
  37478. if (this.matricesIndices) {
  37479. serializationObject.matricesIndices = this.matricesIndices;
  37480. serializationObject.matricesIndices._isExpanded = true;
  37481. }
  37482. if (this.matricesWeights) {
  37483. serializationObject.matricesWeights = this.matricesWeights;
  37484. }
  37485. if (this.matricesIndicesExtra) {
  37486. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37487. serializationObject.matricesIndicesExtra._isExpanded = true;
  37488. }
  37489. if (this.matricesWeightsExtra) {
  37490. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37491. }
  37492. serializationObject.indices = this.indices;
  37493. return serializationObject;
  37494. };
  37495. // Statics
  37496. /**
  37497. * Extracts the vertexData from a mesh
  37498. * @param mesh the mesh from which to extract the VertexData
  37499. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37500. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37501. * @returns the object VertexData associated to the passed mesh
  37502. */
  37503. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37504. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37505. };
  37506. /**
  37507. * Extracts the vertexData from the geometry
  37508. * @param geometry the geometry from which to extract the VertexData
  37509. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37510. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37511. * @returns the object VertexData associated to the passed mesh
  37512. */
  37513. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37514. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37515. };
  37516. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37517. var result = new VertexData();
  37518. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37519. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37520. }
  37521. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37522. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37523. }
  37524. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37525. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37526. }
  37527. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37528. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37529. }
  37530. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37531. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37532. }
  37533. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37534. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37535. }
  37536. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37537. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37538. }
  37539. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37540. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37541. }
  37542. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37543. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37544. }
  37545. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37546. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37547. }
  37548. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37549. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37550. }
  37551. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37552. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37553. }
  37554. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37555. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37556. }
  37557. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37558. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37559. }
  37560. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  37561. return result;
  37562. };
  37563. /**
  37564. * Creates the VertexData for a Ribbon
  37565. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37566. * * pathArray array of paths, each of which an array of successive Vector3
  37567. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37568. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37569. * * 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
  37570. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37571. * * 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)
  37572. * * 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)
  37573. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37574. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37575. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37576. * @returns the VertexData of the ribbon
  37577. */
  37578. VertexData.CreateRibbon = function (options) {
  37579. var pathArray = options.pathArray;
  37580. var closeArray = options.closeArray || false;
  37581. var closePath = options.closePath || false;
  37582. var invertUV = options.invertUV || false;
  37583. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37584. var offset = options.offset || defaultOffset;
  37585. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37586. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37587. var customUV = options.uvs;
  37588. var customColors = options.colors;
  37589. var positions = [];
  37590. var indices = [];
  37591. var normals = [];
  37592. var uvs = [];
  37593. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37594. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37595. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37596. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37597. var minlg; // minimal length among all paths from pathArray
  37598. var lg = []; // array of path lengths : nb of vertex per path
  37599. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37600. var p; // path iterator
  37601. var i; // point iterator
  37602. var j; // point iterator
  37603. // if single path in pathArray
  37604. if (pathArray.length < 2) {
  37605. var ar1 = [];
  37606. var ar2 = [];
  37607. for (i = 0; i < pathArray[0].length - offset; i++) {
  37608. ar1.push(pathArray[0][i]);
  37609. ar2.push(pathArray[0][i + offset]);
  37610. }
  37611. pathArray = [ar1, ar2];
  37612. }
  37613. // positions and horizontal distances (u)
  37614. var idc = 0;
  37615. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37616. var path;
  37617. var l;
  37618. minlg = pathArray[0].length;
  37619. var vectlg;
  37620. var dist;
  37621. for (p = 0; p < pathArray.length; p++) {
  37622. uTotalDistance[p] = 0;
  37623. us[p] = [0];
  37624. path = pathArray[p];
  37625. l = path.length;
  37626. minlg = (minlg < l) ? minlg : l;
  37627. j = 0;
  37628. while (j < l) {
  37629. positions.push(path[j].x, path[j].y, path[j].z);
  37630. if (j > 0) {
  37631. vectlg = path[j].subtract(path[j - 1]).length();
  37632. dist = vectlg + uTotalDistance[p];
  37633. us[p].push(dist);
  37634. uTotalDistance[p] = dist;
  37635. }
  37636. j++;
  37637. }
  37638. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37639. j--;
  37640. positions.push(path[0].x, path[0].y, path[0].z);
  37641. vectlg = path[j].subtract(path[0]).length();
  37642. dist = vectlg + uTotalDistance[p];
  37643. us[p].push(dist);
  37644. uTotalDistance[p] = dist;
  37645. }
  37646. lg[p] = l + closePathCorr;
  37647. idx[p] = idc;
  37648. idc += (l + closePathCorr);
  37649. }
  37650. // vertical distances (v)
  37651. var path1;
  37652. var path2;
  37653. var vertex1 = null;
  37654. var vertex2 = null;
  37655. for (i = 0; i < minlg + closePathCorr; i++) {
  37656. vTotalDistance[i] = 0;
  37657. vs[i] = [0];
  37658. for (p = 0; p < pathArray.length - 1; p++) {
  37659. path1 = pathArray[p];
  37660. path2 = pathArray[p + 1];
  37661. if (i === minlg) { // closePath
  37662. vertex1 = path1[0];
  37663. vertex2 = path2[0];
  37664. }
  37665. else {
  37666. vertex1 = path1[i];
  37667. vertex2 = path2[i];
  37668. }
  37669. vectlg = vertex2.subtract(vertex1).length();
  37670. dist = vectlg + vTotalDistance[i];
  37671. vs[i].push(dist);
  37672. vTotalDistance[i] = dist;
  37673. }
  37674. if (closeArray && vertex2 && vertex1) {
  37675. path1 = pathArray[p];
  37676. path2 = pathArray[0];
  37677. if (i === minlg) { // closePath
  37678. vertex2 = path2[0];
  37679. }
  37680. vectlg = vertex2.subtract(vertex1).length();
  37681. dist = vectlg + vTotalDistance[i];
  37682. vTotalDistance[i] = dist;
  37683. }
  37684. }
  37685. // uvs
  37686. var u;
  37687. var v;
  37688. if (customUV) {
  37689. for (p = 0; p < customUV.length; p++) {
  37690. uvs.push(customUV[p].x, customUV[p].y);
  37691. }
  37692. }
  37693. else {
  37694. for (p = 0; p < pathArray.length; p++) {
  37695. for (i = 0; i < minlg + closePathCorr; i++) {
  37696. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37697. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37698. if (invertUV) {
  37699. uvs.push(v, u);
  37700. }
  37701. else {
  37702. uvs.push(u, v);
  37703. }
  37704. }
  37705. }
  37706. }
  37707. // indices
  37708. p = 0; // path index
  37709. var pi = 0; // positions array index
  37710. var l1 = lg[p] - 1; // path1 length
  37711. var l2 = lg[p + 1] - 1; // path2 length
  37712. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37713. var shft = idx[1] - idx[0]; // shift
  37714. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37715. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37716. // 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
  37717. indices.push(pi, pi + shft, pi + 1);
  37718. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37719. pi += 1;
  37720. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37721. p++;
  37722. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37723. shft = idx[0] - idx[p];
  37724. l1 = lg[p] - 1;
  37725. l2 = lg[0] - 1;
  37726. }
  37727. else {
  37728. shft = idx[p + 1] - idx[p];
  37729. l1 = lg[p] - 1;
  37730. l2 = lg[p + 1] - 1;
  37731. }
  37732. pi = idx[p];
  37733. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37734. }
  37735. }
  37736. // normals
  37737. VertexData.ComputeNormals(positions, indices, normals);
  37738. if (closePath) { // update both the first and last vertex normals to their average value
  37739. var indexFirst = 0;
  37740. var indexLast = 0;
  37741. for (p = 0; p < pathArray.length; p++) {
  37742. indexFirst = idx[p] * 3;
  37743. if (p + 1 < pathArray.length) {
  37744. indexLast = (idx[p + 1] - 1) * 3;
  37745. }
  37746. else {
  37747. indexLast = normals.length - 3;
  37748. }
  37749. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37750. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37751. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37752. normals[indexLast] = normals[indexFirst];
  37753. normals[indexLast + 1] = normals[indexFirst + 1];
  37754. normals[indexLast + 2] = normals[indexFirst + 2];
  37755. }
  37756. }
  37757. // sides
  37758. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37759. // Colors
  37760. var colors = null;
  37761. if (customColors) {
  37762. colors = new Float32Array(customColors.length * 4);
  37763. for (var c = 0; c < customColors.length; c++) {
  37764. colors[c * 4] = customColors[c].r;
  37765. colors[c * 4 + 1] = customColors[c].g;
  37766. colors[c * 4 + 2] = customColors[c].b;
  37767. colors[c * 4 + 3] = customColors[c].a;
  37768. }
  37769. }
  37770. // Result
  37771. var vertexData = new VertexData();
  37772. var positions32 = new Float32Array(positions);
  37773. var normals32 = new Float32Array(normals);
  37774. var uvs32 = new Float32Array(uvs);
  37775. vertexData.indices = indices;
  37776. vertexData.positions = positions32;
  37777. vertexData.normals = normals32;
  37778. vertexData.uvs = uvs32;
  37779. if (colors) {
  37780. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37781. }
  37782. if (closePath) {
  37783. vertexData._idx = idx;
  37784. }
  37785. return vertexData;
  37786. };
  37787. /**
  37788. * Creates the VertexData for a box
  37789. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37790. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37791. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37792. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37793. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37794. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37795. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37796. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37797. * * 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)
  37798. * * 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)
  37799. * @returns the VertexData of the box
  37800. */
  37801. VertexData.CreateBox = function (options) {
  37802. var normalsSource = [
  37803. new BABYLON.Vector3(0, 0, 1),
  37804. new BABYLON.Vector3(0, 0, -1),
  37805. new BABYLON.Vector3(1, 0, 0),
  37806. new BABYLON.Vector3(-1, 0, 0),
  37807. new BABYLON.Vector3(0, 1, 0),
  37808. new BABYLON.Vector3(0, -1, 0)
  37809. ];
  37810. var indices = [];
  37811. var positions = [];
  37812. var normals = [];
  37813. var uvs = [];
  37814. var width = options.width || options.size || 1;
  37815. var height = options.height || options.size || 1;
  37816. var depth = options.depth || options.size || 1;
  37817. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37818. var faceUV = options.faceUV || new Array(6);
  37819. var faceColors = options.faceColors;
  37820. var colors = [];
  37821. // default face colors and UV if undefined
  37822. for (var f = 0; f < 6; f++) {
  37823. if (faceUV[f] === undefined) {
  37824. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37825. }
  37826. if (faceColors && faceColors[f] === undefined) {
  37827. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37828. }
  37829. }
  37830. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37831. // Create each face in turn.
  37832. for (var index = 0; index < normalsSource.length; index++) {
  37833. var normal = normalsSource[index];
  37834. // Get two vectors perpendicular to the face normal and to each other.
  37835. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37836. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37837. // Six indices (two triangles) per face.
  37838. var verticesLength = positions.length / 3;
  37839. indices.push(verticesLength);
  37840. indices.push(verticesLength + 1);
  37841. indices.push(verticesLength + 2);
  37842. indices.push(verticesLength);
  37843. indices.push(verticesLength + 2);
  37844. indices.push(verticesLength + 3);
  37845. // Four vertices per face.
  37846. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37847. positions.push(vertex.x, vertex.y, vertex.z);
  37848. normals.push(normal.x, normal.y, normal.z);
  37849. uvs.push(faceUV[index].z, faceUV[index].w);
  37850. if (faceColors) {
  37851. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37852. }
  37853. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37854. positions.push(vertex.x, vertex.y, vertex.z);
  37855. normals.push(normal.x, normal.y, normal.z);
  37856. uvs.push(faceUV[index].x, faceUV[index].w);
  37857. if (faceColors) {
  37858. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37859. }
  37860. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37861. positions.push(vertex.x, vertex.y, vertex.z);
  37862. normals.push(normal.x, normal.y, normal.z);
  37863. uvs.push(faceUV[index].x, faceUV[index].y);
  37864. if (faceColors) {
  37865. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37866. }
  37867. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37868. positions.push(vertex.x, vertex.y, vertex.z);
  37869. normals.push(normal.x, normal.y, normal.z);
  37870. uvs.push(faceUV[index].z, faceUV[index].y);
  37871. if (faceColors) {
  37872. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37873. }
  37874. }
  37875. // sides
  37876. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37877. // Result
  37878. var vertexData = new VertexData();
  37879. vertexData.indices = indices;
  37880. vertexData.positions = positions;
  37881. vertexData.normals = normals;
  37882. vertexData.uvs = uvs;
  37883. if (faceColors) {
  37884. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37885. vertexData.colors = totalColors;
  37886. }
  37887. return vertexData;
  37888. };
  37889. /**
  37890. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37891. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37892. * * segments sets the number of horizontal strips optional, default 32
  37893. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37894. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37895. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37896. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37897. * * 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
  37898. * * 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
  37899. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37900. * * 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)
  37901. * * 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)
  37902. * @returns the VertexData of the ellipsoid
  37903. */
  37904. VertexData.CreateSphere = function (options) {
  37905. var segments = options.segments || 32;
  37906. var diameterX = options.diameterX || options.diameter || 1;
  37907. var diameterY = options.diameterY || options.diameter || 1;
  37908. var diameterZ = options.diameterZ || options.diameter || 1;
  37909. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37910. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37911. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37912. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37913. var totalZRotationSteps = 2 + segments;
  37914. var totalYRotationSteps = 2 * totalZRotationSteps;
  37915. var indices = [];
  37916. var positions = [];
  37917. var normals = [];
  37918. var uvs = [];
  37919. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37920. var normalizedZ = zRotationStep / totalZRotationSteps;
  37921. var angleZ = normalizedZ * Math.PI * slice;
  37922. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37923. var normalizedY = yRotationStep / totalYRotationSteps;
  37924. var angleY = normalizedY * Math.PI * 2 * arc;
  37925. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37926. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37927. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37928. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37929. var vertex = complete.multiply(radius);
  37930. var normal = complete.divide(radius).normalize();
  37931. positions.push(vertex.x, vertex.y, vertex.z);
  37932. normals.push(normal.x, normal.y, normal.z);
  37933. uvs.push(normalizedY, normalizedZ);
  37934. }
  37935. if (zRotationStep > 0) {
  37936. var verticesCount = positions.length / 3;
  37937. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37938. indices.push((firstIndex));
  37939. indices.push((firstIndex + 1));
  37940. indices.push(firstIndex + totalYRotationSteps + 1);
  37941. indices.push((firstIndex + totalYRotationSteps + 1));
  37942. indices.push((firstIndex + 1));
  37943. indices.push((firstIndex + totalYRotationSteps + 2));
  37944. }
  37945. }
  37946. }
  37947. // Sides
  37948. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37949. // Result
  37950. var vertexData = new VertexData();
  37951. vertexData.indices = indices;
  37952. vertexData.positions = positions;
  37953. vertexData.normals = normals;
  37954. vertexData.uvs = uvs;
  37955. return vertexData;
  37956. };
  37957. /**
  37958. * Creates the VertexData for a cylinder, cone or prism
  37959. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37960. * * height sets the height (y direction) of the cylinder, optional, default 2
  37961. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37962. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37963. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37964. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37965. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37966. * * 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
  37967. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37968. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37969. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37970. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37971. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37972. * * 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)
  37973. * * 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)
  37974. * @returns the VertexData of the cylinder, cone or prism
  37975. */
  37976. VertexData.CreateCylinder = function (options) {
  37977. var height = options.height || 2;
  37978. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37979. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37980. var tessellation = options.tessellation || 24;
  37981. var subdivisions = options.subdivisions || 1;
  37982. var hasRings = options.hasRings ? true : false;
  37983. var enclose = options.enclose ? true : false;
  37984. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37985. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37986. var faceUV = options.faceUV || new Array(3);
  37987. var faceColors = options.faceColors;
  37988. // default face colors and UV if undefined
  37989. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37990. var ringNb = (hasRings) ? subdivisions : 1;
  37991. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37992. var f;
  37993. for (f = 0; f < surfaceNb; f++) {
  37994. if (faceColors && faceColors[f] === undefined) {
  37995. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37996. }
  37997. }
  37998. for (f = 0; f < surfaceNb; f++) {
  37999. if (faceUV && faceUV[f] === undefined) {
  38000. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38001. }
  38002. }
  38003. var indices = new Array();
  38004. var positions = new Array();
  38005. var normals = new Array();
  38006. var uvs = new Array();
  38007. var colors = new Array();
  38008. var angle_step = Math.PI * 2 * arc / tessellation;
  38009. var angle;
  38010. var h;
  38011. var radius;
  38012. var tan = (diameterBottom - diameterTop) / 2 / height;
  38013. var ringVertex = BABYLON.Vector3.Zero();
  38014. var ringNormal = BABYLON.Vector3.Zero();
  38015. var ringFirstVertex = BABYLON.Vector3.Zero();
  38016. var ringFirstNormal = BABYLON.Vector3.Zero();
  38017. var quadNormal = BABYLON.Vector3.Zero();
  38018. var Y = BABYLON.Axis.Y;
  38019. // positions, normals, uvs
  38020. var i;
  38021. var j;
  38022. var r;
  38023. var ringIdx = 1;
  38024. var s = 1; // surface index
  38025. var cs = 0;
  38026. var v = 0;
  38027. for (i = 0; i <= subdivisions; i++) {
  38028. h = i / subdivisions;
  38029. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38030. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38031. for (r = 0; r < ringIdx; r++) {
  38032. if (hasRings) {
  38033. s += r;
  38034. }
  38035. if (enclose) {
  38036. s += 2 * r;
  38037. }
  38038. for (j = 0; j <= tessellation; j++) {
  38039. angle = j * angle_step;
  38040. // position
  38041. ringVertex.x = Math.cos(-angle) * radius;
  38042. ringVertex.y = -height / 2 + h * height;
  38043. ringVertex.z = Math.sin(-angle) * radius;
  38044. // normal
  38045. if (diameterTop === 0 && i === subdivisions) {
  38046. // if no top cap, reuse former normals
  38047. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38048. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38049. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38050. }
  38051. else {
  38052. ringNormal.x = ringVertex.x;
  38053. ringNormal.z = ringVertex.z;
  38054. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38055. ringNormal.normalize();
  38056. }
  38057. // keep first ring vertex values for enclose
  38058. if (j === 0) {
  38059. ringFirstVertex.copyFrom(ringVertex);
  38060. ringFirstNormal.copyFrom(ringNormal);
  38061. }
  38062. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38063. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38064. if (hasRings) {
  38065. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38066. }
  38067. else {
  38068. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38069. }
  38070. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38071. if (faceColors) {
  38072. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38073. }
  38074. }
  38075. // if enclose, add four vertices and their dedicated normals
  38076. if (arc !== 1 && enclose) {
  38077. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38078. positions.push(0, ringVertex.y, 0);
  38079. positions.push(0, ringVertex.y, 0);
  38080. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38081. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38082. quadNormal.normalize();
  38083. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38084. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38085. quadNormal.normalize();
  38086. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38087. if (hasRings) {
  38088. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38089. }
  38090. else {
  38091. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38092. }
  38093. uvs.push(faceUV[s + 1].x, v);
  38094. uvs.push(faceUV[s + 1].z, v);
  38095. if (hasRings) {
  38096. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38097. }
  38098. else {
  38099. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38100. }
  38101. uvs.push(faceUV[s + 2].x, v);
  38102. uvs.push(faceUV[s + 2].z, v);
  38103. if (faceColors) {
  38104. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38105. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38106. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38107. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38108. }
  38109. }
  38110. if (cs !== s) {
  38111. cs = s;
  38112. }
  38113. }
  38114. }
  38115. // indices
  38116. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38117. var s;
  38118. i = 0;
  38119. for (s = 0; s < subdivisions; s++) {
  38120. var i0 = 0;
  38121. var i1 = 0;
  38122. var i2 = 0;
  38123. var i3 = 0;
  38124. for (j = 0; j < tessellation; j++) {
  38125. i0 = i * (e + 1) + j;
  38126. i1 = (i + 1) * (e + 1) + j;
  38127. i2 = i * (e + 1) + (j + 1);
  38128. i3 = (i + 1) * (e + 1) + (j + 1);
  38129. indices.push(i0, i1, i2);
  38130. indices.push(i3, i2, i1);
  38131. }
  38132. if (arc !== 1 && enclose) { // if enclose, add two quads
  38133. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38134. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38135. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38136. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38137. }
  38138. i = (hasRings) ? (i + 2) : (i + 1);
  38139. }
  38140. // Caps
  38141. var createCylinderCap = function (isTop) {
  38142. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38143. if (radius === 0) {
  38144. return;
  38145. }
  38146. // Cap positions, normals & uvs
  38147. var angle;
  38148. var circleVector;
  38149. var i;
  38150. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38151. var c = null;
  38152. if (faceColors) {
  38153. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38154. }
  38155. // cap center
  38156. var vbase = positions.length / 3;
  38157. var offset = isTop ? height / 2 : -height / 2;
  38158. var center = new BABYLON.Vector3(0, offset, 0);
  38159. positions.push(center.x, center.y, center.z);
  38160. normals.push(0, isTop ? 1 : -1, 0);
  38161. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38162. if (c) {
  38163. colors.push(c.r, c.g, c.b, c.a);
  38164. }
  38165. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38166. for (i = 0; i <= tessellation; i++) {
  38167. angle = Math.PI * 2 * i * arc / tessellation;
  38168. var cos = Math.cos(-angle);
  38169. var sin = Math.sin(-angle);
  38170. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38171. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38172. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38173. normals.push(0, isTop ? 1 : -1, 0);
  38174. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38175. if (c) {
  38176. colors.push(c.r, c.g, c.b, c.a);
  38177. }
  38178. }
  38179. // Cap indices
  38180. for (i = 0; i < tessellation; i++) {
  38181. if (!isTop) {
  38182. indices.push(vbase);
  38183. indices.push(vbase + (i + 1));
  38184. indices.push(vbase + (i + 2));
  38185. }
  38186. else {
  38187. indices.push(vbase);
  38188. indices.push(vbase + (i + 2));
  38189. indices.push(vbase + (i + 1));
  38190. }
  38191. }
  38192. };
  38193. // add caps to geometry
  38194. createCylinderCap(false);
  38195. createCylinderCap(true);
  38196. // Sides
  38197. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38198. var vertexData = new VertexData();
  38199. vertexData.indices = indices;
  38200. vertexData.positions = positions;
  38201. vertexData.normals = normals;
  38202. vertexData.uvs = uvs;
  38203. if (faceColors) {
  38204. vertexData.colors = colors;
  38205. }
  38206. return vertexData;
  38207. };
  38208. /**
  38209. * Creates the VertexData for a torus
  38210. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38211. * * diameter the diameter of the torus, optional default 1
  38212. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38213. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38214. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38215. * * 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)
  38216. * * 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)
  38217. * @returns the VertexData of the torus
  38218. */
  38219. VertexData.CreateTorus = function (options) {
  38220. var indices = [];
  38221. var positions = [];
  38222. var normals = [];
  38223. var uvs = [];
  38224. var diameter = options.diameter || 1;
  38225. var thickness = options.thickness || 0.5;
  38226. var tessellation = options.tessellation || 16;
  38227. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38228. var stride = tessellation + 1;
  38229. for (var i = 0; i <= tessellation; i++) {
  38230. var u = i / tessellation;
  38231. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38232. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38233. for (var j = 0; j <= tessellation; j++) {
  38234. var v = 1 - j / tessellation;
  38235. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38236. var dx = Math.cos(innerAngle);
  38237. var dy = Math.sin(innerAngle);
  38238. // Create a vertex.
  38239. var normal = new BABYLON.Vector3(dx, dy, 0);
  38240. var position = normal.scale(thickness / 2);
  38241. var textureCoordinate = new BABYLON.Vector2(u, v);
  38242. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38243. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38244. positions.push(position.x, position.y, position.z);
  38245. normals.push(normal.x, normal.y, normal.z);
  38246. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38247. // And create indices for two triangles.
  38248. var nextI = (i + 1) % stride;
  38249. var nextJ = (j + 1) % stride;
  38250. indices.push(i * stride + j);
  38251. indices.push(i * stride + nextJ);
  38252. indices.push(nextI * stride + j);
  38253. indices.push(i * stride + nextJ);
  38254. indices.push(nextI * stride + nextJ);
  38255. indices.push(nextI * stride + j);
  38256. }
  38257. }
  38258. // Sides
  38259. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38260. // Result
  38261. var vertexData = new VertexData();
  38262. vertexData.indices = indices;
  38263. vertexData.positions = positions;
  38264. vertexData.normals = normals;
  38265. vertexData.uvs = uvs;
  38266. return vertexData;
  38267. };
  38268. /**
  38269. * Creates the VertexData of the LineSystem
  38270. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38271. * - lines an array of lines, each line being an array of successive Vector3
  38272. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38273. * @returns the VertexData of the LineSystem
  38274. */
  38275. VertexData.CreateLineSystem = function (options) {
  38276. var indices = [];
  38277. var positions = [];
  38278. var lines = options.lines;
  38279. var colors = options.colors;
  38280. var vertexColors = [];
  38281. var idx = 0;
  38282. for (var l = 0; l < lines.length; l++) {
  38283. var points = lines[l];
  38284. for (var index = 0; index < points.length; index++) {
  38285. positions.push(points[index].x, points[index].y, points[index].z);
  38286. if (colors) {
  38287. var color = colors[l];
  38288. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38289. }
  38290. if (index > 0) {
  38291. indices.push(idx - 1);
  38292. indices.push(idx);
  38293. }
  38294. idx++;
  38295. }
  38296. }
  38297. var vertexData = new VertexData();
  38298. vertexData.indices = indices;
  38299. vertexData.positions = positions;
  38300. if (colors) {
  38301. vertexData.colors = vertexColors;
  38302. }
  38303. return vertexData;
  38304. };
  38305. /**
  38306. * Create the VertexData for a DashedLines
  38307. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38308. * - points an array successive Vector3
  38309. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38310. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38311. * - dashNb the intended total number of dashes, optional, default 200
  38312. * @returns the VertexData for the DashedLines
  38313. */
  38314. VertexData.CreateDashedLines = function (options) {
  38315. var dashSize = options.dashSize || 3;
  38316. var gapSize = options.gapSize || 1;
  38317. var dashNb = options.dashNb || 200;
  38318. var points = options.points;
  38319. var positions = new Array();
  38320. var indices = new Array();
  38321. var curvect = BABYLON.Vector3.Zero();
  38322. var lg = 0;
  38323. var nb = 0;
  38324. var shft = 0;
  38325. var dashshft = 0;
  38326. var curshft = 0;
  38327. var idx = 0;
  38328. var i = 0;
  38329. for (i = 0; i < points.length - 1; i++) {
  38330. points[i + 1].subtractToRef(points[i], curvect);
  38331. lg += curvect.length();
  38332. }
  38333. shft = lg / dashNb;
  38334. dashshft = dashSize * shft / (dashSize + gapSize);
  38335. for (i = 0; i < points.length - 1; i++) {
  38336. points[i + 1].subtractToRef(points[i], curvect);
  38337. nb = Math.floor(curvect.length() / shft);
  38338. curvect.normalize();
  38339. for (var j = 0; j < nb; j++) {
  38340. curshft = shft * j;
  38341. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38342. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38343. indices.push(idx, idx + 1);
  38344. idx += 2;
  38345. }
  38346. }
  38347. // Result
  38348. var vertexData = new VertexData();
  38349. vertexData.positions = positions;
  38350. vertexData.indices = indices;
  38351. return vertexData;
  38352. };
  38353. /**
  38354. * Creates the VertexData for a Ground
  38355. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38356. * - width the width (x direction) of the ground, optional, default 1
  38357. * - height the height (z direction) of the ground, optional, default 1
  38358. * - subdivisions the number of subdivisions per side, optional, default 1
  38359. * @returns the VertexData of the Ground
  38360. */
  38361. VertexData.CreateGround = function (options) {
  38362. var indices = [];
  38363. var positions = [];
  38364. var normals = [];
  38365. var uvs = [];
  38366. var row, col;
  38367. var width = options.width || 1;
  38368. var height = options.height || 1;
  38369. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38370. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38371. for (row = 0; row <= subdivisionsY; row++) {
  38372. for (col = 0; col <= subdivisionsX; col++) {
  38373. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38374. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38375. positions.push(position.x, position.y, position.z);
  38376. normals.push(normal.x, normal.y, normal.z);
  38377. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38378. }
  38379. }
  38380. for (row = 0; row < subdivisionsY; row++) {
  38381. for (col = 0; col < subdivisionsX; col++) {
  38382. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38383. indices.push(col + 1 + row * (subdivisionsX + 1));
  38384. indices.push(col + row * (subdivisionsX + 1));
  38385. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38386. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38387. indices.push(col + row * (subdivisionsX + 1));
  38388. }
  38389. }
  38390. // Result
  38391. var vertexData = new VertexData();
  38392. vertexData.indices = indices;
  38393. vertexData.positions = positions;
  38394. vertexData.normals = normals;
  38395. vertexData.uvs = uvs;
  38396. return vertexData;
  38397. };
  38398. /**
  38399. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  38400. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38401. * * xmin the ground minimum X coordinate, optional, default -1
  38402. * * zmin the ground minimum Z coordinate, optional, default -1
  38403. * * xmax the ground maximum X coordinate, optional, default 1
  38404. * * zmax the ground maximum Z coordinate, optional, default 1
  38405. * * 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}
  38406. * * 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}
  38407. * @returns the VertexData of the TiledGround
  38408. */
  38409. VertexData.CreateTiledGround = function (options) {
  38410. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  38411. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  38412. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  38413. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  38414. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38415. var precision = options.precision || { w: 1, h: 1 };
  38416. var indices = new Array();
  38417. var positions = new Array();
  38418. var normals = new Array();
  38419. var uvs = new Array();
  38420. var row, col, tileRow, tileCol;
  38421. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38422. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38423. precision.w = (precision.w < 1) ? 1 : precision.w;
  38424. precision.h = (precision.h < 1) ? 1 : precision.h;
  38425. var tileSize = {
  38426. 'w': (xmax - xmin) / subdivisions.w,
  38427. 'h': (zmax - zmin) / subdivisions.h
  38428. };
  38429. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38430. // Indices
  38431. var base = positions.length / 3;
  38432. var rowLength = precision.w + 1;
  38433. for (row = 0; row < precision.h; row++) {
  38434. for (col = 0; col < precision.w; col++) {
  38435. var square = [
  38436. base + col + row * rowLength,
  38437. base + (col + 1) + row * rowLength,
  38438. base + (col + 1) + (row + 1) * rowLength,
  38439. base + col + (row + 1) * rowLength
  38440. ];
  38441. indices.push(square[1]);
  38442. indices.push(square[2]);
  38443. indices.push(square[3]);
  38444. indices.push(square[0]);
  38445. indices.push(square[1]);
  38446. indices.push(square[3]);
  38447. }
  38448. }
  38449. // Position, normals and uvs
  38450. var position = BABYLON.Vector3.Zero();
  38451. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38452. for (row = 0; row <= precision.h; row++) {
  38453. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38454. for (col = 0; col <= precision.w; col++) {
  38455. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38456. position.y = 0;
  38457. positions.push(position.x, position.y, position.z);
  38458. normals.push(normal.x, normal.y, normal.z);
  38459. uvs.push(col / precision.w, row / precision.h);
  38460. }
  38461. }
  38462. }
  38463. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38464. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38465. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38466. }
  38467. }
  38468. // Result
  38469. var vertexData = new VertexData();
  38470. vertexData.indices = indices;
  38471. vertexData.positions = positions;
  38472. vertexData.normals = normals;
  38473. vertexData.uvs = uvs;
  38474. return vertexData;
  38475. };
  38476. /**
  38477. * Creates the VertexData of the Ground designed from a heightmap
  38478. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38479. * * width the width (x direction) of the ground
  38480. * * height the height (z direction) of the ground
  38481. * * subdivisions the number of subdivisions per side
  38482. * * minHeight the minimum altitude on the ground, optional, default 0
  38483. * * maxHeight the maximum altitude on the ground, optional default 1
  38484. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38485. * * buffer the array holding the image color data
  38486. * * bufferWidth the width of image
  38487. * * bufferHeight the height of image
  38488. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  38489. * @returns the VertexData of the Ground designed from a heightmap
  38490. */
  38491. VertexData.CreateGroundFromHeightMap = function (options) {
  38492. var indices = [];
  38493. var positions = [];
  38494. var normals = [];
  38495. var uvs = [];
  38496. var row, col;
  38497. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38498. var alphaFilter = options.alphaFilter || 0.0;
  38499. // Vertices
  38500. for (row = 0; row <= options.subdivisions; row++) {
  38501. for (col = 0; col <= options.subdivisions; col++) {
  38502. 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));
  38503. // Compute height
  38504. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38505. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38506. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38507. var r = options.buffer[pos] / 255.0;
  38508. var g = options.buffer[pos + 1] / 255.0;
  38509. var b = options.buffer[pos + 2] / 255.0;
  38510. var a = options.buffer[pos + 3] / 255.0;
  38511. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38512. // If our alpha channel is not within our filter then we will assign a 'special' height
  38513. // Then when building the indices, we will ignore any vertex that is using the special height
  38514. if (a >= alphaFilter)
  38515. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38516. else {
  38517. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  38518. }
  38519. // Add vertex
  38520. positions.push(position.x, position.y, position.z);
  38521. normals.push(0, 0, 0);
  38522. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38523. }
  38524. }
  38525. // Indices
  38526. for (row = 0; row < options.subdivisions; row++) {
  38527. for (col = 0; col < options.subdivisions; col++) {
  38528. // Calculate Indices
  38529. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  38530. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  38531. var idx3 = (col + row * (options.subdivisions + 1));
  38532. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  38533. // Check that all indices are visible (based on our special height)
  38534. // Only display the vertex if all Indices are visible
  38535. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  38536. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  38537. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  38538. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  38539. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  38540. indices.push(idx1);
  38541. indices.push(idx2);
  38542. indices.push(idx3);
  38543. }
  38544. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  38545. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  38546. indices.push(idx4);
  38547. indices.push(idx1);
  38548. indices.push(idx3);
  38549. }
  38550. }
  38551. }
  38552. // Normals
  38553. VertexData.ComputeNormals(positions, indices, normals);
  38554. // Result
  38555. var vertexData = new VertexData();
  38556. vertexData.indices = indices;
  38557. vertexData.positions = positions;
  38558. vertexData.normals = normals;
  38559. vertexData.uvs = uvs;
  38560. return vertexData;
  38561. };
  38562. /**
  38563. * Creates the VertexData for a Plane
  38564. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38565. * * size sets the width and height of the plane to the value of size, optional default 1
  38566. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38567. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38568. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38569. * * 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)
  38570. * * 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)
  38571. * @returns the VertexData of the box
  38572. */
  38573. VertexData.CreatePlane = function (options) {
  38574. var indices = [];
  38575. var positions = [];
  38576. var normals = [];
  38577. var uvs = [];
  38578. var width = options.width || options.size || 1;
  38579. var height = options.height || options.size || 1;
  38580. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38581. // Vertices
  38582. var halfWidth = width / 2.0;
  38583. var halfHeight = height / 2.0;
  38584. positions.push(-halfWidth, -halfHeight, 0);
  38585. normals.push(0, 0, -1.0);
  38586. uvs.push(0.0, 0.0);
  38587. positions.push(halfWidth, -halfHeight, 0);
  38588. normals.push(0, 0, -1.0);
  38589. uvs.push(1.0, 0.0);
  38590. positions.push(halfWidth, halfHeight, 0);
  38591. normals.push(0, 0, -1.0);
  38592. uvs.push(1.0, 1.0);
  38593. positions.push(-halfWidth, halfHeight, 0);
  38594. normals.push(0, 0, -1.0);
  38595. uvs.push(0.0, 1.0);
  38596. // Indices
  38597. indices.push(0);
  38598. indices.push(1);
  38599. indices.push(2);
  38600. indices.push(0);
  38601. indices.push(2);
  38602. indices.push(3);
  38603. // Sides
  38604. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38605. // Result
  38606. var vertexData = new VertexData();
  38607. vertexData.indices = indices;
  38608. vertexData.positions = positions;
  38609. vertexData.normals = normals;
  38610. vertexData.uvs = uvs;
  38611. return vertexData;
  38612. };
  38613. /**
  38614. * Creates the VertexData of the Disc or regular Polygon
  38615. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38616. * * radius the radius of the disc, optional default 0.5
  38617. * * tessellation the number of polygon sides, optional, default 64
  38618. * * 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
  38619. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38620. * * 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)
  38621. * * 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)
  38622. * @returns the VertexData of the box
  38623. */
  38624. VertexData.CreateDisc = function (options) {
  38625. var positions = new Array();
  38626. var indices = new Array();
  38627. var normals = new Array();
  38628. var uvs = new Array();
  38629. var radius = options.radius || 0.5;
  38630. var tessellation = options.tessellation || 64;
  38631. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38632. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38633. // positions and uvs
  38634. positions.push(0, 0, 0); // disc center first
  38635. uvs.push(0.5, 0.5);
  38636. var theta = Math.PI * 2 * arc;
  38637. var step = theta / tessellation;
  38638. for (var a = 0; a < theta; a += step) {
  38639. var x = Math.cos(a);
  38640. var y = Math.sin(a);
  38641. var u = (x + 1) / 2;
  38642. var v = (1 - y) / 2;
  38643. positions.push(radius * x, radius * y, 0);
  38644. uvs.push(u, v);
  38645. }
  38646. if (arc === 1) {
  38647. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38648. uvs.push(uvs[2], uvs[3]);
  38649. }
  38650. //indices
  38651. var vertexNb = positions.length / 3;
  38652. for (var i = 1; i < vertexNb - 1; i++) {
  38653. indices.push(i + 1, 0, i);
  38654. }
  38655. // result
  38656. VertexData.ComputeNormals(positions, indices, normals);
  38657. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38658. var vertexData = new VertexData();
  38659. vertexData.indices = indices;
  38660. vertexData.positions = positions;
  38661. vertexData.normals = normals;
  38662. vertexData.uvs = uvs;
  38663. return vertexData;
  38664. };
  38665. /**
  38666. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38667. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38668. * @param polygon a mesh built from polygonTriangulation.build()
  38669. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38670. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38671. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38672. * @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)
  38673. * @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)
  38674. * @returns the VertexData of the Polygon
  38675. */
  38676. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38677. var faceUV = fUV || new Array(3);
  38678. var faceColors = fColors;
  38679. var colors = [];
  38680. // default face colors and UV if undefined
  38681. for (var f = 0; f < 3; f++) {
  38682. if (faceUV[f] === undefined) {
  38683. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38684. }
  38685. if (faceColors && faceColors[f] === undefined) {
  38686. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38687. }
  38688. }
  38689. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38690. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38691. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38692. var indices = polygon.getIndices();
  38693. // set face colours and textures
  38694. var idx = 0;
  38695. var face = 0;
  38696. for (var index = 0; index < normals.length; index += 3) {
  38697. //Edge Face no. 1
  38698. if (Math.abs(normals[index + 1]) < 0.001) {
  38699. face = 1;
  38700. }
  38701. //Top Face no. 0
  38702. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38703. face = 0;
  38704. }
  38705. //Bottom Face no. 2
  38706. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38707. face = 2;
  38708. }
  38709. idx = index / 3;
  38710. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38711. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38712. if (faceColors) {
  38713. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38714. }
  38715. }
  38716. // sides
  38717. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38718. // Result
  38719. var vertexData = new VertexData();
  38720. vertexData.indices = indices;
  38721. vertexData.positions = positions;
  38722. vertexData.normals = normals;
  38723. vertexData.uvs = uvs;
  38724. if (faceColors) {
  38725. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38726. vertexData.colors = totalColors;
  38727. }
  38728. return vertexData;
  38729. };
  38730. /**
  38731. * Creates the VertexData of the IcoSphere
  38732. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38733. * * radius the radius of the IcoSphere, optional default 1
  38734. * * radiusX allows stretching in the x direction, optional, default radius
  38735. * * radiusY allows stretching in the y direction, optional, default radius
  38736. * * radiusZ allows stretching in the z direction, optional, default radius
  38737. * * flat when true creates a flat shaded mesh, optional, default true
  38738. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38739. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38740. * * 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)
  38741. * * 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)
  38742. * @returns the VertexData of the IcoSphere
  38743. */
  38744. VertexData.CreateIcoSphere = function (options) {
  38745. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38746. var radius = options.radius || 1;
  38747. var flat = (options.flat === undefined) ? true : options.flat;
  38748. var subdivisions = options.subdivisions || 4;
  38749. var radiusX = options.radiusX || radius;
  38750. var radiusY = options.radiusY || radius;
  38751. var radiusZ = options.radiusZ || radius;
  38752. var t = (1 + Math.sqrt(5)) / 2;
  38753. // 12 vertex x,y,z
  38754. var ico_vertices = [
  38755. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38756. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38757. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38758. ];
  38759. // index of 3 vertex makes a face of icopshere
  38760. var ico_indices = [
  38761. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38762. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38763. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38764. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38765. ];
  38766. // vertex for uv have aliased position, not for UV
  38767. var vertices_unalias_id = [
  38768. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38769. // vertex alias
  38770. 0,
  38771. 2,
  38772. 3,
  38773. 3,
  38774. 3,
  38775. 4,
  38776. 7,
  38777. 8,
  38778. 9,
  38779. 9,
  38780. 10,
  38781. 11 // 23: B + 12
  38782. ];
  38783. // uv as integer step (not pixels !)
  38784. var ico_vertexuv = [
  38785. 5, 1, 3, 1, 6, 4, 0, 0,
  38786. 5, 3, 4, 2, 2, 2, 4, 0,
  38787. 2, 0, 1, 1, 6, 0, 6, 2,
  38788. // vertex alias (for same vertex on different faces)
  38789. 0, 4,
  38790. 3, 3,
  38791. 4, 4,
  38792. 3, 1,
  38793. 4, 2,
  38794. 4, 4,
  38795. 0, 2,
  38796. 1, 1,
  38797. 2, 2,
  38798. 3, 3,
  38799. 1, 3,
  38800. 2, 4 // 23: B + 12
  38801. ];
  38802. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38803. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38804. // First island of uv mapping
  38805. // v = 4h 3+ 2
  38806. // v = 3h 9+ 4
  38807. // v = 2h 9+ 5 B
  38808. // v = 1h 9 1 0
  38809. // v = 0h 3 8 7 A
  38810. // u = 0 1 2 3 4 5 6 *a
  38811. // Second island of uv mapping
  38812. // v = 4h 0+ B+ 4+
  38813. // v = 3h A+ 2+
  38814. // v = 2h 7+ 6 3+
  38815. // v = 1h 8+ 3+
  38816. // v = 0h
  38817. // u = 0 1 2 3 4 5 6 *a
  38818. // Face layout on texture UV mapping
  38819. // ============
  38820. // \ 4 /\ 16 / ======
  38821. // \ / \ / /\ 11 /
  38822. // \/ 7 \/ / \ /
  38823. // ======= / 10 \/
  38824. // /\ 17 /\ =======
  38825. // / \ / \ \ 15 /\
  38826. // / 8 \/ 12 \ \ / \
  38827. // ============ \/ 6 \
  38828. // \ 18 /\ ============
  38829. // \ / \ \ 5 /\ 0 /
  38830. // \/ 13 \ \ / \ /
  38831. // ======= \/ 1 \/
  38832. // =============
  38833. // /\ 19 /\ 2 /\
  38834. // / \ / \ / \
  38835. // / 14 \/ 9 \/ 3 \
  38836. // ===================
  38837. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38838. var ustep = 138 / 1024;
  38839. var vstep = 239 / 1024;
  38840. var uoffset = 60 / 1024;
  38841. var voffset = 26 / 1024;
  38842. // Second island should have margin, not to touch the first island
  38843. // avoid any borderline artefact in pixel rounding
  38844. var island_u_offset = -40 / 1024;
  38845. var island_v_offset = +20 / 1024;
  38846. // face is either island 0 or 1 :
  38847. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38848. var island = [
  38849. 0, 0, 0, 0, 1,
  38850. 0, 0, 1, 1, 0,
  38851. 0, 0, 1, 1, 0,
  38852. 0, 1, 1, 1, 0 // 15 - 19
  38853. ];
  38854. var indices = new Array();
  38855. var positions = new Array();
  38856. var normals = new Array();
  38857. var uvs = new Array();
  38858. var current_indice = 0;
  38859. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38860. var face_vertex_pos = new Array(3);
  38861. var face_vertex_uv = new Array(3);
  38862. var v012;
  38863. for (v012 = 0; v012 < 3; v012++) {
  38864. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38865. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38866. }
  38867. // create all with normals
  38868. for (var face = 0; face < 20; face++) {
  38869. // 3 vertex per face
  38870. for (v012 = 0; v012 < 3; v012++) {
  38871. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38872. var v_id = ico_indices[3 * face + v012];
  38873. // vertex have 3D position (x,y,z)
  38874. 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]);
  38875. // Normalize to get normal, then scale to radius
  38876. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38877. // uv Coordinates from vertex ID
  38878. 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);
  38879. }
  38880. // Subdivide the face (interpolate pos, norm, uv)
  38881. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38882. // - norm is linear interpolation of vertex corner normal
  38883. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38884. // - uv is linear interpolation
  38885. //
  38886. // Topology is as below for sub-divide by 2
  38887. // vertex shown as v0,v1,v2
  38888. // interp index is i1 to progress in range [v0,v1[
  38889. // interp index is i2 to progress in range [v0,v2[
  38890. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38891. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38892. //
  38893. //
  38894. // i2 v2
  38895. // ^ ^
  38896. // / / \
  38897. // / / \
  38898. // / / \
  38899. // / / (0,1) \
  38900. // / #---------\
  38901. // / / \ (0,0)'/ \
  38902. // / / \ / \
  38903. // / / \ / \
  38904. // / / (0,0) \ / (1,0) \
  38905. // / #---------#---------\
  38906. // v0 v1
  38907. //
  38908. // --------------------> i1
  38909. //
  38910. // interp of (i1,i2):
  38911. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38912. // along i1 : lerp(x0,x1, i1/(S-i2))
  38913. //
  38914. // centroid of triangle is needed to get help normal computation
  38915. // (c1,c2) are used for centroid location
  38916. var interp_vertex = function (i1, i2, c1, c2) {
  38917. // vertex is interpolated from
  38918. // - face_vertex_pos[0..2]
  38919. // - face_vertex_uv[0..2]
  38920. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38921. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38922. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38923. pos_interp.normalize();
  38924. var vertex_normal;
  38925. if (flat) {
  38926. // in flat mode, recalculate normal as face centroid normal
  38927. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38928. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38929. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38930. }
  38931. else {
  38932. // in smooth mode, recalculate normal from each single vertex position
  38933. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38934. }
  38935. // Vertex normal need correction due to X,Y,Z radius scaling
  38936. vertex_normal.x /= radiusX;
  38937. vertex_normal.y /= radiusY;
  38938. vertex_normal.z /= radiusZ;
  38939. vertex_normal.normalize();
  38940. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38941. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38942. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38943. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38944. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38945. uvs.push(uv_interp.x, uv_interp.y);
  38946. // push each vertex has member of a face
  38947. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38948. indices.push(current_indice);
  38949. current_indice++;
  38950. };
  38951. for (var i2 = 0; i2 < subdivisions; i2++) {
  38952. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38953. // face : (i1,i2) for /\ :
  38954. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38955. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38956. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38957. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38958. if (i1 + i2 + 1 < subdivisions) {
  38959. // face : (i1,i2)' for \/ :
  38960. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38961. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38962. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38963. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38964. }
  38965. }
  38966. }
  38967. }
  38968. // Sides
  38969. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38970. // Result
  38971. var vertexData = new VertexData();
  38972. vertexData.indices = indices;
  38973. vertexData.positions = positions;
  38974. vertexData.normals = normals;
  38975. vertexData.uvs = uvs;
  38976. return vertexData;
  38977. };
  38978. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38979. /**
  38980. * Creates the VertexData for a Polyhedron
  38981. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38982. * * type provided types are:
  38983. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38984. * * 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)
  38985. * * size the size of the IcoSphere, optional default 1
  38986. * * sizeX allows stretching in the x direction, optional, default size
  38987. * * sizeY allows stretching in the y direction, optional, default size
  38988. * * sizeZ allows stretching in the z direction, optional, default size
  38989. * * 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
  38990. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38991. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38992. * * flat when true creates a flat shaded mesh, optional, default true
  38993. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38994. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38995. * * 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)
  38996. * * 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)
  38997. * @returns the VertexData of the Polyhedron
  38998. */
  38999. VertexData.CreatePolyhedron = function (options) {
  39000. // provided polyhedron types :
  39001. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39002. // 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)
  39003. var polyhedra = [];
  39004. 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]] };
  39005. 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]] };
  39006. polyhedra[2] = {
  39007. 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]],
  39008. 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]]
  39009. };
  39010. polyhedra[3] = {
  39011. 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]],
  39012. 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]]
  39013. };
  39014. polyhedra[4] = {
  39015. 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]],
  39016. 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]]
  39017. };
  39018. 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]] };
  39019. 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]] };
  39020. 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]] };
  39021. 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]] };
  39022. 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]] };
  39023. 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]] };
  39024. 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]] };
  39025. 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]] };
  39026. 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]] };
  39027. polyhedra[14] = {
  39028. 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]],
  39029. 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]]
  39030. };
  39031. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39032. var size = options.size;
  39033. var sizeX = options.sizeX || size || 1;
  39034. var sizeY = options.sizeY || size || 1;
  39035. var sizeZ = options.sizeZ || size || 1;
  39036. var data = options.custom || polyhedra[type];
  39037. var nbfaces = data.face.length;
  39038. var faceUV = options.faceUV || new Array(nbfaces);
  39039. var faceColors = options.faceColors;
  39040. var flat = (options.flat === undefined) ? true : options.flat;
  39041. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39042. var positions = new Array();
  39043. var indices = new Array();
  39044. var normals = new Array();
  39045. var uvs = new Array();
  39046. var colors = new Array();
  39047. var index = 0;
  39048. var faceIdx = 0; // face cursor in the array "indexes"
  39049. var indexes = new Array();
  39050. var i = 0;
  39051. var f = 0;
  39052. var u, v, ang, x, y, tmp;
  39053. // default face colors and UV if undefined
  39054. if (flat) {
  39055. for (f = 0; f < nbfaces; f++) {
  39056. if (faceColors && faceColors[f] === undefined) {
  39057. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39058. }
  39059. if (faceUV && faceUV[f] === undefined) {
  39060. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39061. }
  39062. }
  39063. }
  39064. if (!flat) {
  39065. for (i = 0; i < data.vertex.length; i++) {
  39066. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39067. uvs.push(0, 0);
  39068. }
  39069. for (f = 0; f < nbfaces; f++) {
  39070. for (i = 0; i < data.face[f].length - 2; i++) {
  39071. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39072. }
  39073. }
  39074. }
  39075. else {
  39076. for (f = 0; f < nbfaces; f++) {
  39077. var fl = data.face[f].length; // number of vertices of the current face
  39078. ang = 2 * Math.PI / fl;
  39079. x = 0.5 * Math.tan(ang / 2);
  39080. y = 0.5;
  39081. // positions, uvs, colors
  39082. for (i = 0; i < fl; i++) {
  39083. // positions
  39084. 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);
  39085. indexes.push(index);
  39086. index++;
  39087. // uvs
  39088. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39089. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39090. uvs.push(u, v);
  39091. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39092. y = x * Math.sin(ang) + y * Math.cos(ang);
  39093. x = tmp;
  39094. // colors
  39095. if (faceColors) {
  39096. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39097. }
  39098. }
  39099. // indices from indexes
  39100. for (i = 0; i < fl - 2; i++) {
  39101. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39102. }
  39103. faceIdx += fl;
  39104. }
  39105. }
  39106. VertexData.ComputeNormals(positions, indices, normals);
  39107. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39108. var vertexData = new VertexData();
  39109. vertexData.positions = positions;
  39110. vertexData.indices = indices;
  39111. vertexData.normals = normals;
  39112. vertexData.uvs = uvs;
  39113. if (faceColors && flat) {
  39114. vertexData.colors = colors;
  39115. }
  39116. return vertexData;
  39117. };
  39118. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39119. /**
  39120. * Creates the VertexData for a TorusKnot
  39121. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  39122. * * radius the radius of the torus knot, optional, default 2
  39123. * * tube the thickness of the tube, optional, default 0.5
  39124. * * radialSegments the number of sides on each tube segments, optional, default 32
  39125. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  39126. * * p the number of windings around the z axis, optional, default 2
  39127. * * q the number of windings around the x axis, optional, default 3
  39128. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39129. * * 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)
  39130. * * 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)
  39131. * @returns the VertexData of the Torus Knot
  39132. */
  39133. VertexData.CreateTorusKnot = function (options) {
  39134. var indices = new Array();
  39135. var positions = new Array();
  39136. var normals = new Array();
  39137. var uvs = new Array();
  39138. var radius = options.radius || 2;
  39139. var tube = options.tube || 0.5;
  39140. var radialSegments = options.radialSegments || 32;
  39141. var tubularSegments = options.tubularSegments || 32;
  39142. var p = options.p || 2;
  39143. var q = options.q || 3;
  39144. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39145. // Helper
  39146. var getPos = function (angle) {
  39147. var cu = Math.cos(angle);
  39148. var su = Math.sin(angle);
  39149. var quOverP = q / p * angle;
  39150. var cs = Math.cos(quOverP);
  39151. var tx = radius * (2 + cs) * 0.5 * cu;
  39152. var ty = radius * (2 + cs) * su * 0.5;
  39153. var tz = radius * Math.sin(quOverP) * 0.5;
  39154. return new BABYLON.Vector3(tx, ty, tz);
  39155. };
  39156. // Vertices
  39157. var i;
  39158. var j;
  39159. for (i = 0; i <= radialSegments; i++) {
  39160. var modI = i % radialSegments;
  39161. var u = modI / radialSegments * 2 * p * Math.PI;
  39162. var p1 = getPos(u);
  39163. var p2 = getPos(u + 0.01);
  39164. var tang = p2.subtract(p1);
  39165. var n = p2.add(p1);
  39166. var bitan = BABYLON.Vector3.Cross(tang, n);
  39167. n = BABYLON.Vector3.Cross(bitan, tang);
  39168. bitan.normalize();
  39169. n.normalize();
  39170. for (j = 0; j < tubularSegments; j++) {
  39171. var modJ = j % tubularSegments;
  39172. var v = modJ / tubularSegments * 2 * Math.PI;
  39173. var cx = -tube * Math.cos(v);
  39174. var cy = tube * Math.sin(v);
  39175. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39176. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39177. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39178. uvs.push(i / radialSegments);
  39179. uvs.push(j / tubularSegments);
  39180. }
  39181. }
  39182. for (i = 0; i < radialSegments; i++) {
  39183. for (j = 0; j < tubularSegments; j++) {
  39184. var jNext = (j + 1) % tubularSegments;
  39185. var a = i * tubularSegments + j;
  39186. var b = (i + 1) * tubularSegments + j;
  39187. var c = (i + 1) * tubularSegments + jNext;
  39188. var d = i * tubularSegments + jNext;
  39189. indices.push(d);
  39190. indices.push(b);
  39191. indices.push(a);
  39192. indices.push(d);
  39193. indices.push(c);
  39194. indices.push(b);
  39195. }
  39196. }
  39197. // Normals
  39198. VertexData.ComputeNormals(positions, indices, normals);
  39199. // Sides
  39200. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39201. // Result
  39202. var vertexData = new VertexData();
  39203. vertexData.indices = indices;
  39204. vertexData.positions = positions;
  39205. vertexData.normals = normals;
  39206. vertexData.uvs = uvs;
  39207. return vertexData;
  39208. };
  39209. // Tools
  39210. /**
  39211. * Compute normals for given positions and indices
  39212. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39213. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39214. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39215. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39216. * * facetNormals : optional array of facet normals (vector3)
  39217. * * facetPositions : optional array of facet positions (vector3)
  39218. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39219. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39220. * * bInfo : optional bounding info, required for facetPartitioning computation
  39221. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39222. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39223. * * useRightHandedSystem: optional boolean to for right handed system computation
  39224. * * depthSort : optional boolean to enable the facet depth sort computation
  39225. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39226. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39227. */
  39228. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39229. // temporary scalar variables
  39230. var index = 0; // facet index
  39231. var p1p2x = 0.0; // p1p2 vector x coordinate
  39232. var p1p2y = 0.0; // p1p2 vector y coordinate
  39233. var p1p2z = 0.0; // p1p2 vector z coordinate
  39234. var p3p2x = 0.0; // p3p2 vector x coordinate
  39235. var p3p2y = 0.0; // p3p2 vector y coordinate
  39236. var p3p2z = 0.0; // p3p2 vector z coordinate
  39237. var faceNormalx = 0.0; // facet normal x coordinate
  39238. var faceNormaly = 0.0; // facet normal y coordinate
  39239. var faceNormalz = 0.0; // facet normal z coordinate
  39240. var length = 0.0; // facet normal length before normalization
  39241. var v1x = 0; // vector1 x index in the positions array
  39242. var v1y = 0; // vector1 y index in the positions array
  39243. var v1z = 0; // vector1 z index in the positions array
  39244. var v2x = 0; // vector2 x index in the positions array
  39245. var v2y = 0; // vector2 y index in the positions array
  39246. var v2z = 0; // vector2 z index in the positions array
  39247. var v3x = 0; // vector3 x index in the positions array
  39248. var v3y = 0; // vector3 y index in the positions array
  39249. var v3z = 0; // vector3 z index in the positions array
  39250. var computeFacetNormals = false;
  39251. var computeFacetPositions = false;
  39252. var computeFacetPartitioning = false;
  39253. var computeDepthSort = false;
  39254. var faceNormalSign = 1;
  39255. var ratio = 0;
  39256. var distanceTo = null;
  39257. if (options) {
  39258. computeFacetNormals = (options.facetNormals) ? true : false;
  39259. computeFacetPositions = (options.facetPositions) ? true : false;
  39260. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39261. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39262. ratio = options.ratio || 0;
  39263. computeDepthSort = (options.depthSort) ? true : false;
  39264. distanceTo = (options.distanceTo);
  39265. if (computeDepthSort) {
  39266. if (distanceTo === undefined) {
  39267. distanceTo = BABYLON.Vector3.Zero();
  39268. }
  39269. var depthSortedFacets = options.depthSortedFacets;
  39270. }
  39271. }
  39272. // facetPartitioning reinit if needed
  39273. var xSubRatio = 0;
  39274. var ySubRatio = 0;
  39275. var zSubRatio = 0;
  39276. var subSq = 0;
  39277. if (computeFacetPartitioning && options && options.bbSize) {
  39278. var ox = 0; // X partitioning index for facet position
  39279. var oy = 0; // Y partinioning index for facet position
  39280. var oz = 0; // Z partinioning index for facet position
  39281. var b1x = 0; // X partitioning index for facet v1 vertex
  39282. var b1y = 0; // Y partitioning index for facet v1 vertex
  39283. var b1z = 0; // z partitioning index for facet v1 vertex
  39284. var b2x = 0; // X partitioning index for facet v2 vertex
  39285. var b2y = 0; // Y partitioning index for facet v2 vertex
  39286. var b2z = 0; // Z partitioning index for facet v2 vertex
  39287. var b3x = 0; // X partitioning index for facet v3 vertex
  39288. var b3y = 0; // Y partitioning index for facet v3 vertex
  39289. var b3z = 0; // Z partitioning index for facet v3 vertex
  39290. var block_idx_o = 0; // facet barycenter block index
  39291. var block_idx_v1 = 0; // v1 vertex block index
  39292. var block_idx_v2 = 0; // v2 vertex block index
  39293. var block_idx_v3 = 0; // v3 vertex block index
  39294. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39295. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39296. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39297. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39298. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39299. subSq = options.subDiv.max * options.subDiv.max;
  39300. options.facetPartitioning.length = 0;
  39301. }
  39302. // reset the normals
  39303. for (index = 0; index < positions.length; index++) {
  39304. normals[index] = 0.0;
  39305. }
  39306. // Loop : 1 indice triplet = 1 facet
  39307. var nbFaces = (indices.length / 3) | 0;
  39308. for (index = 0; index < nbFaces; index++) {
  39309. // get the indexes of the coordinates of each vertex of the facet
  39310. v1x = indices[index * 3] * 3;
  39311. v1y = v1x + 1;
  39312. v1z = v1x + 2;
  39313. v2x = indices[index * 3 + 1] * 3;
  39314. v2y = v2x + 1;
  39315. v2z = v2x + 2;
  39316. v3x = indices[index * 3 + 2] * 3;
  39317. v3y = v3x + 1;
  39318. v3z = v3x + 2;
  39319. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39320. p1p2y = positions[v1y] - positions[v2y];
  39321. p1p2z = positions[v1z] - positions[v2z];
  39322. p3p2x = positions[v3x] - positions[v2x];
  39323. p3p2y = positions[v3y] - positions[v2y];
  39324. p3p2z = positions[v3z] - positions[v2z];
  39325. // compute the face normal with the cross product
  39326. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39327. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39328. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39329. // normalize this normal and store it in the array facetData
  39330. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39331. length = (length === 0) ? 1.0 : length;
  39332. faceNormalx /= length;
  39333. faceNormaly /= length;
  39334. faceNormalz /= length;
  39335. if (computeFacetNormals && options) {
  39336. options.facetNormals[index].x = faceNormalx;
  39337. options.facetNormals[index].y = faceNormaly;
  39338. options.facetNormals[index].z = faceNormalz;
  39339. }
  39340. if (computeFacetPositions && options) {
  39341. // compute and the facet barycenter coordinates in the array facetPositions
  39342. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39343. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39344. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39345. }
  39346. if (computeFacetPartitioning && options) {
  39347. // store the facet indexes in arrays in the main facetPartitioning array :
  39348. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39349. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39350. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39351. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39352. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39353. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39354. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39355. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39356. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39357. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39358. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39359. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39360. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39361. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39362. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39363. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39364. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39365. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39366. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39367. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39368. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39369. // push each facet index in each block containing the vertex
  39370. options.facetPartitioning[block_idx_v1].push(index);
  39371. if (block_idx_v2 != block_idx_v1) {
  39372. options.facetPartitioning[block_idx_v2].push(index);
  39373. }
  39374. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39375. options.facetPartitioning[block_idx_v3].push(index);
  39376. }
  39377. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39378. options.facetPartitioning[block_idx_o].push(index);
  39379. }
  39380. }
  39381. if (computeDepthSort && options && options.facetPositions) {
  39382. var dsf = depthSortedFacets[index];
  39383. dsf.ind = index * 3;
  39384. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39385. }
  39386. // compute the normals anyway
  39387. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39388. normals[v1y] += faceNormaly;
  39389. normals[v1z] += faceNormalz;
  39390. normals[v2x] += faceNormalx;
  39391. normals[v2y] += faceNormaly;
  39392. normals[v2z] += faceNormalz;
  39393. normals[v3x] += faceNormalx;
  39394. normals[v3y] += faceNormaly;
  39395. normals[v3z] += faceNormalz;
  39396. }
  39397. // last normalization of each normal
  39398. for (index = 0; index < normals.length / 3; index++) {
  39399. faceNormalx = normals[index * 3];
  39400. faceNormaly = normals[index * 3 + 1];
  39401. faceNormalz = normals[index * 3 + 2];
  39402. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39403. length = (length === 0) ? 1.0 : length;
  39404. faceNormalx /= length;
  39405. faceNormaly /= length;
  39406. faceNormalz /= length;
  39407. normals[index * 3] = faceNormalx;
  39408. normals[index * 3 + 1] = faceNormaly;
  39409. normals[index * 3 + 2] = faceNormalz;
  39410. }
  39411. };
  39412. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  39413. var li = indices.length;
  39414. var ln = normals.length;
  39415. var i;
  39416. var n;
  39417. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39418. switch (sideOrientation) {
  39419. case BABYLON.Mesh.FRONTSIDE:
  39420. // nothing changed
  39421. break;
  39422. case BABYLON.Mesh.BACKSIDE:
  39423. var tmp;
  39424. // indices
  39425. for (i = 0; i < li; i += 3) {
  39426. tmp = indices[i];
  39427. indices[i] = indices[i + 2];
  39428. indices[i + 2] = tmp;
  39429. }
  39430. // normals
  39431. for (n = 0; n < ln; n++) {
  39432. normals[n] = -normals[n];
  39433. }
  39434. break;
  39435. case BABYLON.Mesh.DOUBLESIDE:
  39436. // positions
  39437. var lp = positions.length;
  39438. var l = lp / 3;
  39439. for (var p = 0; p < lp; p++) {
  39440. positions[lp + p] = positions[p];
  39441. }
  39442. // indices
  39443. for (i = 0; i < li; i += 3) {
  39444. indices[i + li] = indices[i + 2] + l;
  39445. indices[i + 1 + li] = indices[i + 1] + l;
  39446. indices[i + 2 + li] = indices[i] + l;
  39447. }
  39448. // normals
  39449. for (n = 0; n < ln; n++) {
  39450. normals[ln + n] = -normals[n];
  39451. }
  39452. // uvs
  39453. var lu = uvs.length;
  39454. var u = 0;
  39455. for (u = 0; u < lu; u++) {
  39456. uvs[u + lu] = uvs[u];
  39457. }
  39458. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39459. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39460. u = 0;
  39461. for (i = 0; i < lu / 2; i++) {
  39462. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39463. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39464. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39465. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39466. u += 2;
  39467. }
  39468. break;
  39469. }
  39470. };
  39471. /**
  39472. * Applies VertexData created from the imported parameters to the geometry
  39473. * @param parsedVertexData the parsed data from an imported file
  39474. * @param geometry the geometry to apply the VertexData to
  39475. */
  39476. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39477. var vertexData = new VertexData();
  39478. // positions
  39479. var positions = parsedVertexData.positions;
  39480. if (positions) {
  39481. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39482. }
  39483. // normals
  39484. var normals = parsedVertexData.normals;
  39485. if (normals) {
  39486. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39487. }
  39488. // tangents
  39489. var tangents = parsedVertexData.tangents;
  39490. if (tangents) {
  39491. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39492. }
  39493. // uvs
  39494. var uvs = parsedVertexData.uvs;
  39495. if (uvs) {
  39496. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39497. }
  39498. // uv2s
  39499. var uv2s = parsedVertexData.uv2s;
  39500. if (uv2s) {
  39501. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39502. }
  39503. // uv3s
  39504. var uv3s = parsedVertexData.uv3s;
  39505. if (uv3s) {
  39506. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39507. }
  39508. // uv4s
  39509. var uv4s = parsedVertexData.uv4s;
  39510. if (uv4s) {
  39511. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39512. }
  39513. // uv5s
  39514. var uv5s = parsedVertexData.uv5s;
  39515. if (uv5s) {
  39516. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39517. }
  39518. // uv6s
  39519. var uv6s = parsedVertexData.uv6s;
  39520. if (uv6s) {
  39521. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39522. }
  39523. // colors
  39524. var colors = parsedVertexData.colors;
  39525. if (colors) {
  39526. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39527. }
  39528. // matricesIndices
  39529. var matricesIndices = parsedVertexData.matricesIndices;
  39530. if (matricesIndices) {
  39531. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39532. }
  39533. // matricesWeights
  39534. var matricesWeights = parsedVertexData.matricesWeights;
  39535. if (matricesWeights) {
  39536. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39537. }
  39538. // indices
  39539. var indices = parsedVertexData.indices;
  39540. if (indices) {
  39541. vertexData.indices = indices;
  39542. }
  39543. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39544. };
  39545. return VertexData;
  39546. }());
  39547. BABYLON.VertexData = VertexData;
  39548. })(BABYLON || (BABYLON = {}));
  39549. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39550. var BABYLON;
  39551. (function (BABYLON) {
  39552. /**
  39553. * Class used to store geometry data (vertex buffers + index buffer)
  39554. */
  39555. var Geometry = /** @class */ (function () {
  39556. /**
  39557. * Creates a new geometry
  39558. * @param id defines the unique ID
  39559. * @param scene defines the hosting scene
  39560. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39561. * @param updatable defines if geometry must be updatable (false by default)
  39562. * @param mesh defines the mesh that will be associated with the geometry
  39563. */
  39564. function Geometry(id, scene, vertexData, updatable, mesh) {
  39565. if (updatable === void 0) { updatable = false; }
  39566. if (mesh === void 0) { mesh = null; }
  39567. /**
  39568. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39569. */
  39570. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39571. this._totalVertices = 0;
  39572. this._isDisposed = false;
  39573. this._indexBufferIsUpdatable = false;
  39574. this.id = id;
  39575. this._engine = scene.getEngine();
  39576. this._meshes = [];
  39577. this._scene = scene;
  39578. //Init vertex buffer cache
  39579. this._vertexBuffers = {};
  39580. this._indices = [];
  39581. this._updatable = updatable;
  39582. // vertexData
  39583. if (vertexData) {
  39584. this.setAllVerticesData(vertexData, updatable);
  39585. }
  39586. else {
  39587. this._totalVertices = 0;
  39588. this._indices = [];
  39589. }
  39590. if (this._engine.getCaps().vertexArrayObject) {
  39591. this._vertexArrayObjects = {};
  39592. }
  39593. // applyToMesh
  39594. if (mesh) {
  39595. if (mesh.getClassName() === "LinesMesh") {
  39596. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39597. this._updateExtend();
  39598. }
  39599. this.applyToMesh(mesh);
  39600. mesh.computeWorldMatrix(true);
  39601. }
  39602. }
  39603. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39604. /**
  39605. * 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
  39606. */
  39607. get: function () {
  39608. return this._boundingBias;
  39609. },
  39610. /**
  39611. * 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
  39612. */
  39613. set: function (value) {
  39614. if (this._boundingBias) {
  39615. if (this._boundingBias.equals(value)) {
  39616. return;
  39617. }
  39618. this._boundingBias.copyFrom(value);
  39619. }
  39620. else {
  39621. this._boundingBias = value.clone();
  39622. }
  39623. this._updateBoundingInfo(true, null);
  39624. },
  39625. enumerable: true,
  39626. configurable: true
  39627. });
  39628. /**
  39629. * Static function used to attach a new empty geometry to a mesh
  39630. * @param mesh defines the mesh to attach the geometry to
  39631. * @returns the new {BABYLON.Geometry}
  39632. */
  39633. Geometry.CreateGeometryForMesh = function (mesh) {
  39634. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39635. geometry.applyToMesh(mesh);
  39636. return geometry;
  39637. };
  39638. Object.defineProperty(Geometry.prototype, "extend", {
  39639. /**
  39640. * Gets the current extend of the geometry
  39641. */
  39642. get: function () {
  39643. return this._extend;
  39644. },
  39645. enumerable: true,
  39646. configurable: true
  39647. });
  39648. /**
  39649. * Gets the hosting scene
  39650. * @returns the hosting {BABYLON.Scene}
  39651. */
  39652. Geometry.prototype.getScene = function () {
  39653. return this._scene;
  39654. };
  39655. /**
  39656. * Gets the hosting engine
  39657. * @returns the hosting {BABYLON.Engine}
  39658. */
  39659. Geometry.prototype.getEngine = function () {
  39660. return this._engine;
  39661. };
  39662. /**
  39663. * Defines if the geometry is ready to use
  39664. * @returns true if the geometry is ready to be used
  39665. */
  39666. Geometry.prototype.isReady = function () {
  39667. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39668. };
  39669. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39670. /**
  39671. * Gets a value indicating that the geometry should not be serialized
  39672. */
  39673. get: function () {
  39674. for (var index = 0; index < this._meshes.length; index++) {
  39675. if (!this._meshes[index].doNotSerialize) {
  39676. return false;
  39677. }
  39678. }
  39679. return true;
  39680. },
  39681. enumerable: true,
  39682. configurable: true
  39683. });
  39684. /** @hidden */
  39685. Geometry.prototype._rebuild = function () {
  39686. if (this._vertexArrayObjects) {
  39687. this._vertexArrayObjects = {};
  39688. }
  39689. // Index buffer
  39690. if (this._meshes.length !== 0 && this._indices) {
  39691. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39692. }
  39693. // Vertex buffers
  39694. for (var key in this._vertexBuffers) {
  39695. var vertexBuffer = this._vertexBuffers[key];
  39696. vertexBuffer._rebuild();
  39697. }
  39698. };
  39699. /**
  39700. * Affects all geometry data in one call
  39701. * @param vertexData defines the geometry data
  39702. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39703. */
  39704. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39705. vertexData.applyToGeometry(this, updatable);
  39706. this.notifyUpdate();
  39707. };
  39708. /**
  39709. * Set specific vertex data
  39710. * @param kind defines the data kind (Position, normal, etc...)
  39711. * @param data defines the vertex data to use
  39712. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39713. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39714. */
  39715. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39716. if (updatable === void 0) { updatable = false; }
  39717. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39718. this.setVerticesBuffer(buffer);
  39719. };
  39720. /**
  39721. * Removes a specific vertex data
  39722. * @param kind defines the data kind (Position, normal, etc...)
  39723. */
  39724. Geometry.prototype.removeVerticesData = function (kind) {
  39725. if (this._vertexBuffers[kind]) {
  39726. this._vertexBuffers[kind].dispose();
  39727. delete this._vertexBuffers[kind];
  39728. }
  39729. };
  39730. /**
  39731. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39732. * @param buffer defines the vertex buffer to use
  39733. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39734. */
  39735. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39736. if (totalVertices === void 0) { totalVertices = null; }
  39737. var kind = buffer.getKind();
  39738. if (this._vertexBuffers[kind]) {
  39739. this._vertexBuffers[kind].dispose();
  39740. }
  39741. this._vertexBuffers[kind] = buffer;
  39742. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39743. var data = buffer.getData();
  39744. if (totalVertices != null) {
  39745. this._totalVertices = totalVertices;
  39746. }
  39747. else {
  39748. if (data != null) {
  39749. this._totalVertices = data.length / (buffer.byteStride / 4);
  39750. }
  39751. }
  39752. this._updateExtend(data);
  39753. this._resetPointsArrayCache();
  39754. var meshes = this._meshes;
  39755. var numOfMeshes = meshes.length;
  39756. for (var index = 0; index < numOfMeshes; index++) {
  39757. var mesh = meshes[index];
  39758. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39759. mesh._createGlobalSubMesh(false);
  39760. mesh.computeWorldMatrix(true);
  39761. }
  39762. }
  39763. this.notifyUpdate(kind);
  39764. if (this._vertexArrayObjects) {
  39765. this._disposeVertexArrayObjects();
  39766. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39767. }
  39768. };
  39769. /**
  39770. * Update a specific vertex buffer
  39771. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39772. * It will do nothing if the buffer is not updatable
  39773. * @param kind defines the data kind (Position, normal, etc...)
  39774. * @param data defines the data to use
  39775. * @param offset defines the offset in the target buffer where to store the data
  39776. * @param useBytes set to true if the offset is in bytes
  39777. */
  39778. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39779. if (useBytes === void 0) { useBytes = false; }
  39780. var vertexBuffer = this.getVertexBuffer(kind);
  39781. if (!vertexBuffer) {
  39782. return;
  39783. }
  39784. vertexBuffer.updateDirectly(data, offset, useBytes);
  39785. this.notifyUpdate(kind);
  39786. };
  39787. /**
  39788. * Update a specific vertex buffer
  39789. * This function will create a new buffer if the current one is not updatable
  39790. * @param kind defines the data kind (Position, normal, etc...)
  39791. * @param data defines the data to use
  39792. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39793. */
  39794. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39795. if (updateExtends === void 0) { updateExtends = false; }
  39796. var vertexBuffer = this.getVertexBuffer(kind);
  39797. if (!vertexBuffer) {
  39798. return;
  39799. }
  39800. vertexBuffer.update(data);
  39801. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39802. this._updateBoundingInfo(updateExtends, data);
  39803. }
  39804. this.notifyUpdate(kind);
  39805. };
  39806. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39807. if (updateExtends) {
  39808. this._updateExtend(data);
  39809. }
  39810. var meshes = this._meshes;
  39811. var numOfMeshes = meshes.length;
  39812. this._resetPointsArrayCache();
  39813. for (var index = 0; index < numOfMeshes; index++) {
  39814. var mesh = meshes[index];
  39815. if (updateExtends) {
  39816. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39817. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39818. var subMesh = mesh.subMeshes[subIndex];
  39819. subMesh.refreshBoundingInfo();
  39820. }
  39821. }
  39822. }
  39823. };
  39824. /** @hidden */
  39825. Geometry.prototype._bind = function (effect, indexToBind) {
  39826. if (!effect) {
  39827. return;
  39828. }
  39829. if (indexToBind === undefined) {
  39830. indexToBind = this._indexBuffer;
  39831. }
  39832. var vbs = this.getVertexBuffers();
  39833. if (!vbs) {
  39834. return;
  39835. }
  39836. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39837. this._engine.bindBuffers(vbs, indexToBind, effect);
  39838. return;
  39839. }
  39840. // Using VAO
  39841. if (!this._vertexArrayObjects[effect.key]) {
  39842. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39843. }
  39844. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39845. };
  39846. /**
  39847. * Gets total number of vertices
  39848. * @returns the total number of vertices
  39849. */
  39850. Geometry.prototype.getTotalVertices = function () {
  39851. if (!this.isReady()) {
  39852. return 0;
  39853. }
  39854. return this._totalVertices;
  39855. };
  39856. /**
  39857. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39858. * @param kind defines the data kind (Position, normal, etc...)
  39859. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39860. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39861. * @returns a float array containing vertex data
  39862. */
  39863. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39864. var vertexBuffer = this.getVertexBuffer(kind);
  39865. if (!vertexBuffer) {
  39866. return null;
  39867. }
  39868. var data = vertexBuffer.getData();
  39869. if (!data) {
  39870. return null;
  39871. }
  39872. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39873. var count = this._totalVertices * vertexBuffer.getSize();
  39874. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39875. var copy_1 = new Array(count);
  39876. vertexBuffer.forEach(count, function (value, index) {
  39877. copy_1[index] = value;
  39878. });
  39879. return copy_1;
  39880. }
  39881. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39882. if (data instanceof Array) {
  39883. var offset = vertexBuffer.byteOffset / 4;
  39884. return BABYLON.Tools.Slice(data, offset, offset + count);
  39885. }
  39886. else if (data instanceof ArrayBuffer) {
  39887. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39888. }
  39889. else {
  39890. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39891. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39892. var result = new Float32Array(count);
  39893. var source = new Float32Array(data.buffer, offset, count);
  39894. result.set(source);
  39895. return result;
  39896. }
  39897. return new Float32Array(data.buffer, offset, count);
  39898. }
  39899. }
  39900. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39901. return BABYLON.Tools.Slice(data);
  39902. }
  39903. return data;
  39904. };
  39905. /**
  39906. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39907. * @param kind defines the data kind (Position, normal, etc...)
  39908. * @returns true if the vertex buffer with the specified kind is updatable
  39909. */
  39910. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39911. var vb = this._vertexBuffers[kind];
  39912. if (!vb) {
  39913. return false;
  39914. }
  39915. return vb.isUpdatable();
  39916. };
  39917. /**
  39918. * Gets a specific vertex buffer
  39919. * @param kind defines the data kind (Position, normal, etc...)
  39920. * @returns a {BABYLON.VertexBuffer}
  39921. */
  39922. Geometry.prototype.getVertexBuffer = function (kind) {
  39923. if (!this.isReady()) {
  39924. return null;
  39925. }
  39926. return this._vertexBuffers[kind];
  39927. };
  39928. /**
  39929. * Returns all vertex buffers
  39930. * @return an object holding all vertex buffers indexed by kind
  39931. */
  39932. Geometry.prototype.getVertexBuffers = function () {
  39933. if (!this.isReady()) {
  39934. return null;
  39935. }
  39936. return this._vertexBuffers;
  39937. };
  39938. /**
  39939. * Gets a boolean indicating if specific vertex buffer is present
  39940. * @param kind defines the data kind (Position, normal, etc...)
  39941. * @returns true if data is present
  39942. */
  39943. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39944. if (!this._vertexBuffers) {
  39945. if (this._delayInfo) {
  39946. return this._delayInfo.indexOf(kind) !== -1;
  39947. }
  39948. return false;
  39949. }
  39950. return this._vertexBuffers[kind] !== undefined;
  39951. };
  39952. /**
  39953. * Gets a list of all attached data kinds (Position, normal, etc...)
  39954. * @returns a list of string containing all kinds
  39955. */
  39956. Geometry.prototype.getVerticesDataKinds = function () {
  39957. var result = [];
  39958. var kind;
  39959. if (!this._vertexBuffers && this._delayInfo) {
  39960. for (kind in this._delayInfo) {
  39961. result.push(kind);
  39962. }
  39963. }
  39964. else {
  39965. for (kind in this._vertexBuffers) {
  39966. result.push(kind);
  39967. }
  39968. }
  39969. return result;
  39970. };
  39971. /**
  39972. * Update index buffer
  39973. * @param indices defines the indices to store in the index buffer
  39974. * @param offset defines the offset in the target buffer where to store the data
  39975. */
  39976. Geometry.prototype.updateIndices = function (indices, offset) {
  39977. if (!this._indexBuffer) {
  39978. return;
  39979. }
  39980. if (!this._indexBufferIsUpdatable) {
  39981. this.setIndices(indices, null, true);
  39982. }
  39983. else {
  39984. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39985. }
  39986. };
  39987. /**
  39988. * Creates a new index buffer
  39989. * @param indices defines the indices to store in the index buffer
  39990. * @param totalVertices defines the total number of vertices (could be null)
  39991. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39992. */
  39993. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39994. if (totalVertices === void 0) { totalVertices = null; }
  39995. if (updatable === void 0) { updatable = false; }
  39996. if (this._indexBuffer) {
  39997. this._engine._releaseBuffer(this._indexBuffer);
  39998. }
  39999. this._disposeVertexArrayObjects();
  40000. this._indices = indices;
  40001. this._indexBufferIsUpdatable = updatable;
  40002. if (this._meshes.length !== 0 && this._indices) {
  40003. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40004. }
  40005. if (totalVertices != undefined) { // including null and undefined
  40006. this._totalVertices = totalVertices;
  40007. }
  40008. var meshes = this._meshes;
  40009. var numOfMeshes = meshes.length;
  40010. for (var index = 0; index < numOfMeshes; index++) {
  40011. meshes[index]._createGlobalSubMesh(true);
  40012. }
  40013. this.notifyUpdate();
  40014. };
  40015. /**
  40016. * Return the total number of indices
  40017. * @returns the total number of indices
  40018. */
  40019. Geometry.prototype.getTotalIndices = function () {
  40020. if (!this.isReady()) {
  40021. return 0;
  40022. }
  40023. return this._indices.length;
  40024. };
  40025. /**
  40026. * Gets the index buffer array
  40027. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40028. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40029. * @returns the index buffer array
  40030. */
  40031. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40032. if (!this.isReady()) {
  40033. return null;
  40034. }
  40035. var orig = this._indices;
  40036. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40037. return orig;
  40038. }
  40039. else {
  40040. var len = orig.length;
  40041. var copy = [];
  40042. for (var i = 0; i < len; i++) {
  40043. copy.push(orig[i]);
  40044. }
  40045. return copy;
  40046. }
  40047. };
  40048. /**
  40049. * Gets the index buffer
  40050. * @return the index buffer
  40051. */
  40052. Geometry.prototype.getIndexBuffer = function () {
  40053. if (!this.isReady()) {
  40054. return null;
  40055. }
  40056. return this._indexBuffer;
  40057. };
  40058. /** @hidden */
  40059. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40060. if (effect === void 0) { effect = null; }
  40061. if (!effect || !this._vertexArrayObjects) {
  40062. return;
  40063. }
  40064. if (this._vertexArrayObjects[effect.key]) {
  40065. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40066. delete this._vertexArrayObjects[effect.key];
  40067. }
  40068. };
  40069. /**
  40070. * Release the associated resources for a specific mesh
  40071. * @param mesh defines the source mesh
  40072. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40073. */
  40074. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40075. var meshes = this._meshes;
  40076. var index = meshes.indexOf(mesh);
  40077. if (index === -1) {
  40078. return;
  40079. }
  40080. meshes.splice(index, 1);
  40081. mesh._geometry = null;
  40082. if (meshes.length === 0 && shouldDispose) {
  40083. this.dispose();
  40084. }
  40085. };
  40086. /**
  40087. * Apply current geometry to a given mesh
  40088. * @param mesh defines the mesh to apply geometry to
  40089. */
  40090. Geometry.prototype.applyToMesh = function (mesh) {
  40091. if (mesh._geometry === this) {
  40092. return;
  40093. }
  40094. var previousGeometry = mesh._geometry;
  40095. if (previousGeometry) {
  40096. previousGeometry.releaseForMesh(mesh);
  40097. }
  40098. var meshes = this._meshes;
  40099. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40100. mesh._geometry = this;
  40101. this._scene.pushGeometry(this);
  40102. meshes.push(mesh);
  40103. if (this.isReady()) {
  40104. this._applyToMesh(mesh);
  40105. }
  40106. else {
  40107. mesh._boundingInfo = this._boundingInfo;
  40108. }
  40109. };
  40110. Geometry.prototype._updateExtend = function (data) {
  40111. if (data === void 0) { data = null; }
  40112. if (!data) {
  40113. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40114. }
  40115. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  40116. };
  40117. Geometry.prototype._applyToMesh = function (mesh) {
  40118. var numOfMeshes = this._meshes.length;
  40119. // vertexBuffers
  40120. for (var kind in this._vertexBuffers) {
  40121. if (numOfMeshes === 1) {
  40122. this._vertexBuffers[kind].create();
  40123. }
  40124. var buffer = this._vertexBuffers[kind].getBuffer();
  40125. if (buffer)
  40126. buffer.references = numOfMeshes;
  40127. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40128. if (!this._extend) {
  40129. this._updateExtend();
  40130. }
  40131. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40132. mesh._createGlobalSubMesh(false);
  40133. //bounding info was just created again, world matrix should be applied again.
  40134. mesh._updateBoundingInfo();
  40135. }
  40136. }
  40137. // indexBuffer
  40138. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40139. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40140. }
  40141. if (this._indexBuffer) {
  40142. this._indexBuffer.references = numOfMeshes;
  40143. }
  40144. };
  40145. Geometry.prototype.notifyUpdate = function (kind) {
  40146. if (this.onGeometryUpdated) {
  40147. this.onGeometryUpdated(this, kind);
  40148. }
  40149. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  40150. var mesh = _a[_i];
  40151. mesh._markSubMeshesAsAttributesDirty();
  40152. }
  40153. };
  40154. /**
  40155. * Load the geometry if it was flagged as delay loaded
  40156. * @param scene defines the hosting scene
  40157. * @param onLoaded defines a callback called when the geometry is loaded
  40158. */
  40159. Geometry.prototype.load = function (scene, onLoaded) {
  40160. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  40161. return;
  40162. }
  40163. if (this.isReady()) {
  40164. if (onLoaded) {
  40165. onLoaded();
  40166. }
  40167. return;
  40168. }
  40169. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40170. this._queueLoad(scene, onLoaded);
  40171. };
  40172. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40173. var _this = this;
  40174. if (!this.delayLoadingFile) {
  40175. return;
  40176. }
  40177. scene._addPendingData(this);
  40178. scene._loadFile(this.delayLoadingFile, function (data) {
  40179. if (!_this._delayLoadingFunction) {
  40180. return;
  40181. }
  40182. _this._delayLoadingFunction(JSON.parse(data), _this);
  40183. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40184. _this._delayInfo = [];
  40185. scene._removePendingData(_this);
  40186. var meshes = _this._meshes;
  40187. var numOfMeshes = meshes.length;
  40188. for (var index = 0; index < numOfMeshes; index++) {
  40189. _this._applyToMesh(meshes[index]);
  40190. }
  40191. if (onLoaded) {
  40192. onLoaded();
  40193. }
  40194. }, undefined, true);
  40195. };
  40196. /**
  40197. * Invert the geometry to move from a right handed system to a left handed one.
  40198. */
  40199. Geometry.prototype.toLeftHanded = function () {
  40200. // Flip faces
  40201. var tIndices = this.getIndices(false);
  40202. if (tIndices != null && tIndices.length > 0) {
  40203. for (var i = 0; i < tIndices.length; i += 3) {
  40204. var tTemp = tIndices[i + 0];
  40205. tIndices[i + 0] = tIndices[i + 2];
  40206. tIndices[i + 2] = tTemp;
  40207. }
  40208. this.setIndices(tIndices);
  40209. }
  40210. // Negate position.z
  40211. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40212. if (tPositions != null && tPositions.length > 0) {
  40213. for (var i = 0; i < tPositions.length; i += 3) {
  40214. tPositions[i + 2] = -tPositions[i + 2];
  40215. }
  40216. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40217. }
  40218. // Negate normal.z
  40219. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40220. if (tNormals != null && tNormals.length > 0) {
  40221. for (var i = 0; i < tNormals.length; i += 3) {
  40222. tNormals[i + 2] = -tNormals[i + 2];
  40223. }
  40224. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40225. }
  40226. };
  40227. // Cache
  40228. /** @hidden */
  40229. Geometry.prototype._resetPointsArrayCache = function () {
  40230. this._positions = null;
  40231. };
  40232. /** @hidden */
  40233. Geometry.prototype._generatePointsArray = function () {
  40234. if (this._positions)
  40235. return true;
  40236. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40237. if (!data || data.length === 0) {
  40238. return false;
  40239. }
  40240. this._positions = [];
  40241. for (var index = 0; index < data.length; index += 3) {
  40242. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40243. }
  40244. return true;
  40245. };
  40246. /**
  40247. * Gets a value indicating if the geometry is disposed
  40248. * @returns true if the geometry was disposed
  40249. */
  40250. Geometry.prototype.isDisposed = function () {
  40251. return this._isDisposed;
  40252. };
  40253. Geometry.prototype._disposeVertexArrayObjects = function () {
  40254. if (this._vertexArrayObjects) {
  40255. for (var kind in this._vertexArrayObjects) {
  40256. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40257. }
  40258. this._vertexArrayObjects = {};
  40259. }
  40260. };
  40261. /**
  40262. * Free all associated resources
  40263. */
  40264. Geometry.prototype.dispose = function () {
  40265. var meshes = this._meshes;
  40266. var numOfMeshes = meshes.length;
  40267. var index;
  40268. for (index = 0; index < numOfMeshes; index++) {
  40269. this.releaseForMesh(meshes[index]);
  40270. }
  40271. this._meshes = [];
  40272. this._disposeVertexArrayObjects();
  40273. for (var kind in this._vertexBuffers) {
  40274. this._vertexBuffers[kind].dispose();
  40275. }
  40276. this._vertexBuffers = {};
  40277. this._totalVertices = 0;
  40278. if (this._indexBuffer) {
  40279. this._engine._releaseBuffer(this._indexBuffer);
  40280. }
  40281. this._indexBuffer = null;
  40282. this._indices = [];
  40283. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40284. this.delayLoadingFile = null;
  40285. this._delayLoadingFunction = null;
  40286. this._delayInfo = [];
  40287. this._boundingInfo = null;
  40288. this._scene.removeGeometry(this);
  40289. this._isDisposed = true;
  40290. };
  40291. /**
  40292. * Clone the current geometry into a new geometry
  40293. * @param id defines the unique ID of the new geometry
  40294. * @returns a new geometry object
  40295. */
  40296. Geometry.prototype.copy = function (id) {
  40297. var vertexData = new BABYLON.VertexData();
  40298. vertexData.indices = [];
  40299. var indices = this.getIndices();
  40300. if (indices) {
  40301. for (var index = 0; index < indices.length; index++) {
  40302. vertexData.indices.push(indices[index]);
  40303. }
  40304. }
  40305. var updatable = false;
  40306. var stopChecking = false;
  40307. var kind;
  40308. for (kind in this._vertexBuffers) {
  40309. // using slice() to make a copy of the array and not just reference it
  40310. var data = this.getVerticesData(kind);
  40311. if (data instanceof Float32Array) {
  40312. vertexData.set(new Float32Array(data), kind);
  40313. }
  40314. else {
  40315. vertexData.set(data.slice(0), kind);
  40316. }
  40317. if (!stopChecking) {
  40318. var vb = this.getVertexBuffer(kind);
  40319. if (vb) {
  40320. updatable = vb.isUpdatable();
  40321. stopChecking = !updatable;
  40322. }
  40323. }
  40324. }
  40325. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40326. geometry.delayLoadState = this.delayLoadState;
  40327. geometry.delayLoadingFile = this.delayLoadingFile;
  40328. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40329. for (kind in this._delayInfo) {
  40330. geometry._delayInfo = geometry._delayInfo || [];
  40331. geometry._delayInfo.push(kind);
  40332. }
  40333. // Bounding info
  40334. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40335. return geometry;
  40336. };
  40337. /**
  40338. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40339. * @return a JSON representation of the current geometry data (without the vertices data)
  40340. */
  40341. Geometry.prototype.serialize = function () {
  40342. var serializationObject = {};
  40343. serializationObject.id = this.id;
  40344. serializationObject.updatable = this._updatable;
  40345. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40346. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40347. }
  40348. return serializationObject;
  40349. };
  40350. Geometry.prototype.toNumberArray = function (origin) {
  40351. if (Array.isArray(origin)) {
  40352. return origin;
  40353. }
  40354. else {
  40355. return Array.prototype.slice.call(origin);
  40356. }
  40357. };
  40358. /**
  40359. * Serialize all vertices data into a JSON oject
  40360. * @returns a JSON representation of the current geometry data
  40361. */
  40362. Geometry.prototype.serializeVerticeData = function () {
  40363. var serializationObject = this.serialize();
  40364. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40365. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  40366. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  40367. serializationObject.positions._updatable = true;
  40368. }
  40369. }
  40370. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40371. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  40372. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  40373. serializationObject.normals._updatable = true;
  40374. }
  40375. }
  40376. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40377. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  40378. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  40379. serializationObject.tangets._updatable = true;
  40380. }
  40381. }
  40382. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40383. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40384. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40385. serializationObject.uvs._updatable = true;
  40386. }
  40387. }
  40388. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40389. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  40390. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  40391. serializationObject.uv2s._updatable = true;
  40392. }
  40393. }
  40394. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40395. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  40396. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  40397. serializationObject.uv3s._updatable = true;
  40398. }
  40399. }
  40400. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40401. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  40402. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  40403. serializationObject.uv4s._updatable = true;
  40404. }
  40405. }
  40406. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40407. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  40408. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  40409. serializationObject.uv5s._updatable = true;
  40410. }
  40411. }
  40412. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40413. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  40414. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  40415. serializationObject.uv6s._updatable = true;
  40416. }
  40417. }
  40418. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40419. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  40420. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  40421. serializationObject.colors._updatable = true;
  40422. }
  40423. }
  40424. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40425. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  40426. serializationObject.matricesIndices._isExpanded = true;
  40427. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40428. serializationObject.matricesIndices._updatable = true;
  40429. }
  40430. }
  40431. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40432. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  40433. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40434. serializationObject.matricesWeights._updatable = true;
  40435. }
  40436. }
  40437. serializationObject.indices = this.toNumberArray(this.getIndices());
  40438. return serializationObject;
  40439. };
  40440. // Statics
  40441. /**
  40442. * Extracts a clone of a mesh geometry
  40443. * @param mesh defines the source mesh
  40444. * @param id defines the unique ID of the new geometry object
  40445. * @returns the new geometry object
  40446. */
  40447. Geometry.ExtractFromMesh = function (mesh, id) {
  40448. var geometry = mesh._geometry;
  40449. if (!geometry) {
  40450. return null;
  40451. }
  40452. return geometry.copy(id);
  40453. };
  40454. /**
  40455. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40456. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40457. * Be aware Math.random() could cause collisions, but:
  40458. * "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"
  40459. * @returns a string containing a new GUID
  40460. */
  40461. Geometry.RandomId = function () {
  40462. return BABYLON.Tools.RandomId();
  40463. };
  40464. /** @hidden */
  40465. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40466. var scene = mesh.getScene();
  40467. // Geometry
  40468. var geometryId = parsedGeometry.geometryId;
  40469. if (geometryId) {
  40470. var geometry = scene.getGeometryByID(geometryId);
  40471. if (geometry) {
  40472. geometry.applyToMesh(mesh);
  40473. }
  40474. }
  40475. else if (parsedGeometry instanceof ArrayBuffer) {
  40476. var binaryInfo = mesh._binaryInfo;
  40477. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40478. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40479. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40480. }
  40481. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40482. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40483. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40484. }
  40485. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40486. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40487. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40488. }
  40489. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40490. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40491. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40492. }
  40493. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40494. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40495. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40496. }
  40497. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40498. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40499. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40500. }
  40501. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40502. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40503. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40504. }
  40505. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40506. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40507. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40508. }
  40509. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40510. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40511. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40512. }
  40513. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40514. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40515. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40516. }
  40517. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40518. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40519. var floatIndices = [];
  40520. for (var i = 0; i < matricesIndicesData.length; i++) {
  40521. var index = matricesIndicesData[i];
  40522. floatIndices.push(index & 0x000000FF);
  40523. floatIndices.push((index & 0x0000FF00) >> 8);
  40524. floatIndices.push((index & 0x00FF0000) >> 16);
  40525. floatIndices.push(index >> 24);
  40526. }
  40527. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  40528. }
  40529. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40530. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40531. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40532. }
  40533. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40534. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40535. mesh.setIndices(indicesData, null);
  40536. }
  40537. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40538. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40539. mesh.subMeshes = [];
  40540. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40541. var materialIndex = subMeshesData[(i * 5) + 0];
  40542. var verticesStart = subMeshesData[(i * 5) + 1];
  40543. var verticesCount = subMeshesData[(i * 5) + 2];
  40544. var indexStart = subMeshesData[(i * 5) + 3];
  40545. var indexCount = subMeshesData[(i * 5) + 4];
  40546. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40547. }
  40548. }
  40549. }
  40550. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40551. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40552. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40553. if (parsedGeometry.tangents) {
  40554. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40555. }
  40556. if (parsedGeometry.uvs) {
  40557. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40558. }
  40559. if (parsedGeometry.uvs2) {
  40560. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40561. }
  40562. if (parsedGeometry.uvs3) {
  40563. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40564. }
  40565. if (parsedGeometry.uvs4) {
  40566. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40567. }
  40568. if (parsedGeometry.uvs5) {
  40569. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40570. }
  40571. if (parsedGeometry.uvs6) {
  40572. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40573. }
  40574. if (parsedGeometry.colors) {
  40575. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40576. }
  40577. if (parsedGeometry.matricesIndices) {
  40578. if (!parsedGeometry.matricesIndices._isExpanded) {
  40579. var floatIndices = [];
  40580. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40581. var matricesIndex = parsedGeometry.matricesIndices[i];
  40582. floatIndices.push(matricesIndex & 0x000000FF);
  40583. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40584. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40585. floatIndices.push(matricesIndex >> 24);
  40586. }
  40587. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40588. }
  40589. else {
  40590. delete parsedGeometry.matricesIndices._isExpanded;
  40591. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40592. }
  40593. }
  40594. if (parsedGeometry.matricesIndicesExtra) {
  40595. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40596. var floatIndices = [];
  40597. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40598. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40599. floatIndices.push(matricesIndex & 0x000000FF);
  40600. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40601. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40602. floatIndices.push(matricesIndex >> 24);
  40603. }
  40604. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40605. }
  40606. else {
  40607. delete parsedGeometry.matricesIndices._isExpanded;
  40608. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40609. }
  40610. }
  40611. if (parsedGeometry.matricesWeights) {
  40612. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40613. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40614. }
  40615. if (parsedGeometry.matricesWeightsExtra) {
  40616. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40617. }
  40618. mesh.setIndices(parsedGeometry.indices, null);
  40619. }
  40620. // SubMeshes
  40621. if (parsedGeometry.subMeshes) {
  40622. mesh.subMeshes = [];
  40623. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40624. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40625. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40626. }
  40627. }
  40628. // Flat shading
  40629. if (mesh._shouldGenerateFlatShading) {
  40630. mesh.convertToFlatShadedMesh();
  40631. delete mesh._shouldGenerateFlatShading;
  40632. }
  40633. // Update
  40634. mesh.computeWorldMatrix(true);
  40635. scene.onMeshImportedObservable.notifyObservers(mesh);
  40636. };
  40637. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40638. var epsilon = 1e-3;
  40639. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40640. return;
  40641. }
  40642. var noInfluenceBoneIndex = 0.0;
  40643. if (parsedGeometry.skeletonId > -1) {
  40644. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40645. if (!skeleton) {
  40646. return;
  40647. }
  40648. noInfluenceBoneIndex = skeleton.bones.length;
  40649. }
  40650. else {
  40651. return;
  40652. }
  40653. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40654. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40655. var matricesWeights = parsedGeometry.matricesWeights;
  40656. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40657. var influencers = parsedGeometry.numBoneInfluencer;
  40658. var size = matricesWeights.length;
  40659. for (var i = 0; i < size; i += 4) {
  40660. var weight = 0.0;
  40661. var firstZeroWeight = -1;
  40662. for (var j = 0; j < 4; j++) {
  40663. var w = matricesWeights[i + j];
  40664. weight += w;
  40665. if (w < epsilon && firstZeroWeight < 0) {
  40666. firstZeroWeight = j;
  40667. }
  40668. }
  40669. if (matricesWeightsExtra) {
  40670. for (var j = 0; j < 4; j++) {
  40671. var w = matricesWeightsExtra[i + j];
  40672. weight += w;
  40673. if (w < epsilon && firstZeroWeight < 0) {
  40674. firstZeroWeight = j + 4;
  40675. }
  40676. }
  40677. }
  40678. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40679. firstZeroWeight = influencers - 1;
  40680. }
  40681. if (weight > epsilon) {
  40682. var mweight = 1.0 / weight;
  40683. for (var j = 0; j < 4; j++) {
  40684. matricesWeights[i + j] *= mweight;
  40685. }
  40686. if (matricesWeightsExtra) {
  40687. for (var j = 0; j < 4; j++) {
  40688. matricesWeightsExtra[i + j] *= mweight;
  40689. }
  40690. }
  40691. }
  40692. else {
  40693. if (firstZeroWeight >= 4) {
  40694. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40695. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40696. }
  40697. else {
  40698. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40699. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40700. }
  40701. }
  40702. }
  40703. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40704. if (parsedGeometry.matricesWeightsExtra) {
  40705. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40706. }
  40707. };
  40708. /**
  40709. * Create a new geometry from persisted data (Using .babylon file format)
  40710. * @param parsedVertexData defines the persisted data
  40711. * @param scene defines the hosting scene
  40712. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40713. * @returns the new geometry object
  40714. */
  40715. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40716. if (scene.getGeometryByID(parsedVertexData.id)) {
  40717. return null; // null since geometry could be something else than a box...
  40718. }
  40719. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40720. if (BABYLON.Tags) {
  40721. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40722. }
  40723. if (parsedVertexData.delayLoadingFile) {
  40724. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40725. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40726. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40727. geometry._delayInfo = [];
  40728. if (parsedVertexData.hasUVs) {
  40729. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40730. }
  40731. if (parsedVertexData.hasUVs2) {
  40732. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40733. }
  40734. if (parsedVertexData.hasUVs3) {
  40735. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40736. }
  40737. if (parsedVertexData.hasUVs4) {
  40738. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40739. }
  40740. if (parsedVertexData.hasUVs5) {
  40741. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40742. }
  40743. if (parsedVertexData.hasUVs6) {
  40744. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40745. }
  40746. if (parsedVertexData.hasColors) {
  40747. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40748. }
  40749. if (parsedVertexData.hasMatricesIndices) {
  40750. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40751. }
  40752. if (parsedVertexData.hasMatricesWeights) {
  40753. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40754. }
  40755. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40756. }
  40757. else {
  40758. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40759. }
  40760. scene.pushGeometry(geometry, true);
  40761. return geometry;
  40762. };
  40763. return Geometry;
  40764. }());
  40765. BABYLON.Geometry = Geometry;
  40766. // Primitives
  40767. /// Abstract class
  40768. /**
  40769. * Abstract class used to provide common services for all typed geometries
  40770. * @hidden
  40771. */
  40772. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40773. __extends(_PrimitiveGeometry, _super);
  40774. /**
  40775. * Creates a new typed geometry
  40776. * @param id defines the unique ID of the geometry
  40777. * @param scene defines the hosting scene
  40778. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40779. * @param mesh defines the hosting mesh (can be null)
  40780. */
  40781. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40782. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40783. if (mesh === void 0) { mesh = null; }
  40784. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40785. _this._canBeRegenerated = _canBeRegenerated;
  40786. _this._beingRegenerated = true;
  40787. _this.regenerate();
  40788. _this._beingRegenerated = false;
  40789. return _this;
  40790. }
  40791. /**
  40792. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40793. * @returns true if the geometry can be regenerated
  40794. */
  40795. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40796. return this._canBeRegenerated;
  40797. };
  40798. /**
  40799. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40800. */
  40801. _PrimitiveGeometry.prototype.regenerate = function () {
  40802. if (!this._canBeRegenerated) {
  40803. return;
  40804. }
  40805. this._beingRegenerated = true;
  40806. this.setAllVerticesData(this._regenerateVertexData(), false);
  40807. this._beingRegenerated = false;
  40808. };
  40809. /**
  40810. * Clone the geometry
  40811. * @param id defines the unique ID of the new geometry
  40812. * @returns the new geometry
  40813. */
  40814. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40815. return _super.prototype.copy.call(this, id);
  40816. };
  40817. // overrides
  40818. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40819. if (!this._beingRegenerated) {
  40820. return;
  40821. }
  40822. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40823. };
  40824. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40825. if (!this._beingRegenerated) {
  40826. return;
  40827. }
  40828. _super.prototype.setVerticesData.call(this, kind, data, false);
  40829. };
  40830. // to override
  40831. /** @hidden */
  40832. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40833. throw new Error("Abstract method");
  40834. };
  40835. _PrimitiveGeometry.prototype.copy = function (id) {
  40836. throw new Error("Must be overriden in sub-classes.");
  40837. };
  40838. _PrimitiveGeometry.prototype.serialize = function () {
  40839. var serializationObject = _super.prototype.serialize.call(this);
  40840. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40841. return serializationObject;
  40842. };
  40843. return _PrimitiveGeometry;
  40844. }(Geometry));
  40845. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40846. /**
  40847. * Creates a ribbon geometry
  40848. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40849. */
  40850. var RibbonGeometry = /** @class */ (function (_super) {
  40851. __extends(RibbonGeometry, _super);
  40852. /**
  40853. * Creates a ribbon geometry
  40854. * @param id defines the unique ID of the geometry
  40855. * @param scene defines the hosting scene
  40856. * @param pathArray defines the array of paths to use
  40857. * @param closeArray defines if the last path and the first path must be joined
  40858. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40859. * @param offset defines the offset between points
  40860. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40861. * @param mesh defines the hosting mesh (can be null)
  40862. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40863. */
  40864. function RibbonGeometry(id, scene,
  40865. /**
  40866. * Defines the array of paths to use
  40867. */
  40868. pathArray,
  40869. /**
  40870. * Defines if the last and first points of each path in your pathArray must be joined
  40871. */
  40872. closeArray,
  40873. /**
  40874. * Defines if the last and first points of each path in your pathArray must be joined
  40875. */
  40876. closePath,
  40877. /**
  40878. * Defines the offset between points
  40879. */
  40880. offset, canBeRegenerated, mesh,
  40881. /**
  40882. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40883. */
  40884. side) {
  40885. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40886. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40887. _this.pathArray = pathArray;
  40888. _this.closeArray = closeArray;
  40889. _this.closePath = closePath;
  40890. _this.offset = offset;
  40891. _this.side = side;
  40892. return _this;
  40893. }
  40894. /** @hidden */
  40895. RibbonGeometry.prototype._regenerateVertexData = function () {
  40896. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40897. };
  40898. RibbonGeometry.prototype.copy = function (id) {
  40899. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40900. };
  40901. return RibbonGeometry;
  40902. }(_PrimitiveGeometry));
  40903. BABYLON.RibbonGeometry = RibbonGeometry;
  40904. /**
  40905. * Creates a box geometry
  40906. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40907. */
  40908. var BoxGeometry = /** @class */ (function (_super) {
  40909. __extends(BoxGeometry, _super);
  40910. /**
  40911. * Creates a box geometry
  40912. * @param id defines the unique ID of the geometry
  40913. * @param scene defines the hosting scene
  40914. * @param size defines the zise of the box (width, height and depth are the same)
  40915. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40916. * @param mesh defines the hosting mesh (can be null)
  40917. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40918. */
  40919. function BoxGeometry(id, scene,
  40920. /**
  40921. * Defines the zise of the box (width, height and depth are the same)
  40922. */
  40923. size, canBeRegenerated, mesh,
  40924. /**
  40925. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40926. */
  40927. side) {
  40928. if (mesh === void 0) { mesh = null; }
  40929. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40930. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40931. _this.size = size;
  40932. _this.side = side;
  40933. return _this;
  40934. }
  40935. /** @hidden */
  40936. BoxGeometry.prototype._regenerateVertexData = function () {
  40937. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40938. };
  40939. BoxGeometry.prototype.copy = function (id) {
  40940. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40941. };
  40942. BoxGeometry.prototype.serialize = function () {
  40943. var serializationObject = _super.prototype.serialize.call(this);
  40944. serializationObject.size = this.size;
  40945. return serializationObject;
  40946. };
  40947. BoxGeometry.Parse = function (parsedBox, scene) {
  40948. if (scene.getGeometryByID(parsedBox.id)) {
  40949. return null; // null since geometry could be something else than a box...
  40950. }
  40951. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40952. if (BABYLON.Tags) {
  40953. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40954. }
  40955. scene.pushGeometry(box, true);
  40956. return box;
  40957. };
  40958. return BoxGeometry;
  40959. }(_PrimitiveGeometry));
  40960. BABYLON.BoxGeometry = BoxGeometry;
  40961. /**
  40962. * Creates a sphere geometry
  40963. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40964. */
  40965. var SphereGeometry = /** @class */ (function (_super) {
  40966. __extends(SphereGeometry, _super);
  40967. /**
  40968. * Create a new sphere geometry
  40969. * @param id defines the unique ID of the geometry
  40970. * @param scene defines the hosting scene
  40971. * @param segments defines the number of segments to use to create the sphere
  40972. * @param diameter defines the diameter of the sphere
  40973. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40974. * @param mesh defines the hosting mesh (can be null)
  40975. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40976. */
  40977. function SphereGeometry(id, scene,
  40978. /**
  40979. * Defines the number of segments to use to create the sphere
  40980. */
  40981. segments,
  40982. /**
  40983. * Defines the diameter of the sphere
  40984. */
  40985. diameter, canBeRegenerated, mesh,
  40986. /**
  40987. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40988. */
  40989. side) {
  40990. if (mesh === void 0) { mesh = null; }
  40991. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40992. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40993. _this.segments = segments;
  40994. _this.diameter = diameter;
  40995. _this.side = side;
  40996. return _this;
  40997. }
  40998. /** @hidden */
  40999. SphereGeometry.prototype._regenerateVertexData = function () {
  41000. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41001. };
  41002. SphereGeometry.prototype.copy = function (id) {
  41003. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41004. };
  41005. SphereGeometry.prototype.serialize = function () {
  41006. var serializationObject = _super.prototype.serialize.call(this);
  41007. serializationObject.segments = this.segments;
  41008. serializationObject.diameter = this.diameter;
  41009. return serializationObject;
  41010. };
  41011. SphereGeometry.Parse = function (parsedSphere, scene) {
  41012. if (scene.getGeometryByID(parsedSphere.id)) {
  41013. return null; // null since geometry could be something else than a sphere...
  41014. }
  41015. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41016. if (BABYLON.Tags) {
  41017. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41018. }
  41019. scene.pushGeometry(sphere, true);
  41020. return sphere;
  41021. };
  41022. return SphereGeometry;
  41023. }(_PrimitiveGeometry));
  41024. BABYLON.SphereGeometry = SphereGeometry;
  41025. /**
  41026. * Creates a disc geometry
  41027. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41028. */
  41029. var DiscGeometry = /** @class */ (function (_super) {
  41030. __extends(DiscGeometry, _super);
  41031. /**
  41032. * Creates a new disc geometry
  41033. * @param id defines the unique ID of the geometry
  41034. * @param scene defines the hosting scene
  41035. * @param radius defines the radius of the disc
  41036. * @param tessellation defines the tesselation factor to apply to the disc
  41037. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41038. * @param mesh defines the hosting mesh (can be null)
  41039. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41040. */
  41041. function DiscGeometry(id, scene,
  41042. /**
  41043. * Defines the radius of the disc
  41044. */
  41045. radius,
  41046. /**
  41047. * Defines the tesselation factor to apply to the disc
  41048. */
  41049. tessellation, canBeRegenerated, mesh,
  41050. /**
  41051. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41052. */
  41053. side) {
  41054. if (mesh === void 0) { mesh = null; }
  41055. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41056. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41057. _this.radius = radius;
  41058. _this.tessellation = tessellation;
  41059. _this.side = side;
  41060. return _this;
  41061. }
  41062. /** @hidden */
  41063. DiscGeometry.prototype._regenerateVertexData = function () {
  41064. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41065. };
  41066. DiscGeometry.prototype.copy = function (id) {
  41067. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41068. };
  41069. return DiscGeometry;
  41070. }(_PrimitiveGeometry));
  41071. BABYLON.DiscGeometry = DiscGeometry;
  41072. /**
  41073. * Creates a new cylinder geometry
  41074. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41075. */
  41076. var CylinderGeometry = /** @class */ (function (_super) {
  41077. __extends(CylinderGeometry, _super);
  41078. /**
  41079. * Creates a new cylinder geometry
  41080. * @param id defines the unique ID of the geometry
  41081. * @param scene defines the hosting scene
  41082. * @param height defines the height of the cylinder
  41083. * @param diameterTop defines the diameter of the cylinder's top cap
  41084. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41085. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41086. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41087. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41088. * @param mesh defines the hosting mesh (can be null)
  41089. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41090. */
  41091. function CylinderGeometry(id, scene,
  41092. /**
  41093. * Defines the height of the cylinder
  41094. */
  41095. height,
  41096. /**
  41097. * Defines the diameter of the cylinder's top cap
  41098. */
  41099. diameterTop,
  41100. /**
  41101. * Defines the diameter of the cylinder's bottom cap
  41102. */
  41103. diameterBottom,
  41104. /**
  41105. * Defines the tessellation factor to apply to the cylinder
  41106. */
  41107. tessellation,
  41108. /**
  41109. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  41110. */
  41111. subdivisions, canBeRegenerated, mesh,
  41112. /**
  41113. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41114. */
  41115. side) {
  41116. if (subdivisions === void 0) { subdivisions = 1; }
  41117. if (mesh === void 0) { mesh = null; }
  41118. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41119. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41120. _this.height = height;
  41121. _this.diameterTop = diameterTop;
  41122. _this.diameterBottom = diameterBottom;
  41123. _this.tessellation = tessellation;
  41124. _this.subdivisions = subdivisions;
  41125. _this.side = side;
  41126. return _this;
  41127. }
  41128. /** @hidden */
  41129. CylinderGeometry.prototype._regenerateVertexData = function () {
  41130. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41131. };
  41132. CylinderGeometry.prototype.copy = function (id) {
  41133. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41134. };
  41135. CylinderGeometry.prototype.serialize = function () {
  41136. var serializationObject = _super.prototype.serialize.call(this);
  41137. serializationObject.height = this.height;
  41138. serializationObject.diameterTop = this.diameterTop;
  41139. serializationObject.diameterBottom = this.diameterBottom;
  41140. serializationObject.tessellation = this.tessellation;
  41141. return serializationObject;
  41142. };
  41143. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  41144. if (scene.getGeometryByID(parsedCylinder.id)) {
  41145. return null; // null since geometry could be something else than a cylinder...
  41146. }
  41147. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41148. if (BABYLON.Tags) {
  41149. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41150. }
  41151. scene.pushGeometry(cylinder, true);
  41152. return cylinder;
  41153. };
  41154. return CylinderGeometry;
  41155. }(_PrimitiveGeometry));
  41156. BABYLON.CylinderGeometry = CylinderGeometry;
  41157. /**
  41158. * Creates a new torus geometry
  41159. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  41160. */
  41161. var TorusGeometry = /** @class */ (function (_super) {
  41162. __extends(TorusGeometry, _super);
  41163. /**
  41164. * Creates a new torus geometry
  41165. * @param id defines the unique ID of the geometry
  41166. * @param scene defines the hosting scene
  41167. * @param diameter defines the diameter of the torus
  41168. * @param thickness defines the thickness of the torus (ie. internal diameter)
  41169. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  41170. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41171. * @param mesh defines the hosting mesh (can be null)
  41172. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41173. */
  41174. function TorusGeometry(id, scene,
  41175. /**
  41176. * Defines the diameter of the torus
  41177. */
  41178. diameter,
  41179. /**
  41180. * Defines the thickness of the torus (ie. internal diameter)
  41181. */
  41182. thickness,
  41183. /**
  41184. * Defines the tesselation factor to apply to the torus
  41185. */
  41186. tessellation, canBeRegenerated, mesh,
  41187. /**
  41188. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41189. */
  41190. side) {
  41191. if (mesh === void 0) { mesh = null; }
  41192. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41193. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41194. _this.diameter = diameter;
  41195. _this.thickness = thickness;
  41196. _this.tessellation = tessellation;
  41197. _this.side = side;
  41198. return _this;
  41199. }
  41200. /** @hidden */
  41201. TorusGeometry.prototype._regenerateVertexData = function () {
  41202. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41203. };
  41204. TorusGeometry.prototype.copy = function (id) {
  41205. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41206. };
  41207. TorusGeometry.prototype.serialize = function () {
  41208. var serializationObject = _super.prototype.serialize.call(this);
  41209. serializationObject.diameter = this.diameter;
  41210. serializationObject.thickness = this.thickness;
  41211. serializationObject.tessellation = this.tessellation;
  41212. return serializationObject;
  41213. };
  41214. TorusGeometry.Parse = function (parsedTorus, scene) {
  41215. if (scene.getGeometryByID(parsedTorus.id)) {
  41216. return null; // null since geometry could be something else than a torus...
  41217. }
  41218. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41219. if (BABYLON.Tags) {
  41220. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41221. }
  41222. scene.pushGeometry(torus, true);
  41223. return torus;
  41224. };
  41225. return TorusGeometry;
  41226. }(_PrimitiveGeometry));
  41227. BABYLON.TorusGeometry = TorusGeometry;
  41228. /**
  41229. * Creates a new ground geometry
  41230. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41231. */
  41232. var GroundGeometry = /** @class */ (function (_super) {
  41233. __extends(GroundGeometry, _super);
  41234. /**
  41235. * Creates a new ground geometry
  41236. * @param id defines the unique ID of the geometry
  41237. * @param scene defines the hosting scene
  41238. * @param width defines the width of the ground
  41239. * @param height defines the height of the ground
  41240. * @param subdivisions defines the subdivisions to apply to the ground
  41241. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41242. * @param mesh defines the hosting mesh (can be null)
  41243. */
  41244. function GroundGeometry(id, scene,
  41245. /**
  41246. * Defines the width of the ground
  41247. */
  41248. width,
  41249. /**
  41250. * Defines the height of the ground
  41251. */
  41252. height,
  41253. /**
  41254. * Defines the subdivisions to apply to the ground
  41255. */
  41256. subdivisions, canBeRegenerated, mesh) {
  41257. if (mesh === void 0) { mesh = null; }
  41258. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41259. _this.width = width;
  41260. _this.height = height;
  41261. _this.subdivisions = subdivisions;
  41262. return _this;
  41263. }
  41264. /** @hidden */
  41265. GroundGeometry.prototype._regenerateVertexData = function () {
  41266. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41267. };
  41268. GroundGeometry.prototype.copy = function (id) {
  41269. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41270. };
  41271. GroundGeometry.prototype.serialize = function () {
  41272. var serializationObject = _super.prototype.serialize.call(this);
  41273. serializationObject.width = this.width;
  41274. serializationObject.height = this.height;
  41275. serializationObject.subdivisions = this.subdivisions;
  41276. return serializationObject;
  41277. };
  41278. GroundGeometry.Parse = function (parsedGround, scene) {
  41279. if (scene.getGeometryByID(parsedGround.id)) {
  41280. return null; // null since geometry could be something else than a ground...
  41281. }
  41282. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41283. if (BABYLON.Tags) {
  41284. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41285. }
  41286. scene.pushGeometry(ground, true);
  41287. return ground;
  41288. };
  41289. return GroundGeometry;
  41290. }(_PrimitiveGeometry));
  41291. BABYLON.GroundGeometry = GroundGeometry;
  41292. /**
  41293. * Creates a tiled ground geometry
  41294. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41295. */
  41296. var TiledGroundGeometry = /** @class */ (function (_super) {
  41297. __extends(TiledGroundGeometry, _super);
  41298. /**
  41299. * Creates a tiled ground geometry
  41300. * @param id defines the unique ID of the geometry
  41301. * @param scene defines the hosting scene
  41302. * @param xmin defines the minimum value on X axis
  41303. * @param zmin defines the minimum value on Z axis
  41304. * @param xmax defines the maximum value on X axis
  41305. * @param zmax defines the maximum value on Z axis
  41306. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41307. * @param precision defines the precision to use when computing the tiles
  41308. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41309. * @param mesh defines the hosting mesh (can be null)
  41310. */
  41311. function TiledGroundGeometry(id, scene,
  41312. /**
  41313. * Defines the minimum value on X axis
  41314. */
  41315. xmin,
  41316. /**
  41317. * Defines the minimum value on Z axis
  41318. */
  41319. zmin,
  41320. /**
  41321. * Defines the maximum value on X axis
  41322. */
  41323. xmax,
  41324. /**
  41325. * Defines the maximum value on Z axis
  41326. */
  41327. zmax,
  41328. /**
  41329. * Defines the subdivisions to apply to the ground
  41330. */
  41331. subdivisions,
  41332. /**
  41333. * Defines the precision to use when computing the tiles
  41334. */
  41335. precision, canBeRegenerated, mesh) {
  41336. if (mesh === void 0) { mesh = null; }
  41337. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41338. _this.xmin = xmin;
  41339. _this.zmin = zmin;
  41340. _this.xmax = xmax;
  41341. _this.zmax = zmax;
  41342. _this.subdivisions = subdivisions;
  41343. _this.precision = precision;
  41344. return _this;
  41345. }
  41346. /** @hidden */
  41347. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41348. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41349. };
  41350. TiledGroundGeometry.prototype.copy = function (id) {
  41351. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41352. };
  41353. return TiledGroundGeometry;
  41354. }(_PrimitiveGeometry));
  41355. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41356. /**
  41357. * Creates a plane geometry
  41358. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41359. */
  41360. var PlaneGeometry = /** @class */ (function (_super) {
  41361. __extends(PlaneGeometry, _super);
  41362. /**
  41363. * Creates a plane geometry
  41364. * @param id defines the unique ID of the geometry
  41365. * @param scene defines the hosting scene
  41366. * @param size defines the size of the plane (width === height)
  41367. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41368. * @param mesh defines the hosting mesh (can be null)
  41369. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41370. */
  41371. function PlaneGeometry(id, scene,
  41372. /**
  41373. * Defines the size of the plane (width === height)
  41374. */
  41375. size, canBeRegenerated, mesh,
  41376. /**
  41377. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41378. */
  41379. side) {
  41380. if (mesh === void 0) { mesh = null; }
  41381. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41382. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41383. _this.size = size;
  41384. _this.side = side;
  41385. return _this;
  41386. }
  41387. /** @hidden */
  41388. PlaneGeometry.prototype._regenerateVertexData = function () {
  41389. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41390. };
  41391. PlaneGeometry.prototype.copy = function (id) {
  41392. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41393. };
  41394. PlaneGeometry.prototype.serialize = function () {
  41395. var serializationObject = _super.prototype.serialize.call(this);
  41396. serializationObject.size = this.size;
  41397. return serializationObject;
  41398. };
  41399. PlaneGeometry.Parse = function (parsedPlane, scene) {
  41400. if (scene.getGeometryByID(parsedPlane.id)) {
  41401. return null; // null since geometry could be something else than a ground...
  41402. }
  41403. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41404. if (BABYLON.Tags) {
  41405. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41406. }
  41407. scene.pushGeometry(plane, true);
  41408. return plane;
  41409. };
  41410. return PlaneGeometry;
  41411. }(_PrimitiveGeometry));
  41412. BABYLON.PlaneGeometry = PlaneGeometry;
  41413. /**
  41414. * Creates a torus knot geometry
  41415. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  41416. */
  41417. var TorusKnotGeometry = /** @class */ (function (_super) {
  41418. __extends(TorusKnotGeometry, _super);
  41419. /**
  41420. * Creates a torus knot geometry
  41421. * @param id defines the unique ID of the geometry
  41422. * @param scene defines the hosting scene
  41423. * @param radius defines the radius of the torus knot
  41424. * @param tube defines the thickness of the torus knot tube
  41425. * @param radialSegments defines the number of radial segments
  41426. * @param tubularSegments defines the number of tubular segments
  41427. * @param p defines the first number of windings
  41428. * @param q defines the second number of windings
  41429. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41430. * @param mesh defines the hosting mesh (can be null)
  41431. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41432. */
  41433. function TorusKnotGeometry(id, scene,
  41434. /**
  41435. * Defines the radius of the torus knot
  41436. */
  41437. radius,
  41438. /**
  41439. * Defines the thickness of the torus knot tube
  41440. */
  41441. tube,
  41442. /**
  41443. * Defines the number of radial segments
  41444. */
  41445. radialSegments,
  41446. /**
  41447. * Defines the number of tubular segments
  41448. */
  41449. tubularSegments,
  41450. /**
  41451. * Defines the first number of windings
  41452. */
  41453. p,
  41454. /**
  41455. * Defines the second number of windings
  41456. */
  41457. q, canBeRegenerated, mesh,
  41458. /**
  41459. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41460. */
  41461. side) {
  41462. if (mesh === void 0) { mesh = null; }
  41463. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41464. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41465. _this.radius = radius;
  41466. _this.tube = tube;
  41467. _this.radialSegments = radialSegments;
  41468. _this.tubularSegments = tubularSegments;
  41469. _this.p = p;
  41470. _this.q = q;
  41471. _this.side = side;
  41472. return _this;
  41473. }
  41474. /** @hidden */
  41475. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41476. 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 });
  41477. };
  41478. TorusKnotGeometry.prototype.copy = function (id) {
  41479. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41480. };
  41481. TorusKnotGeometry.prototype.serialize = function () {
  41482. var serializationObject = _super.prototype.serialize.call(this);
  41483. serializationObject.radius = this.radius;
  41484. serializationObject.tube = this.tube;
  41485. serializationObject.radialSegments = this.radialSegments;
  41486. serializationObject.tubularSegments = this.tubularSegments;
  41487. serializationObject.p = this.p;
  41488. serializationObject.q = this.q;
  41489. return serializationObject;
  41490. };
  41491. ;
  41492. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41493. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41494. return null; // null since geometry could be something else than a ground...
  41495. }
  41496. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41497. if (BABYLON.Tags) {
  41498. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41499. }
  41500. scene.pushGeometry(torusKnot, true);
  41501. return torusKnot;
  41502. };
  41503. return TorusKnotGeometry;
  41504. }(_PrimitiveGeometry));
  41505. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41506. //}
  41507. })(BABYLON || (BABYLON = {}));
  41508. //# sourceMappingURL=babylon.geometry.js.map
  41509. var BABYLON;
  41510. (function (BABYLON) {
  41511. /**
  41512. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41513. */
  41514. var PerformanceMonitor = /** @class */ (function () {
  41515. /**
  41516. * constructor
  41517. * @param frameSampleSize The number of samples required to saturate the sliding window
  41518. */
  41519. function PerformanceMonitor(frameSampleSize) {
  41520. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41521. this._enabled = true;
  41522. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41523. }
  41524. /**
  41525. * Samples current frame
  41526. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41527. */
  41528. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41529. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41530. if (!this._enabled)
  41531. return;
  41532. if (this._lastFrameTimeMs != null) {
  41533. var dt = timeMs - this._lastFrameTimeMs;
  41534. this._rollingFrameTime.add(dt);
  41535. }
  41536. this._lastFrameTimeMs = timeMs;
  41537. };
  41538. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41539. /**
  41540. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41541. */
  41542. get: function () {
  41543. return this._rollingFrameTime.average;
  41544. },
  41545. enumerable: true,
  41546. configurable: true
  41547. });
  41548. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41549. /**
  41550. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41551. */
  41552. get: function () {
  41553. return this._rollingFrameTime.variance;
  41554. },
  41555. enumerable: true,
  41556. configurable: true
  41557. });
  41558. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41559. /**
  41560. * Returns the frame time of the most recent frame
  41561. */
  41562. get: function () {
  41563. return this._rollingFrameTime.history(0);
  41564. },
  41565. enumerable: true,
  41566. configurable: true
  41567. });
  41568. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41569. /**
  41570. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41571. */
  41572. get: function () {
  41573. return 1000.0 / this._rollingFrameTime.average;
  41574. },
  41575. enumerable: true,
  41576. configurable: true
  41577. });
  41578. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41579. /**
  41580. * Returns the average framerate in frames per second using the most recent frame time
  41581. */
  41582. get: function () {
  41583. var history = this._rollingFrameTime.history(0);
  41584. if (history === 0) {
  41585. return 0;
  41586. }
  41587. return 1000.0 / history;
  41588. },
  41589. enumerable: true,
  41590. configurable: true
  41591. });
  41592. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41593. /**
  41594. * Returns true if enough samples have been taken to completely fill the sliding window
  41595. */
  41596. get: function () {
  41597. return this._rollingFrameTime.isSaturated();
  41598. },
  41599. enumerable: true,
  41600. configurable: true
  41601. });
  41602. /**
  41603. * Enables contributions to the sliding window sample set
  41604. */
  41605. PerformanceMonitor.prototype.enable = function () {
  41606. this._enabled = true;
  41607. };
  41608. /**
  41609. * Disables contributions to the sliding window sample set
  41610. * Samples will not be interpolated over the disabled period
  41611. */
  41612. PerformanceMonitor.prototype.disable = function () {
  41613. this._enabled = false;
  41614. //clear last sample to avoid interpolating over the disabled period when next enabled
  41615. this._lastFrameTimeMs = null;
  41616. };
  41617. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41618. /**
  41619. * Returns true if sampling is enabled
  41620. */
  41621. get: function () {
  41622. return this._enabled;
  41623. },
  41624. enumerable: true,
  41625. configurable: true
  41626. });
  41627. /**
  41628. * Resets performance monitor
  41629. */
  41630. PerformanceMonitor.prototype.reset = function () {
  41631. //clear last sample to avoid interpolating over the disabled period when next enabled
  41632. this._lastFrameTimeMs = null;
  41633. //wipe record
  41634. this._rollingFrameTime.reset();
  41635. };
  41636. return PerformanceMonitor;
  41637. }());
  41638. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41639. /**
  41640. * RollingAverage
  41641. *
  41642. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41643. */
  41644. var RollingAverage = /** @class */ (function () {
  41645. /**
  41646. * constructor
  41647. * @param length The number of samples required to saturate the sliding window
  41648. */
  41649. function RollingAverage(length) {
  41650. this._samples = new Array(length);
  41651. this.reset();
  41652. }
  41653. /**
  41654. * Adds a sample to the sample set
  41655. * @param v The sample value
  41656. */
  41657. RollingAverage.prototype.add = function (v) {
  41658. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41659. var delta;
  41660. //we need to check if we've already wrapped round
  41661. if (this.isSaturated()) {
  41662. //remove bottom of stack from mean
  41663. var bottomValue = this._samples[this._pos];
  41664. delta = bottomValue - this.average;
  41665. this.average -= delta / (this._sampleCount - 1);
  41666. this._m2 -= delta * (bottomValue - this.average);
  41667. }
  41668. else {
  41669. this._sampleCount++;
  41670. }
  41671. //add new value to mean
  41672. delta = v - this.average;
  41673. this.average += delta / (this._sampleCount);
  41674. this._m2 += delta * (v - this.average);
  41675. //set the new variance
  41676. this.variance = this._m2 / (this._sampleCount - 1);
  41677. this._samples[this._pos] = v;
  41678. this._pos++;
  41679. this._pos %= this._samples.length; //positive wrap around
  41680. };
  41681. /**
  41682. * Returns previously added values or null if outside of history or outside the sliding window domain
  41683. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41684. * @return Value previously recorded with add() or null if outside of range
  41685. */
  41686. RollingAverage.prototype.history = function (i) {
  41687. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41688. return 0;
  41689. }
  41690. var i0 = this._wrapPosition(this._pos - 1.0);
  41691. return this._samples[this._wrapPosition(i0 - i)];
  41692. };
  41693. /**
  41694. * Returns true if enough samples have been taken to completely fill the sliding window
  41695. * @return true if sample-set saturated
  41696. */
  41697. RollingAverage.prototype.isSaturated = function () {
  41698. return this._sampleCount >= this._samples.length;
  41699. };
  41700. /**
  41701. * Resets the rolling average (equivalent to 0 samples taken so far)
  41702. */
  41703. RollingAverage.prototype.reset = function () {
  41704. this.average = 0;
  41705. this.variance = 0;
  41706. this._sampleCount = 0;
  41707. this._pos = 0;
  41708. this._m2 = 0;
  41709. };
  41710. /**
  41711. * Wraps a value around the sample range boundaries
  41712. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41713. * @return Wrapped position in sample range
  41714. */
  41715. RollingAverage.prototype._wrapPosition = function (i) {
  41716. var max = this._samples.length;
  41717. return ((i % max) + max) % max;
  41718. };
  41719. return RollingAverage;
  41720. }());
  41721. BABYLON.RollingAverage = RollingAverage;
  41722. })(BABYLON || (BABYLON = {}));
  41723. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41724. var BABYLON;
  41725. (function (BABYLON) {
  41726. /**
  41727. * "Static Class" containing the most commonly used helper while dealing with material for
  41728. * rendering purpose.
  41729. *
  41730. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41731. *
  41732. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41733. */
  41734. var MaterialHelper = /** @class */ (function () {
  41735. function MaterialHelper() {
  41736. }
  41737. /**
  41738. * Bind the current view position to an effect.
  41739. * @param effect The effect to be bound
  41740. * @param scene The scene the eyes position is used from
  41741. */
  41742. MaterialHelper.BindEyePosition = function (effect, scene) {
  41743. if (scene._forcedViewPosition) {
  41744. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41745. return;
  41746. }
  41747. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41748. };
  41749. /**
  41750. * Helps preparing the defines values about the UVs in used in the effect.
  41751. * UVs are shared as much as we can accross channels in the shaders.
  41752. * @param texture The texture we are preparing the UVs for
  41753. * @param defines The defines to update
  41754. * @param key The channel key "diffuse", "specular"... used in the shader
  41755. */
  41756. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41757. defines._needUVs = true;
  41758. defines[key] = true;
  41759. if (texture.getTextureMatrix().isIdentity(true)) {
  41760. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41761. if (texture.coordinatesIndex === 0) {
  41762. defines["MAINUV1"] = true;
  41763. }
  41764. else {
  41765. defines["MAINUV2"] = true;
  41766. }
  41767. }
  41768. else {
  41769. defines[key + "DIRECTUV"] = 0;
  41770. }
  41771. };
  41772. /**
  41773. * Binds a texture matrix value to its corrsponding uniform
  41774. * @param texture The texture to bind the matrix for
  41775. * @param uniformBuffer The uniform buffer receivin the data
  41776. * @param key The channel key "diffuse", "specular"... used in the shader
  41777. */
  41778. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41779. var matrix = texture.getTextureMatrix();
  41780. if (!matrix.isIdentity(true)) {
  41781. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41782. }
  41783. };
  41784. /**
  41785. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41786. * @param mesh defines the current mesh
  41787. * @param scene defines the current scene
  41788. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41789. * @param pointsCloud defines if point cloud rendering has to be turned on
  41790. * @param fogEnabled defines if fog has to be turned on
  41791. * @param alphaTest defines if alpha testing has to be turned on
  41792. * @param defines defines the current list of defines
  41793. */
  41794. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41795. if (defines._areMiscDirty) {
  41796. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41797. defines["POINTSIZE"] = pointsCloud;
  41798. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41799. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41800. defines["ALPHATEST"] = alphaTest;
  41801. }
  41802. };
  41803. /**
  41804. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41805. * @param scene defines the current scene
  41806. * @param engine defines the current engine
  41807. * @param defines specifies the list of active defines
  41808. * @param useInstances defines if instances have to be turned on
  41809. * @param useClipPlane defines if clip plane have to be turned on
  41810. */
  41811. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41812. if (useClipPlane === void 0) { useClipPlane = null; }
  41813. var changed = false;
  41814. var useClipPlane1 = false;
  41815. var useClipPlane2 = false;
  41816. var useClipPlane3 = false;
  41817. var useClipPlane4 = false;
  41818. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41819. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41820. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41821. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41822. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41823. defines["CLIPPLANE"] = useClipPlane1;
  41824. changed = true;
  41825. }
  41826. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41827. defines["CLIPPLANE2"] = useClipPlane2;
  41828. changed = true;
  41829. }
  41830. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41831. defines["CLIPPLANE3"] = useClipPlane3;
  41832. changed = true;
  41833. }
  41834. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41835. defines["CLIPPLANE4"] = useClipPlane4;
  41836. changed = true;
  41837. }
  41838. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41839. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41840. changed = true;
  41841. }
  41842. if (defines["INSTANCES"] !== useInstances) {
  41843. defines["INSTANCES"] = useInstances;
  41844. changed = true;
  41845. }
  41846. if (changed) {
  41847. defines.markAsUnprocessed();
  41848. }
  41849. };
  41850. /**
  41851. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41852. * @param mesh The mesh containing the geometry data we will draw
  41853. * @param defines The defines to update
  41854. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41855. * @param useBones Precise whether bones should be used or not (override mesh info)
  41856. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41857. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41858. * @returns false if defines are considered not dirty and have not been checked
  41859. */
  41860. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41861. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41862. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41863. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41864. return false;
  41865. }
  41866. defines._normals = defines._needNormals;
  41867. defines._uvs = defines._needUVs;
  41868. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41869. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41870. defines["TANGENT"] = true;
  41871. }
  41872. if (defines._needUVs) {
  41873. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41874. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41875. }
  41876. else {
  41877. defines["UV1"] = false;
  41878. defines["UV2"] = false;
  41879. }
  41880. if (useVertexColor) {
  41881. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41882. defines["VERTEXCOLOR"] = hasVertexColors;
  41883. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41884. }
  41885. if (useBones) {
  41886. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41887. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41888. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41889. }
  41890. else {
  41891. defines["NUM_BONE_INFLUENCERS"] = 0;
  41892. defines["BonesPerMesh"] = 0;
  41893. }
  41894. }
  41895. if (useMorphTargets) {
  41896. var manager = mesh.morphTargetManager;
  41897. if (manager) {
  41898. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41899. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41900. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41901. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41902. }
  41903. else {
  41904. defines["MORPHTARGETS_TANGENT"] = false;
  41905. defines["MORPHTARGETS_NORMAL"] = false;
  41906. defines["MORPHTARGETS"] = false;
  41907. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41908. }
  41909. }
  41910. return true;
  41911. };
  41912. /**
  41913. * Prepares the defines related to the light information passed in parameter
  41914. * @param scene The scene we are intending to draw
  41915. * @param mesh The mesh the effect is compiling for
  41916. * @param defines The defines to update
  41917. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41918. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41919. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41920. * @returns true if normals will be required for the rest of the effect
  41921. */
  41922. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41923. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41924. if (disableLighting === void 0) { disableLighting = false; }
  41925. if (!defines._areLightsDirty) {
  41926. return defines._needNormals;
  41927. }
  41928. var lightIndex = 0;
  41929. var needNormals = false;
  41930. var needRebuild = false;
  41931. var lightmapMode = false;
  41932. var shadowEnabled = false;
  41933. var specularEnabled = false;
  41934. if (scene.lightsEnabled && !disableLighting) {
  41935. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41936. var light = _a[_i];
  41937. needNormals = true;
  41938. if (defines["LIGHT" + lightIndex] === undefined) {
  41939. needRebuild = true;
  41940. }
  41941. defines["LIGHT" + lightIndex] = true;
  41942. defines["SPOTLIGHT" + lightIndex] = false;
  41943. defines["HEMILIGHT" + lightIndex] = false;
  41944. defines["POINTLIGHT" + lightIndex] = false;
  41945. defines["DIRLIGHT" + lightIndex] = false;
  41946. light.prepareLightSpecificDefines(defines, lightIndex);
  41947. // FallOff.
  41948. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41949. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41950. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41951. switch (light.falloffType) {
  41952. case BABYLON.Light.FALLOFF_GLTF:
  41953. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41954. break;
  41955. case BABYLON.Light.FALLOFF_PHYSICAL:
  41956. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41957. break;
  41958. case BABYLON.Light.FALLOFF_STANDARD:
  41959. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41960. break;
  41961. }
  41962. // Specular
  41963. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41964. specularEnabled = true;
  41965. }
  41966. // Shadows
  41967. defines["SHADOW" + lightIndex] = false;
  41968. defines["SHADOWPCF" + lightIndex] = false;
  41969. defines["SHADOWPCSS" + lightIndex] = false;
  41970. defines["SHADOWPOISSON" + lightIndex] = false;
  41971. defines["SHADOWESM" + lightIndex] = false;
  41972. defines["SHADOWCUBE" + lightIndex] = false;
  41973. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41974. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41975. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41976. var shadowGenerator = light.getShadowGenerator();
  41977. if (shadowGenerator) {
  41978. var shadowMap = shadowGenerator.getShadowMap();
  41979. if (shadowMap) {
  41980. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41981. shadowEnabled = true;
  41982. shadowGenerator.prepareDefines(defines, lightIndex);
  41983. }
  41984. }
  41985. }
  41986. }
  41987. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41988. lightmapMode = true;
  41989. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41990. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41991. }
  41992. else {
  41993. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41994. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41995. }
  41996. lightIndex++;
  41997. if (lightIndex === maxSimultaneousLights)
  41998. break;
  41999. }
  42000. }
  42001. defines["SPECULARTERM"] = specularEnabled;
  42002. defines["SHADOWS"] = shadowEnabled;
  42003. // Resetting all other lights if any
  42004. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42005. if (defines["LIGHT" + index] !== undefined) {
  42006. defines["LIGHT" + index] = false;
  42007. defines["HEMILIGHT" + lightIndex] = false;
  42008. defines["POINTLIGHT" + lightIndex] = false;
  42009. defines["DIRLIGHT" + lightIndex] = false;
  42010. defines["SPOTLIGHT" + lightIndex] = false;
  42011. defines["SHADOW" + lightIndex] = false;
  42012. }
  42013. }
  42014. var caps = scene.getEngine().getCaps();
  42015. if (defines["SHADOWFLOAT"] === undefined) {
  42016. needRebuild = true;
  42017. }
  42018. defines["SHADOWFLOAT"] = shadowEnabled &&
  42019. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42020. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42021. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42022. if (needRebuild) {
  42023. defines.rebuild();
  42024. }
  42025. return needNormals;
  42026. };
  42027. /**
  42028. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42029. * that won t be acctive due to defines being turned off.
  42030. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42031. * @param samplersList The samplers list
  42032. * @param defines The defines helping in the list generation
  42033. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42034. */
  42035. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42036. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42037. var uniformsList;
  42038. var uniformBuffersList = null;
  42039. if (uniformsListOrOptions.uniformsNames) {
  42040. var options = uniformsListOrOptions;
  42041. uniformsList = options.uniformsNames;
  42042. uniformBuffersList = options.uniformBuffersNames;
  42043. samplersList = options.samplers;
  42044. defines = options.defines;
  42045. maxSimultaneousLights = options.maxSimultaneousLights;
  42046. }
  42047. else {
  42048. uniformsList = uniformsListOrOptions;
  42049. if (!samplersList) {
  42050. samplersList = [];
  42051. }
  42052. }
  42053. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42054. if (!defines["LIGHT" + lightIndex]) {
  42055. break;
  42056. }
  42057. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42058. if (uniformBuffersList) {
  42059. uniformBuffersList.push("Light" + lightIndex);
  42060. }
  42061. samplersList.push("shadowSampler" + lightIndex);
  42062. samplersList.push("depthSampler" + lightIndex);
  42063. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42064. samplersList.push("projectionLightSampler" + lightIndex);
  42065. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42066. }
  42067. }
  42068. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42069. uniformsList.push("morphTargetInfluences");
  42070. }
  42071. };
  42072. /**
  42073. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42074. * @param defines The defines to update while falling back
  42075. * @param fallbacks The authorized effect fallbacks
  42076. * @param maxSimultaneousLights The maximum number of lights allowed
  42077. * @param rank the current rank of the Effect
  42078. * @returns The newly affected rank
  42079. */
  42080. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42081. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42082. if (rank === void 0) { rank = 0; }
  42083. var lightFallbackRank = 0;
  42084. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42085. if (!defines["LIGHT" + lightIndex]) {
  42086. break;
  42087. }
  42088. if (lightIndex > 0) {
  42089. lightFallbackRank = rank + lightIndex;
  42090. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42091. }
  42092. if (!defines["SHADOWS"]) {
  42093. if (defines["SHADOW" + lightIndex]) {
  42094. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42095. }
  42096. if (defines["SHADOWPCF" + lightIndex]) {
  42097. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42098. }
  42099. if (defines["SHADOWPCSS" + lightIndex]) {
  42100. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42101. }
  42102. if (defines["SHADOWPOISSON" + lightIndex]) {
  42103. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42104. }
  42105. if (defines["SHADOWESM" + lightIndex]) {
  42106. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42107. }
  42108. }
  42109. }
  42110. return lightFallbackRank++;
  42111. };
  42112. /**
  42113. * Prepares the list of attributes required for morph targets according to the effect defines.
  42114. * @param attribs The current list of supported attribs
  42115. * @param mesh The mesh to prepare the morph targets attributes for
  42116. * @param defines The current Defines of the effect
  42117. */
  42118. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42119. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42120. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42121. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42122. var manager = mesh.morphTargetManager;
  42123. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42124. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42125. for (var index = 0; index < influencers; index++) {
  42126. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42127. if (normal) {
  42128. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42129. }
  42130. if (tangent) {
  42131. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42132. }
  42133. if (attribs.length > maxAttributesCount) {
  42134. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42135. }
  42136. }
  42137. }
  42138. };
  42139. /**
  42140. * Prepares the list of attributes required for bones according to the effect defines.
  42141. * @param attribs The current list of supported attribs
  42142. * @param mesh The mesh to prepare the bones attributes for
  42143. * @param defines The current Defines of the effect
  42144. * @param fallbacks The current efffect fallback strategy
  42145. */
  42146. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42147. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42148. fallbacks.addCPUSkinningFallback(0, mesh);
  42149. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42150. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42151. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42152. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42153. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42154. }
  42155. }
  42156. };
  42157. /**
  42158. * Prepares the list of attributes required for instances according to the effect defines.
  42159. * @param attribs The current list of supported attribs
  42160. * @param defines The current Defines of the effect
  42161. */
  42162. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42163. if (defines["INSTANCES"]) {
  42164. attribs.push("world0");
  42165. attribs.push("world1");
  42166. attribs.push("world2");
  42167. attribs.push("world3");
  42168. }
  42169. };
  42170. /**
  42171. * Binds the light shadow information to the effect for the given mesh.
  42172. * @param light The light containing the generator
  42173. * @param scene The scene the lights belongs to
  42174. * @param mesh The mesh we are binding the information to render
  42175. * @param lightIndex The light index in the effect used to render the mesh
  42176. * @param effect The effect we are binding the data to
  42177. */
  42178. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42179. if (light.shadowEnabled && mesh.receiveShadows) {
  42180. var shadowGenerator = light.getShadowGenerator();
  42181. if (shadowGenerator) {
  42182. shadowGenerator.bindShadowLight(lightIndex, effect);
  42183. }
  42184. }
  42185. };
  42186. /**
  42187. * Binds the light information to the effect.
  42188. * @param light The light containing the generator
  42189. * @param effect The effect we are binding the data to
  42190. * @param lightIndex The light index in the effect used to render
  42191. */
  42192. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42193. light.transferToEffect(effect, lightIndex + "");
  42194. };
  42195. /**
  42196. * Binds the lights information from the scene to the effect for the given mesh.
  42197. * @param scene The scene the lights belongs to
  42198. * @param mesh The mesh we are binding the information to render
  42199. * @param effect The effect we are binding the data to
  42200. * @param defines The generated defines for the effect
  42201. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42202. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42203. */
  42204. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42205. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42206. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42207. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42208. for (var i = 0; i < len; i++) {
  42209. var light = mesh._lightSources[i];
  42210. var iAsString = i.toString();
  42211. var scaledIntensity = light.getScaledIntensity();
  42212. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42213. MaterialHelper.BindLightProperties(light, effect, i);
  42214. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42215. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42216. if (defines["SPECULARTERM"]) {
  42217. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42218. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42219. }
  42220. // Shadows
  42221. if (scene.shadowsEnabled) {
  42222. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42223. }
  42224. light._uniformBuffer.update();
  42225. }
  42226. };
  42227. /**
  42228. * Binds the fog information from the scene to the effect for the given mesh.
  42229. * @param scene The scene the lights belongs to
  42230. * @param mesh The mesh we are binding the information to render
  42231. * @param effect The effect we are binding the data to
  42232. * @param linearSpace Defines if the fog effect is applied in linear space
  42233. */
  42234. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42235. if (linearSpace === void 0) { linearSpace = false; }
  42236. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42237. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42238. // Convert fog color to linear space if used in a linear space computed shader.
  42239. if (linearSpace) {
  42240. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42241. effect.setColor3("vFogColor", this._tempFogColor);
  42242. }
  42243. else {
  42244. effect.setColor3("vFogColor", scene.fogColor);
  42245. }
  42246. }
  42247. };
  42248. /**
  42249. * Binds the bones information from the mesh to the effect.
  42250. * @param mesh The mesh we are binding the information to render
  42251. * @param effect The effect we are binding the data to
  42252. */
  42253. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42254. if (!effect || !mesh) {
  42255. return;
  42256. }
  42257. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42258. mesh.computeBonesUsingShaders = false;
  42259. }
  42260. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42261. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42262. if (matrices) {
  42263. effect.setMatrices("mBones", matrices);
  42264. }
  42265. }
  42266. };
  42267. /**
  42268. * Binds the morph targets information from the mesh to the effect.
  42269. * @param abstractMesh The mesh we are binding the information to render
  42270. * @param effect The effect we are binding the data to
  42271. */
  42272. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42273. var manager = abstractMesh.morphTargetManager;
  42274. if (!abstractMesh || !manager) {
  42275. return;
  42276. }
  42277. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42278. };
  42279. /**
  42280. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42281. * @param defines The generated defines used in the effect
  42282. * @param effect The effect we are binding the data to
  42283. * @param scene The scene we are willing to render with logarithmic scale for
  42284. */
  42285. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42286. if (defines["LOGARITHMICDEPTH"]) {
  42287. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42288. }
  42289. };
  42290. /**
  42291. * Binds the clip plane information from the scene to the effect.
  42292. * @param scene The scene the clip plane information are extracted from
  42293. * @param effect The effect we are binding the data to
  42294. */
  42295. MaterialHelper.BindClipPlane = function (effect, scene) {
  42296. if (scene.clipPlane) {
  42297. var clipPlane = scene.clipPlane;
  42298. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42299. }
  42300. if (scene.clipPlane2) {
  42301. var clipPlane = scene.clipPlane2;
  42302. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42303. }
  42304. if (scene.clipPlane3) {
  42305. var clipPlane = scene.clipPlane3;
  42306. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42307. }
  42308. if (scene.clipPlane4) {
  42309. var clipPlane = scene.clipPlane4;
  42310. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42311. }
  42312. };
  42313. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42314. return MaterialHelper;
  42315. }());
  42316. BABYLON.MaterialHelper = MaterialHelper;
  42317. })(BABYLON || (BABYLON = {}));
  42318. //# sourceMappingURL=babylon.materialHelper.js.map
  42319. var BABYLON;
  42320. (function (BABYLON) {
  42321. /**
  42322. * Base class of materials working in push mode in babylon JS
  42323. * @hidden
  42324. */
  42325. var PushMaterial = /** @class */ (function (_super) {
  42326. __extends(PushMaterial, _super);
  42327. function PushMaterial(name, scene) {
  42328. var _this = _super.call(this, name, scene) || this;
  42329. _this._normalMatrix = new BABYLON.Matrix();
  42330. _this.storeEffectOnSubMeshes = true;
  42331. return _this;
  42332. }
  42333. PushMaterial.prototype.getEffect = function () {
  42334. return this._activeEffect;
  42335. };
  42336. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42337. if (!mesh) {
  42338. return false;
  42339. }
  42340. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42341. return true;
  42342. }
  42343. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42344. };
  42345. /**
  42346. * Binds the given world matrix to the active effect
  42347. *
  42348. * @param world the matrix to bind
  42349. */
  42350. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42351. this._activeEffect.setMatrix("world", world);
  42352. };
  42353. /**
  42354. * Binds the given normal matrix to the active effect
  42355. *
  42356. * @param normalMatrix the matrix to bind
  42357. */
  42358. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42359. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42360. };
  42361. PushMaterial.prototype.bind = function (world, mesh) {
  42362. if (!mesh) {
  42363. return;
  42364. }
  42365. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42366. };
  42367. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42368. if (effect === void 0) { effect = null; }
  42369. _super.prototype._afterBind.call(this, mesh);
  42370. this.getScene()._cachedEffect = effect;
  42371. };
  42372. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42373. if (visibility === void 0) { visibility = 1; }
  42374. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42375. };
  42376. return PushMaterial;
  42377. }(BABYLON.Material));
  42378. BABYLON.PushMaterial = PushMaterial;
  42379. })(BABYLON || (BABYLON = {}));
  42380. //# sourceMappingURL=babylon.pushMaterial.js.map
  42381. var BABYLON;
  42382. (function (BABYLON) {
  42383. /** @hidden */
  42384. var StandardMaterialDefines = /** @class */ (function (_super) {
  42385. __extends(StandardMaterialDefines, _super);
  42386. function StandardMaterialDefines() {
  42387. var _this = _super.call(this) || this;
  42388. _this.MAINUV1 = false;
  42389. _this.MAINUV2 = false;
  42390. _this.DIFFUSE = false;
  42391. _this.DIFFUSEDIRECTUV = 0;
  42392. _this.AMBIENT = false;
  42393. _this.AMBIENTDIRECTUV = 0;
  42394. _this.OPACITY = false;
  42395. _this.OPACITYDIRECTUV = 0;
  42396. _this.OPACITYRGB = false;
  42397. _this.REFLECTION = false;
  42398. _this.EMISSIVE = false;
  42399. _this.EMISSIVEDIRECTUV = 0;
  42400. _this.SPECULAR = false;
  42401. _this.SPECULARDIRECTUV = 0;
  42402. _this.BUMP = false;
  42403. _this.BUMPDIRECTUV = 0;
  42404. _this.PARALLAX = false;
  42405. _this.PARALLAXOCCLUSION = false;
  42406. _this.SPECULAROVERALPHA = false;
  42407. _this.CLIPPLANE = false;
  42408. _this.CLIPPLANE2 = false;
  42409. _this.CLIPPLANE3 = false;
  42410. _this.CLIPPLANE4 = false;
  42411. _this.ALPHATEST = false;
  42412. _this.DEPTHPREPASS = false;
  42413. _this.ALPHAFROMDIFFUSE = false;
  42414. _this.POINTSIZE = false;
  42415. _this.FOG = false;
  42416. _this.SPECULARTERM = false;
  42417. _this.DIFFUSEFRESNEL = false;
  42418. _this.OPACITYFRESNEL = false;
  42419. _this.REFLECTIONFRESNEL = false;
  42420. _this.REFRACTIONFRESNEL = false;
  42421. _this.EMISSIVEFRESNEL = false;
  42422. _this.FRESNEL = false;
  42423. _this.NORMAL = false;
  42424. _this.UV1 = false;
  42425. _this.UV2 = false;
  42426. _this.VERTEXCOLOR = false;
  42427. _this.VERTEXALPHA = false;
  42428. _this.NUM_BONE_INFLUENCERS = 0;
  42429. _this.BonesPerMesh = 0;
  42430. _this.INSTANCES = false;
  42431. _this.GLOSSINESS = false;
  42432. _this.ROUGHNESS = false;
  42433. _this.EMISSIVEASILLUMINATION = false;
  42434. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42435. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42436. _this.LIGHTMAP = false;
  42437. _this.LIGHTMAPDIRECTUV = 0;
  42438. _this.OBJECTSPACE_NORMALMAP = false;
  42439. _this.USELIGHTMAPASSHADOWMAP = false;
  42440. _this.REFLECTIONMAP_3D = false;
  42441. _this.REFLECTIONMAP_SPHERICAL = false;
  42442. _this.REFLECTIONMAP_PLANAR = false;
  42443. _this.REFLECTIONMAP_CUBIC = false;
  42444. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42445. _this.REFLECTIONMAP_PROJECTION = false;
  42446. _this.REFLECTIONMAP_SKYBOX = false;
  42447. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  42448. _this.REFLECTIONMAP_EXPLICIT = false;
  42449. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42450. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42451. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42452. _this.INVERTCUBICMAP = false;
  42453. _this.LOGARITHMICDEPTH = false;
  42454. _this.REFRACTION = false;
  42455. _this.REFRACTIONMAP_3D = false;
  42456. _this.REFLECTIONOVERALPHA = false;
  42457. _this.TWOSIDEDLIGHTING = false;
  42458. _this.SHADOWFLOAT = false;
  42459. _this.MORPHTARGETS = false;
  42460. _this.MORPHTARGETS_NORMAL = false;
  42461. _this.MORPHTARGETS_TANGENT = false;
  42462. _this.NUM_MORPH_INFLUENCERS = 0;
  42463. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42464. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42465. _this.IMAGEPROCESSING = false;
  42466. _this.VIGNETTE = false;
  42467. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42468. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42469. _this.TONEMAPPING = false;
  42470. _this.TONEMAPPING_ACES = false;
  42471. _this.CONTRAST = false;
  42472. _this.COLORCURVES = false;
  42473. _this.COLORGRADING = false;
  42474. _this.COLORGRADING3D = false;
  42475. _this.SAMPLER3DGREENDEPTH = false;
  42476. _this.SAMPLER3DBGRMAP = false;
  42477. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42478. /**
  42479. * If the reflection texture on this material is in linear color space
  42480. * @hidden
  42481. */
  42482. _this.IS_REFLECTION_LINEAR = false;
  42483. /**
  42484. * If the refraction texture on this material is in linear color space
  42485. * @hidden
  42486. */
  42487. _this.IS_REFRACTION_LINEAR = false;
  42488. _this.EXPOSURE = false;
  42489. _this.rebuild();
  42490. return _this;
  42491. }
  42492. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42493. var modes = [
  42494. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42495. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42496. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42497. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42498. ];
  42499. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42500. var mode = modes_1[_i];
  42501. this[mode] = (mode === modeToEnable);
  42502. }
  42503. };
  42504. return StandardMaterialDefines;
  42505. }(BABYLON.MaterialDefines));
  42506. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42507. /**
  42508. * This is the default material used in Babylon. It is the best trade off between quality
  42509. * and performances.
  42510. * @see http://doc.babylonjs.com/babylon101/materials
  42511. */
  42512. var StandardMaterial = /** @class */ (function (_super) {
  42513. __extends(StandardMaterial, _super);
  42514. /**
  42515. * Instantiates a new standard material.
  42516. * This is the default material used in Babylon. It is the best trade off between quality
  42517. * and performances.
  42518. * @see http://doc.babylonjs.com/babylon101/materials
  42519. * @param name Define the name of the material in the scene
  42520. * @param scene Define the scene the material belong to
  42521. */
  42522. function StandardMaterial(name, scene) {
  42523. var _this = _super.call(this, name, scene) || this;
  42524. /**
  42525. * The color of the material lit by the environmental background lighting.
  42526. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  42527. */
  42528. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42529. /**
  42530. * The basic color of the material as viewed under a light.
  42531. */
  42532. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42533. /**
  42534. * Define how the color and intensity of the highlight given by the light in the material.
  42535. */
  42536. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42537. /**
  42538. * Define the color of the material as if self lit.
  42539. * This will be mixed in the final result even in the absence of light.
  42540. */
  42541. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42542. /**
  42543. * Defines how sharp are the highlights in the material.
  42544. * The bigger the value the sharper giving a more glossy feeling to the result.
  42545. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  42546. */
  42547. _this.specularPower = 64;
  42548. _this._useAlphaFromDiffuseTexture = false;
  42549. _this._useEmissiveAsIllumination = false;
  42550. _this._linkEmissiveWithDiffuse = false;
  42551. _this._useSpecularOverAlpha = false;
  42552. _this._useReflectionOverAlpha = false;
  42553. _this._disableLighting = false;
  42554. _this._useObjectSpaceNormalMap = false;
  42555. _this._useParallax = false;
  42556. _this._useParallaxOcclusion = false;
  42557. /**
  42558. * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
  42559. */
  42560. _this.parallaxScaleBias = 0.05;
  42561. _this._roughness = 0;
  42562. /**
  42563. * In case of refraction, define the value of the indice of refraction.
  42564. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  42565. */
  42566. _this.indexOfRefraction = 0.98;
  42567. /**
  42568. * Invert the refraction texture alongside the y axis.
  42569. * It can be usefull with procedural textures or probe for instance.
  42570. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  42571. */
  42572. _this.invertRefractionY = true;
  42573. /**
  42574. * Defines the alpha limits in alpha test mode.
  42575. */
  42576. _this.alphaCutOff = 0.4;
  42577. _this._useLightmapAsShadowmap = false;
  42578. _this._useReflectionFresnelFromSpecular = false;
  42579. _this._useGlossinessFromSpecularMapAlpha = false;
  42580. _this._maxSimultaneousLights = 4;
  42581. _this._invertNormalMapX = false;
  42582. _this._invertNormalMapY = false;
  42583. _this._twoSidedLighting = false;
  42584. _this._renderTargets = new BABYLON.SmartArray(16);
  42585. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42586. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42587. // Setup the default processing configuration to the scene.
  42588. _this._attachImageProcessingConfiguration(null);
  42589. _this.getRenderTargetTextures = function () {
  42590. _this._renderTargets.reset();
  42591. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42592. _this._renderTargets.push(_this._reflectionTexture);
  42593. }
  42594. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42595. _this._renderTargets.push(_this._refractionTexture);
  42596. }
  42597. return _this._renderTargets;
  42598. };
  42599. return _this;
  42600. }
  42601. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42602. /**
  42603. * Gets the image processing configuration used either in this material.
  42604. */
  42605. get: function () {
  42606. return this._imageProcessingConfiguration;
  42607. },
  42608. /**
  42609. * Sets the Default image processing configuration used either in the this material.
  42610. *
  42611. * If sets to null, the scene one is in use.
  42612. */
  42613. set: function (value) {
  42614. this._attachImageProcessingConfiguration(value);
  42615. // Ensure the effect will be rebuilt.
  42616. this._markAllSubMeshesAsTexturesDirty();
  42617. },
  42618. enumerable: true,
  42619. configurable: true
  42620. });
  42621. /**
  42622. * Attaches a new image processing configuration to the Standard Material.
  42623. * @param configuration
  42624. */
  42625. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42626. var _this = this;
  42627. if (configuration === this._imageProcessingConfiguration) {
  42628. return;
  42629. }
  42630. // Detaches observer.
  42631. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42632. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42633. }
  42634. // Pick the scene configuration if needed.
  42635. if (!configuration) {
  42636. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42637. }
  42638. else {
  42639. this._imageProcessingConfiguration = configuration;
  42640. }
  42641. // Attaches observer.
  42642. if (this._imageProcessingConfiguration) {
  42643. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42644. _this._markAllSubMeshesAsImageProcessingDirty();
  42645. });
  42646. }
  42647. };
  42648. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42649. /**
  42650. * Gets wether the color curves effect is enabled.
  42651. */
  42652. get: function () {
  42653. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42654. },
  42655. /**
  42656. * Sets wether the color curves effect is enabled.
  42657. */
  42658. set: function (value) {
  42659. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42660. },
  42661. enumerable: true,
  42662. configurable: true
  42663. });
  42664. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42665. /**
  42666. * Gets wether the color grading effect is enabled.
  42667. */
  42668. get: function () {
  42669. return this.imageProcessingConfiguration.colorGradingEnabled;
  42670. },
  42671. /**
  42672. * Gets wether the color grading effect is enabled.
  42673. */
  42674. set: function (value) {
  42675. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42676. },
  42677. enumerable: true,
  42678. configurable: true
  42679. });
  42680. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42681. /**
  42682. * Gets wether tonemapping is enabled or not.
  42683. */
  42684. get: function () {
  42685. return this._imageProcessingConfiguration.toneMappingEnabled;
  42686. },
  42687. /**
  42688. * Sets wether tonemapping is enabled or not
  42689. */
  42690. set: function (value) {
  42691. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42692. },
  42693. enumerable: true,
  42694. configurable: true
  42695. });
  42696. ;
  42697. ;
  42698. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42699. /**
  42700. * The camera exposure used on this material.
  42701. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42702. * This corresponds to a photographic exposure.
  42703. */
  42704. get: function () {
  42705. return this._imageProcessingConfiguration.exposure;
  42706. },
  42707. /**
  42708. * The camera exposure used on this material.
  42709. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42710. * This corresponds to a photographic exposure.
  42711. */
  42712. set: function (value) {
  42713. this._imageProcessingConfiguration.exposure = value;
  42714. },
  42715. enumerable: true,
  42716. configurable: true
  42717. });
  42718. ;
  42719. ;
  42720. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42721. /**
  42722. * Gets The camera contrast used on this material.
  42723. */
  42724. get: function () {
  42725. return this._imageProcessingConfiguration.contrast;
  42726. },
  42727. /**
  42728. * Sets The camera contrast used on this material.
  42729. */
  42730. set: function (value) {
  42731. this._imageProcessingConfiguration.contrast = value;
  42732. },
  42733. enumerable: true,
  42734. configurable: true
  42735. });
  42736. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42737. /**
  42738. * Gets the Color Grading 2D Lookup Texture.
  42739. */
  42740. get: function () {
  42741. return this._imageProcessingConfiguration.colorGradingTexture;
  42742. },
  42743. /**
  42744. * Sets the Color Grading 2D Lookup Texture.
  42745. */
  42746. set: function (value) {
  42747. this._imageProcessingConfiguration.colorGradingTexture = value;
  42748. },
  42749. enumerable: true,
  42750. configurable: true
  42751. });
  42752. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42753. /**
  42754. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42755. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42756. * 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;
  42757. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42758. */
  42759. get: function () {
  42760. return this._imageProcessingConfiguration.colorCurves;
  42761. },
  42762. /**
  42763. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42764. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42765. * 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;
  42766. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42767. */
  42768. set: function (value) {
  42769. this._imageProcessingConfiguration.colorCurves = value;
  42770. },
  42771. enumerable: true,
  42772. configurable: true
  42773. });
  42774. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  42775. /**
  42776. * Gets a boolean indicating that current material needs to register RTT
  42777. */
  42778. get: function () {
  42779. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42780. return true;
  42781. }
  42782. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42783. return true;
  42784. }
  42785. return false;
  42786. },
  42787. enumerable: true,
  42788. configurable: true
  42789. });
  42790. /**
  42791. * Gets the current class name of the material e.g. "StandardMaterial"
  42792. * Mainly use in serialization.
  42793. * @returns the class name
  42794. */
  42795. StandardMaterial.prototype.getClassName = function () {
  42796. return "StandardMaterial";
  42797. };
  42798. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42799. /**
  42800. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  42801. * You can try switching to logarithmic depth.
  42802. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  42803. */
  42804. get: function () {
  42805. return this._useLogarithmicDepth;
  42806. },
  42807. set: function (value) {
  42808. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42809. this._markAllSubMeshesAsMiscDirty();
  42810. },
  42811. enumerable: true,
  42812. configurable: true
  42813. });
  42814. /**
  42815. * Specifies if the material will require alpha blending
  42816. * @returns a boolean specifying if alpha blending is needed
  42817. */
  42818. StandardMaterial.prototype.needAlphaBlending = function () {
  42819. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42820. };
  42821. /**
  42822. * Specifies if this material should be rendered in alpha test mode
  42823. * @returns a boolean specifying if an alpha test is needed.
  42824. */
  42825. StandardMaterial.prototype.needAlphaTesting = function () {
  42826. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42827. };
  42828. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42829. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42830. };
  42831. /**
  42832. * Get the texture used for alpha test purpose.
  42833. * @returns the diffuse texture in case of the standard material.
  42834. */
  42835. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42836. return this._diffuseTexture;
  42837. };
  42838. /**
  42839. * Get if the submesh is ready to be used and all its information available.
  42840. * Child classes can use it to update shaders
  42841. * @param mesh defines the mesh to check
  42842. * @param subMesh defines which submesh to check
  42843. * @param useInstances specifies that instances should be used
  42844. * @returns a boolean indicating that the submesh is ready or not
  42845. */
  42846. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42847. if (useInstances === void 0) { useInstances = false; }
  42848. if (subMesh.effect && this.isFrozen) {
  42849. if (this._wasPreviouslyReady) {
  42850. return true;
  42851. }
  42852. }
  42853. if (!subMesh._materialDefines) {
  42854. subMesh._materialDefines = new StandardMaterialDefines();
  42855. }
  42856. var scene = this.getScene();
  42857. var defines = subMesh._materialDefines;
  42858. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42859. if (defines._renderId === scene.getRenderId()) {
  42860. return true;
  42861. }
  42862. }
  42863. var engine = scene.getEngine();
  42864. // Lights
  42865. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42866. // Textures
  42867. if (defines._areTexturesDirty) {
  42868. defines._needUVs = false;
  42869. defines.MAINUV1 = false;
  42870. defines.MAINUV2 = false;
  42871. if (scene.texturesEnabled) {
  42872. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42873. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42874. return false;
  42875. }
  42876. else {
  42877. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42878. }
  42879. }
  42880. else {
  42881. defines.DIFFUSE = false;
  42882. }
  42883. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42884. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42885. return false;
  42886. }
  42887. else {
  42888. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42889. }
  42890. }
  42891. else {
  42892. defines.AMBIENT = false;
  42893. }
  42894. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42895. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42896. return false;
  42897. }
  42898. else {
  42899. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42900. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42901. }
  42902. }
  42903. else {
  42904. defines.OPACITY = false;
  42905. }
  42906. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42907. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42908. return false;
  42909. }
  42910. else {
  42911. defines._needNormals = true;
  42912. defines.REFLECTION = true;
  42913. defines.ROUGHNESS = (this._roughness > 0);
  42914. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42915. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42916. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42917. switch (this._reflectionTexture.coordinatesMode) {
  42918. case BABYLON.Texture.EXPLICIT_MODE:
  42919. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42920. break;
  42921. case BABYLON.Texture.PLANAR_MODE:
  42922. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42923. break;
  42924. case BABYLON.Texture.PROJECTION_MODE:
  42925. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42926. break;
  42927. case BABYLON.Texture.SKYBOX_MODE:
  42928. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42929. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42930. break;
  42931. case BABYLON.Texture.SPHERICAL_MODE:
  42932. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42933. break;
  42934. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42935. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42936. break;
  42937. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42938. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42939. break;
  42940. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42941. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42942. break;
  42943. case BABYLON.Texture.CUBIC_MODE:
  42944. case BABYLON.Texture.INVCUBIC_MODE:
  42945. default:
  42946. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42947. break;
  42948. }
  42949. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42950. }
  42951. }
  42952. else {
  42953. defines.REFLECTION = false;
  42954. }
  42955. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42956. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42957. return false;
  42958. }
  42959. else {
  42960. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42961. }
  42962. }
  42963. else {
  42964. defines.EMISSIVE = false;
  42965. }
  42966. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42967. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42968. return false;
  42969. }
  42970. else {
  42971. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42972. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42973. }
  42974. }
  42975. else {
  42976. defines.LIGHTMAP = false;
  42977. }
  42978. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42979. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42980. return false;
  42981. }
  42982. else {
  42983. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42984. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42985. }
  42986. }
  42987. else {
  42988. defines.SPECULAR = false;
  42989. }
  42990. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42991. // Bump texure can not be not blocking.
  42992. if (!this._bumpTexture.isReady()) {
  42993. return false;
  42994. }
  42995. else {
  42996. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42997. defines.PARALLAX = this._useParallax;
  42998. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42999. }
  43000. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43001. }
  43002. else {
  43003. defines.BUMP = false;
  43004. }
  43005. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43006. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43007. return false;
  43008. }
  43009. else {
  43010. defines._needUVs = true;
  43011. defines.REFRACTION = true;
  43012. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43013. }
  43014. }
  43015. else {
  43016. defines.REFRACTION = false;
  43017. }
  43018. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43019. }
  43020. else {
  43021. defines.DIFFUSE = false;
  43022. defines.AMBIENT = false;
  43023. defines.OPACITY = false;
  43024. defines.REFLECTION = false;
  43025. defines.EMISSIVE = false;
  43026. defines.LIGHTMAP = false;
  43027. defines.BUMP = false;
  43028. defines.REFRACTION = false;
  43029. }
  43030. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43031. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43032. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43033. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43034. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43035. }
  43036. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43037. if (!this._imageProcessingConfiguration.isReady()) {
  43038. return false;
  43039. }
  43040. this._imageProcessingConfiguration.prepareDefines(defines);
  43041. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43042. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43043. }
  43044. if (defines._areFresnelDirty) {
  43045. if (StandardMaterial.FresnelEnabled) {
  43046. // Fresnel
  43047. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43048. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43049. this._reflectionFresnelParameters) {
  43050. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43051. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43052. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43053. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43054. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43055. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43056. defines._needNormals = true;
  43057. defines.FRESNEL = true;
  43058. }
  43059. }
  43060. else {
  43061. defines.FRESNEL = false;
  43062. }
  43063. }
  43064. // Misc.
  43065. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43066. // Attribs
  43067. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43068. // Values that need to be evaluated on every frame
  43069. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43070. // Get correct effect
  43071. if (defines.isDirty) {
  43072. defines.markAsProcessed();
  43073. scene.resetCachedMaterial();
  43074. // Fallbacks
  43075. var fallbacks = new BABYLON.EffectFallbacks();
  43076. if (defines.REFLECTION) {
  43077. fallbacks.addFallback(0, "REFLECTION");
  43078. }
  43079. if (defines.SPECULAR) {
  43080. fallbacks.addFallback(0, "SPECULAR");
  43081. }
  43082. if (defines.BUMP) {
  43083. fallbacks.addFallback(0, "BUMP");
  43084. }
  43085. if (defines.PARALLAX) {
  43086. fallbacks.addFallback(1, "PARALLAX");
  43087. }
  43088. if (defines.PARALLAXOCCLUSION) {
  43089. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43090. }
  43091. if (defines.SPECULAROVERALPHA) {
  43092. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43093. }
  43094. if (defines.FOG) {
  43095. fallbacks.addFallback(1, "FOG");
  43096. }
  43097. if (defines.POINTSIZE) {
  43098. fallbacks.addFallback(0, "POINTSIZE");
  43099. }
  43100. if (defines.LOGARITHMICDEPTH) {
  43101. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43102. }
  43103. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43104. if (defines.SPECULARTERM) {
  43105. fallbacks.addFallback(0, "SPECULARTERM");
  43106. }
  43107. if (defines.DIFFUSEFRESNEL) {
  43108. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43109. }
  43110. if (defines.OPACITYFRESNEL) {
  43111. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43112. }
  43113. if (defines.REFLECTIONFRESNEL) {
  43114. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43115. }
  43116. if (defines.EMISSIVEFRESNEL) {
  43117. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43118. }
  43119. if (defines.FRESNEL) {
  43120. fallbacks.addFallback(4, "FRESNEL");
  43121. }
  43122. //Attributes
  43123. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43124. if (defines.NORMAL) {
  43125. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43126. }
  43127. if (defines.UV1) {
  43128. attribs.push(BABYLON.VertexBuffer.UVKind);
  43129. }
  43130. if (defines.UV2) {
  43131. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43132. }
  43133. if (defines.VERTEXCOLOR) {
  43134. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43135. }
  43136. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43137. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43138. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43139. var shaderName = "default";
  43140. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43141. "vFogInfos", "vFogColor", "pointSize",
  43142. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43143. "mBones",
  43144. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43145. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43146. "vReflectionPosition", "vReflectionSize",
  43147. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43148. ];
  43149. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43150. var uniformBuffers = ["Material", "Scene"];
  43151. if (BABYLON.ImageProcessingConfiguration) {
  43152. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43153. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43154. }
  43155. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43156. uniformsNames: uniforms,
  43157. uniformBuffersNames: uniformBuffers,
  43158. samplers: samplers,
  43159. defines: defines,
  43160. maxSimultaneousLights: this._maxSimultaneousLights
  43161. });
  43162. if (this.customShaderNameResolve) {
  43163. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43164. }
  43165. var join = defines.toString();
  43166. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43167. attributes: attribs,
  43168. uniformsNames: uniforms,
  43169. uniformBuffersNames: uniformBuffers,
  43170. samplers: samplers,
  43171. defines: join,
  43172. fallbacks: fallbacks,
  43173. onCompiled: this.onCompiled,
  43174. onError: this.onError,
  43175. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43176. }, engine), defines);
  43177. this.buildUniformLayout();
  43178. }
  43179. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43180. return false;
  43181. }
  43182. defines._renderId = scene.getRenderId();
  43183. this._wasPreviouslyReady = true;
  43184. return true;
  43185. };
  43186. /**
  43187. * Builds the material UBO layouts.
  43188. * Used internally during the effect preparation.
  43189. */
  43190. StandardMaterial.prototype.buildUniformLayout = function () {
  43191. // Order is important !
  43192. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43193. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43194. this._uniformBuffer.addUniform("opacityParts", 4);
  43195. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43196. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43197. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43198. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43199. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43200. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43201. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43202. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43203. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43204. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43205. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43206. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43207. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43208. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43209. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43210. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43211. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43212. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43213. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43214. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43215. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43216. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43217. this._uniformBuffer.addUniform("specularMatrix", 16);
  43218. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43219. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43220. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43221. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43222. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43223. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43224. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43225. this._uniformBuffer.addUniform("pointSize", 1);
  43226. this._uniformBuffer.create();
  43227. };
  43228. /**
  43229. * Unbinds the material from the mesh
  43230. */
  43231. StandardMaterial.prototype.unbind = function () {
  43232. if (this._activeEffect) {
  43233. var needFlag = false;
  43234. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43235. this._activeEffect.setTexture("reflection2DSampler", null);
  43236. needFlag = true;
  43237. }
  43238. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43239. this._activeEffect.setTexture("refraction2DSampler", null);
  43240. needFlag = true;
  43241. }
  43242. if (needFlag) {
  43243. this._markAllSubMeshesAsTexturesDirty();
  43244. }
  43245. }
  43246. _super.prototype.unbind.call(this);
  43247. };
  43248. /**
  43249. * Binds the submesh to this material by preparing the effect and shader to draw
  43250. * @param world defines the world transformation matrix
  43251. * @param mesh defines the mesh containing the submesh
  43252. * @param subMesh defines the submesh to bind the material to
  43253. */
  43254. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43255. var scene = this.getScene();
  43256. var defines = subMesh._materialDefines;
  43257. if (!defines) {
  43258. return;
  43259. }
  43260. var effect = subMesh.effect;
  43261. if (!effect) {
  43262. return;
  43263. }
  43264. this._activeEffect = effect;
  43265. // Matrices
  43266. this.bindOnlyWorldMatrix(world);
  43267. // Normal Matrix
  43268. if (defines.OBJECTSPACE_NORMALMAP) {
  43269. world.toNormalMatrix(this._normalMatrix);
  43270. this.bindOnlyNormalMatrix(this._normalMatrix);
  43271. }
  43272. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43273. // Bones
  43274. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43275. if (mustRebind) {
  43276. this._uniformBuffer.bindToEffect(effect, "Material");
  43277. this.bindViewProjection(effect);
  43278. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43279. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43280. // Fresnel
  43281. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43282. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43283. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43284. }
  43285. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43286. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43287. }
  43288. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43289. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43290. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43291. }
  43292. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43293. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43294. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43295. }
  43296. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43297. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43298. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43299. }
  43300. }
  43301. // Textures
  43302. if (scene.texturesEnabled) {
  43303. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43304. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43305. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43306. if (this._diffuseTexture.hasAlpha) {
  43307. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43308. }
  43309. }
  43310. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43311. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43312. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43313. }
  43314. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43315. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43316. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43317. }
  43318. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43319. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43320. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43321. if (this._reflectionTexture.boundingBoxSize) {
  43322. var cubeTexture = this._reflectionTexture;
  43323. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43324. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43325. }
  43326. }
  43327. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43328. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43329. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43330. }
  43331. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43332. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43333. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43334. }
  43335. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43336. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43337. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43338. }
  43339. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43340. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43341. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43342. if (scene._mirroredCameraPosition) {
  43343. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43344. }
  43345. else {
  43346. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43347. }
  43348. }
  43349. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43350. var depth = 1.0;
  43351. if (!this._refractionTexture.isCube) {
  43352. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43353. if (this._refractionTexture.depth) {
  43354. depth = this._refractionTexture.depth;
  43355. }
  43356. }
  43357. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43358. }
  43359. }
  43360. // Point size
  43361. if (this.pointsCloud) {
  43362. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43363. }
  43364. if (defines.SPECULARTERM) {
  43365. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43366. }
  43367. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43368. // Diffuse
  43369. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43370. }
  43371. // Textures
  43372. if (scene.texturesEnabled) {
  43373. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43374. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43375. }
  43376. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43377. effect.setTexture("ambientSampler", this._ambientTexture);
  43378. }
  43379. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43380. effect.setTexture("opacitySampler", this._opacityTexture);
  43381. }
  43382. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43383. if (this._reflectionTexture.isCube) {
  43384. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43385. }
  43386. else {
  43387. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43388. }
  43389. }
  43390. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43391. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43392. }
  43393. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43394. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43395. }
  43396. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43397. effect.setTexture("specularSampler", this._specularTexture);
  43398. }
  43399. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43400. effect.setTexture("bumpSampler", this._bumpTexture);
  43401. }
  43402. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43403. var depth = 1.0;
  43404. if (this._refractionTexture.isCube) {
  43405. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43406. }
  43407. else {
  43408. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43409. }
  43410. }
  43411. }
  43412. // Clip plane
  43413. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43414. // Colors
  43415. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43416. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43417. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43418. }
  43419. if (mustRebind || !this.isFrozen) {
  43420. // Lights
  43421. if (scene.lightsEnabled && !this._disableLighting) {
  43422. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43423. }
  43424. // View
  43425. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43426. this.bindView(effect);
  43427. }
  43428. // Fog
  43429. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43430. // Morph targets
  43431. if (defines.NUM_MORPH_INFLUENCERS) {
  43432. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43433. }
  43434. // Log. depth
  43435. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43436. // image processing
  43437. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  43438. this._imageProcessingConfiguration.bind(this._activeEffect);
  43439. }
  43440. }
  43441. this._uniformBuffer.update();
  43442. this._afterBind(mesh, this._activeEffect);
  43443. };
  43444. /**
  43445. * Get the list of animatables in the material.
  43446. * @returns the list of animatables object used in the material
  43447. */
  43448. StandardMaterial.prototype.getAnimatables = function () {
  43449. var results = [];
  43450. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43451. results.push(this._diffuseTexture);
  43452. }
  43453. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43454. results.push(this._ambientTexture);
  43455. }
  43456. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43457. results.push(this._opacityTexture);
  43458. }
  43459. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43460. results.push(this._reflectionTexture);
  43461. }
  43462. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43463. results.push(this._emissiveTexture);
  43464. }
  43465. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43466. results.push(this._specularTexture);
  43467. }
  43468. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43469. results.push(this._bumpTexture);
  43470. }
  43471. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43472. results.push(this._lightmapTexture);
  43473. }
  43474. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43475. results.push(this._refractionTexture);
  43476. }
  43477. return results;
  43478. };
  43479. /**
  43480. * Gets the active textures from the material
  43481. * @returns an array of textures
  43482. */
  43483. StandardMaterial.prototype.getActiveTextures = function () {
  43484. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43485. if (this._diffuseTexture) {
  43486. activeTextures.push(this._diffuseTexture);
  43487. }
  43488. if (this._ambientTexture) {
  43489. activeTextures.push(this._ambientTexture);
  43490. }
  43491. if (this._opacityTexture) {
  43492. activeTextures.push(this._opacityTexture);
  43493. }
  43494. if (this._reflectionTexture) {
  43495. activeTextures.push(this._reflectionTexture);
  43496. }
  43497. if (this._emissiveTexture) {
  43498. activeTextures.push(this._emissiveTexture);
  43499. }
  43500. if (this._specularTexture) {
  43501. activeTextures.push(this._specularTexture);
  43502. }
  43503. if (this._bumpTexture) {
  43504. activeTextures.push(this._bumpTexture);
  43505. }
  43506. if (this._lightmapTexture) {
  43507. activeTextures.push(this._lightmapTexture);
  43508. }
  43509. if (this._refractionTexture) {
  43510. activeTextures.push(this._refractionTexture);
  43511. }
  43512. return activeTextures;
  43513. };
  43514. /**
  43515. * Specifies if the material uses a texture
  43516. * @param texture defines the texture to check against the material
  43517. * @returns a boolean specifying if the material uses the texture
  43518. */
  43519. StandardMaterial.prototype.hasTexture = function (texture) {
  43520. if (_super.prototype.hasTexture.call(this, texture)) {
  43521. return true;
  43522. }
  43523. if (this._diffuseTexture === texture) {
  43524. return true;
  43525. }
  43526. if (this._ambientTexture === texture) {
  43527. return true;
  43528. }
  43529. if (this._opacityTexture === texture) {
  43530. return true;
  43531. }
  43532. if (this._reflectionTexture === texture) {
  43533. return true;
  43534. }
  43535. if (this._emissiveTexture === texture) {
  43536. return true;
  43537. }
  43538. if (this._specularTexture === texture) {
  43539. return true;
  43540. }
  43541. if (this._bumpTexture === texture) {
  43542. return true;
  43543. }
  43544. if (this._lightmapTexture === texture) {
  43545. return true;
  43546. }
  43547. if (this._refractionTexture === texture) {
  43548. return true;
  43549. }
  43550. return false;
  43551. };
  43552. /**
  43553. * Disposes the material
  43554. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  43555. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  43556. */
  43557. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43558. if (forceDisposeTextures) {
  43559. if (this._diffuseTexture) {
  43560. this._diffuseTexture.dispose();
  43561. }
  43562. if (this._ambientTexture) {
  43563. this._ambientTexture.dispose();
  43564. }
  43565. if (this._opacityTexture) {
  43566. this._opacityTexture.dispose();
  43567. }
  43568. if (this._reflectionTexture) {
  43569. this._reflectionTexture.dispose();
  43570. }
  43571. if (this._emissiveTexture) {
  43572. this._emissiveTexture.dispose();
  43573. }
  43574. if (this._specularTexture) {
  43575. this._specularTexture.dispose();
  43576. }
  43577. if (this._bumpTexture) {
  43578. this._bumpTexture.dispose();
  43579. }
  43580. if (this._lightmapTexture) {
  43581. this._lightmapTexture.dispose();
  43582. }
  43583. if (this._refractionTexture) {
  43584. this._refractionTexture.dispose();
  43585. }
  43586. }
  43587. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43588. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43589. }
  43590. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43591. };
  43592. /**
  43593. * Makes a duplicate of the material, and gives it a new name
  43594. * @param name defines the new name for the duplicated material
  43595. * @returns the cloned material
  43596. */
  43597. StandardMaterial.prototype.clone = function (name) {
  43598. var _this = this;
  43599. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43600. result.name = name;
  43601. result.id = name;
  43602. return result;
  43603. };
  43604. /**
  43605. * Serializes this material in a JSON representation
  43606. * @returns the serialized material object
  43607. */
  43608. StandardMaterial.prototype.serialize = function () {
  43609. return BABYLON.SerializationHelper.Serialize(this);
  43610. };
  43611. /**
  43612. * Creates a standard material from parsed material data
  43613. * @param source defines the JSON represnetation of the material
  43614. * @param scene defines the hosting scene
  43615. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  43616. * @returns a new material
  43617. */
  43618. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43619. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43620. };
  43621. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43622. /**
  43623. * Are diffuse textures enabled in the application.
  43624. */
  43625. get: function () {
  43626. return StandardMaterial._DiffuseTextureEnabled;
  43627. },
  43628. set: function (value) {
  43629. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43630. return;
  43631. }
  43632. StandardMaterial._DiffuseTextureEnabled = value;
  43633. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43634. },
  43635. enumerable: true,
  43636. configurable: true
  43637. });
  43638. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43639. /**
  43640. * Are ambient textures enabled in the application.
  43641. */
  43642. get: function () {
  43643. return StandardMaterial._AmbientTextureEnabled;
  43644. },
  43645. set: function (value) {
  43646. if (StandardMaterial._AmbientTextureEnabled === value) {
  43647. return;
  43648. }
  43649. StandardMaterial._AmbientTextureEnabled = value;
  43650. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43651. },
  43652. enumerable: true,
  43653. configurable: true
  43654. });
  43655. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43656. /**
  43657. * Are opacity textures enabled in the application.
  43658. */
  43659. get: function () {
  43660. return StandardMaterial._OpacityTextureEnabled;
  43661. },
  43662. set: function (value) {
  43663. if (StandardMaterial._OpacityTextureEnabled === value) {
  43664. return;
  43665. }
  43666. StandardMaterial._OpacityTextureEnabled = value;
  43667. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43668. },
  43669. enumerable: true,
  43670. configurable: true
  43671. });
  43672. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43673. /**
  43674. * Are reflection textures enabled in the application.
  43675. */
  43676. get: function () {
  43677. return StandardMaterial._ReflectionTextureEnabled;
  43678. },
  43679. set: function (value) {
  43680. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43681. return;
  43682. }
  43683. StandardMaterial._ReflectionTextureEnabled = value;
  43684. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43685. },
  43686. enumerable: true,
  43687. configurable: true
  43688. });
  43689. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43690. /**
  43691. * Are emissive textures enabled in the application.
  43692. */
  43693. get: function () {
  43694. return StandardMaterial._EmissiveTextureEnabled;
  43695. },
  43696. set: function (value) {
  43697. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43698. return;
  43699. }
  43700. StandardMaterial._EmissiveTextureEnabled = value;
  43701. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43702. },
  43703. enumerable: true,
  43704. configurable: true
  43705. });
  43706. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43707. /**
  43708. * Are specular textures enabled in the application.
  43709. */
  43710. get: function () {
  43711. return StandardMaterial._SpecularTextureEnabled;
  43712. },
  43713. set: function (value) {
  43714. if (StandardMaterial._SpecularTextureEnabled === value) {
  43715. return;
  43716. }
  43717. StandardMaterial._SpecularTextureEnabled = value;
  43718. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43719. },
  43720. enumerable: true,
  43721. configurable: true
  43722. });
  43723. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43724. /**
  43725. * Are bump textures enabled in the application.
  43726. */
  43727. get: function () {
  43728. return StandardMaterial._BumpTextureEnabled;
  43729. },
  43730. set: function (value) {
  43731. if (StandardMaterial._BumpTextureEnabled === value) {
  43732. return;
  43733. }
  43734. StandardMaterial._BumpTextureEnabled = value;
  43735. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43736. },
  43737. enumerable: true,
  43738. configurable: true
  43739. });
  43740. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43741. /**
  43742. * Are lightmap textures enabled in the application.
  43743. */
  43744. get: function () {
  43745. return StandardMaterial._LightmapTextureEnabled;
  43746. },
  43747. set: function (value) {
  43748. if (StandardMaterial._LightmapTextureEnabled === value) {
  43749. return;
  43750. }
  43751. StandardMaterial._LightmapTextureEnabled = value;
  43752. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43753. },
  43754. enumerable: true,
  43755. configurable: true
  43756. });
  43757. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43758. /**
  43759. * Are refraction textures enabled in the application.
  43760. */
  43761. get: function () {
  43762. return StandardMaterial._RefractionTextureEnabled;
  43763. },
  43764. set: function (value) {
  43765. if (StandardMaterial._RefractionTextureEnabled === value) {
  43766. return;
  43767. }
  43768. StandardMaterial._RefractionTextureEnabled = value;
  43769. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43770. },
  43771. enumerable: true,
  43772. configurable: true
  43773. });
  43774. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43775. /**
  43776. * Are color grading textures enabled in the application.
  43777. */
  43778. get: function () {
  43779. return StandardMaterial._ColorGradingTextureEnabled;
  43780. },
  43781. set: function (value) {
  43782. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43783. return;
  43784. }
  43785. StandardMaterial._ColorGradingTextureEnabled = value;
  43786. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43787. },
  43788. enumerable: true,
  43789. configurable: true
  43790. });
  43791. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43792. /**
  43793. * Are fresnels enabled in the application.
  43794. */
  43795. get: function () {
  43796. return StandardMaterial._FresnelEnabled;
  43797. },
  43798. set: function (value) {
  43799. if (StandardMaterial._FresnelEnabled === value) {
  43800. return;
  43801. }
  43802. StandardMaterial._FresnelEnabled = value;
  43803. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43804. },
  43805. enumerable: true,
  43806. configurable: true
  43807. });
  43808. // Flags used to enable or disable a type of texture for all Standard Materials
  43809. StandardMaterial._DiffuseTextureEnabled = true;
  43810. StandardMaterial._AmbientTextureEnabled = true;
  43811. StandardMaterial._OpacityTextureEnabled = true;
  43812. StandardMaterial._ReflectionTextureEnabled = true;
  43813. StandardMaterial._EmissiveTextureEnabled = true;
  43814. StandardMaterial._SpecularTextureEnabled = true;
  43815. StandardMaterial._BumpTextureEnabled = true;
  43816. StandardMaterial._LightmapTextureEnabled = true;
  43817. StandardMaterial._RefractionTextureEnabled = true;
  43818. StandardMaterial._ColorGradingTextureEnabled = true;
  43819. StandardMaterial._FresnelEnabled = true;
  43820. __decorate([
  43821. BABYLON.serializeAsTexture("diffuseTexture")
  43822. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43823. __decorate([
  43824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43825. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43826. __decorate([
  43827. BABYLON.serializeAsTexture("ambientTexture")
  43828. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43829. __decorate([
  43830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43831. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43832. __decorate([
  43833. BABYLON.serializeAsTexture("opacityTexture")
  43834. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43835. __decorate([
  43836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43837. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43838. __decorate([
  43839. BABYLON.serializeAsTexture("reflectionTexture")
  43840. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43841. __decorate([
  43842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43843. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43844. __decorate([
  43845. BABYLON.serializeAsTexture("emissiveTexture")
  43846. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43847. __decorate([
  43848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43849. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43850. __decorate([
  43851. BABYLON.serializeAsTexture("specularTexture")
  43852. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43853. __decorate([
  43854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43855. ], StandardMaterial.prototype, "specularTexture", void 0);
  43856. __decorate([
  43857. BABYLON.serializeAsTexture("bumpTexture")
  43858. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43859. __decorate([
  43860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43861. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43862. __decorate([
  43863. BABYLON.serializeAsTexture("lightmapTexture")
  43864. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43865. __decorate([
  43866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43867. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43868. __decorate([
  43869. BABYLON.serializeAsTexture("refractionTexture")
  43870. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43871. __decorate([
  43872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43873. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43874. __decorate([
  43875. BABYLON.serializeAsColor3("ambient")
  43876. ], StandardMaterial.prototype, "ambientColor", void 0);
  43877. __decorate([
  43878. BABYLON.serializeAsColor3("diffuse")
  43879. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43880. __decorate([
  43881. BABYLON.serializeAsColor3("specular")
  43882. ], StandardMaterial.prototype, "specularColor", void 0);
  43883. __decorate([
  43884. BABYLON.serializeAsColor3("emissive")
  43885. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43886. __decorate([
  43887. BABYLON.serialize()
  43888. ], StandardMaterial.prototype, "specularPower", void 0);
  43889. __decorate([
  43890. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43891. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43892. __decorate([
  43893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43894. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43895. __decorate([
  43896. BABYLON.serialize("useEmissiveAsIllumination")
  43897. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43898. __decorate([
  43899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43900. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43901. __decorate([
  43902. BABYLON.serialize("linkEmissiveWithDiffuse")
  43903. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43904. __decorate([
  43905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43906. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43907. __decorate([
  43908. BABYLON.serialize("useSpecularOverAlpha")
  43909. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43910. __decorate([
  43911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43912. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43913. __decorate([
  43914. BABYLON.serialize("useReflectionOverAlpha")
  43915. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43916. __decorate([
  43917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43918. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43919. __decorate([
  43920. BABYLON.serialize("disableLighting")
  43921. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43922. __decorate([
  43923. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43924. ], StandardMaterial.prototype, "disableLighting", void 0);
  43925. __decorate([
  43926. BABYLON.serialize("useObjectSpaceNormalMap")
  43927. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43928. __decorate([
  43929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43930. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43931. __decorate([
  43932. BABYLON.serialize("useParallax")
  43933. ], StandardMaterial.prototype, "_useParallax", void 0);
  43934. __decorate([
  43935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43936. ], StandardMaterial.prototype, "useParallax", void 0);
  43937. __decorate([
  43938. BABYLON.serialize("useParallaxOcclusion")
  43939. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43940. __decorate([
  43941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43942. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43943. __decorate([
  43944. BABYLON.serialize()
  43945. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43946. __decorate([
  43947. BABYLON.serialize("roughness")
  43948. ], StandardMaterial.prototype, "_roughness", void 0);
  43949. __decorate([
  43950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43951. ], StandardMaterial.prototype, "roughness", void 0);
  43952. __decorate([
  43953. BABYLON.serialize()
  43954. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43955. __decorate([
  43956. BABYLON.serialize()
  43957. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43958. __decorate([
  43959. BABYLON.serialize()
  43960. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43961. __decorate([
  43962. BABYLON.serialize("useLightmapAsShadowmap")
  43963. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43964. __decorate([
  43965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43966. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43967. __decorate([
  43968. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43969. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43970. __decorate([
  43971. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43972. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43973. __decorate([
  43974. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43975. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43976. __decorate([
  43977. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43978. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43979. __decorate([
  43980. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43981. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43982. __decorate([
  43983. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43984. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43985. __decorate([
  43986. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43987. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43988. __decorate([
  43989. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43990. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43991. __decorate([
  43992. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43993. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43994. __decorate([
  43995. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43996. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43997. __decorate([
  43998. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43999. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44000. __decorate([
  44001. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44002. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44003. __decorate([
  44004. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44005. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44006. __decorate([
  44007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44008. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44009. __decorate([
  44010. BABYLON.serialize("maxSimultaneousLights")
  44011. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44012. __decorate([
  44013. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44014. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44015. __decorate([
  44016. BABYLON.serialize("invertNormalMapX")
  44017. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44018. __decorate([
  44019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44020. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44021. __decorate([
  44022. BABYLON.serialize("invertNormalMapY")
  44023. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44024. __decorate([
  44025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44026. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44027. __decorate([
  44028. BABYLON.serialize("twoSidedLighting")
  44029. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44030. __decorate([
  44031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44032. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44033. __decorate([
  44034. BABYLON.serialize()
  44035. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44036. return StandardMaterial;
  44037. }(BABYLON.PushMaterial));
  44038. BABYLON.StandardMaterial = StandardMaterial;
  44039. })(BABYLON || (BABYLON = {}));
  44040. //# sourceMappingURL=babylon.standardMaterial.js.map
  44041. var BABYLON;
  44042. (function (BABYLON) {
  44043. /**
  44044. * Class representing spherical polynomial coefficients to the 3rd degree
  44045. */
  44046. var SphericalPolynomial = /** @class */ (function () {
  44047. function SphericalPolynomial() {
  44048. /**
  44049. * The x coefficients of the spherical polynomial
  44050. */
  44051. this.x = BABYLON.Vector3.Zero();
  44052. /**
  44053. * The y coefficients of the spherical polynomial
  44054. */
  44055. this.y = BABYLON.Vector3.Zero();
  44056. /**
  44057. * The z coefficients of the spherical polynomial
  44058. */
  44059. this.z = BABYLON.Vector3.Zero();
  44060. /**
  44061. * The xx coefficients of the spherical polynomial
  44062. */
  44063. this.xx = BABYLON.Vector3.Zero();
  44064. /**
  44065. * The yy coefficients of the spherical polynomial
  44066. */
  44067. this.yy = BABYLON.Vector3.Zero();
  44068. /**
  44069. * The zz coefficients of the spherical polynomial
  44070. */
  44071. this.zz = BABYLON.Vector3.Zero();
  44072. /**
  44073. * The xy coefficients of the spherical polynomial
  44074. */
  44075. this.xy = BABYLON.Vector3.Zero();
  44076. /**
  44077. * The yz coefficients of the spherical polynomial
  44078. */
  44079. this.yz = BABYLON.Vector3.Zero();
  44080. /**
  44081. * The zx coefficients of the spherical polynomial
  44082. */
  44083. this.zx = BABYLON.Vector3.Zero();
  44084. }
  44085. /**
  44086. * Adds an ambient color to the spherical polynomial
  44087. * @param color the color to add
  44088. */
  44089. SphericalPolynomial.prototype.addAmbient = function (color) {
  44090. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44091. this.xx = this.xx.add(colorVector);
  44092. this.yy = this.yy.add(colorVector);
  44093. this.zz = this.zz.add(colorVector);
  44094. };
  44095. /**
  44096. * Scales the spherical polynomial by the given amount
  44097. * @param scale the amount to scale
  44098. */
  44099. SphericalPolynomial.prototype.scale = function (scale) {
  44100. this.x = this.x.scale(scale);
  44101. this.y = this.y.scale(scale);
  44102. this.z = this.z.scale(scale);
  44103. this.xx = this.xx.scale(scale);
  44104. this.yy = this.yy.scale(scale);
  44105. this.zz = this.zz.scale(scale);
  44106. this.yz = this.yz.scale(scale);
  44107. this.zx = this.zx.scale(scale);
  44108. this.xy = this.xy.scale(scale);
  44109. };
  44110. /**
  44111. * Gets the spherical polynomial from harmonics
  44112. * @param harmonics the spherical harmonics
  44113. * @returns the spherical polynomial
  44114. */
  44115. SphericalPolynomial.FromHarmonics = function (harmonics) {
  44116. var result = new SphericalPolynomial();
  44117. result.x = harmonics.l11.scale(1.02333);
  44118. result.y = harmonics.l1_1.scale(1.02333);
  44119. result.z = harmonics.l10.scale(1.02333);
  44120. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  44121. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  44122. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  44123. result.yz = harmonics.l2_1.scale(0.858086);
  44124. result.zx = harmonics.l21.scale(0.858086);
  44125. result.xy = harmonics.l2_2.scale(0.858086);
  44126. result.scale(1.0 / Math.PI);
  44127. return result;
  44128. };
  44129. /**
  44130. * Constructs a spherical polynomial from an array.
  44131. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  44132. * @returns the spherical polynomial
  44133. */
  44134. SphericalPolynomial.FromArray = function (data) {
  44135. var sp = new SphericalPolynomial();
  44136. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  44137. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  44138. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  44139. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  44140. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  44141. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  44142. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  44143. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  44144. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  44145. return sp;
  44146. };
  44147. return SphericalPolynomial;
  44148. }());
  44149. BABYLON.SphericalPolynomial = SphericalPolynomial;
  44150. /**
  44151. * Class representing spherical harmonics coefficients to the 3rd degree
  44152. */
  44153. var SphericalHarmonics = /** @class */ (function () {
  44154. function SphericalHarmonics() {
  44155. /**
  44156. * The l0,0 coefficients of the spherical harmonics
  44157. */
  44158. this.l00 = BABYLON.Vector3.Zero();
  44159. /**
  44160. * The l1,-1 coefficients of the spherical harmonics
  44161. */
  44162. this.l1_1 = BABYLON.Vector3.Zero();
  44163. /**
  44164. * The l1,0 coefficients of the spherical harmonics
  44165. */
  44166. this.l10 = BABYLON.Vector3.Zero();
  44167. /**
  44168. * The l1,1 coefficients of the spherical harmonics
  44169. */
  44170. this.l11 = BABYLON.Vector3.Zero();
  44171. /**
  44172. * The l2,-2 coefficients of the spherical harmonics
  44173. */
  44174. this.l2_2 = BABYLON.Vector3.Zero();
  44175. /**
  44176. * The l2,-1 coefficients of the spherical harmonics
  44177. */
  44178. this.l2_1 = BABYLON.Vector3.Zero();
  44179. /**
  44180. * The l2,0 coefficients of the spherical harmonics
  44181. */
  44182. this.l20 = BABYLON.Vector3.Zero();
  44183. /**
  44184. * The l2,1 coefficients of the spherical harmonics
  44185. */
  44186. this.l21 = BABYLON.Vector3.Zero();
  44187. /**
  44188. * The l2,2 coefficients of the spherical harmonics
  44189. */
  44190. this.lL22 = BABYLON.Vector3.Zero();
  44191. }
  44192. /**
  44193. * Adds a light to the spherical harmonics
  44194. * @param direction the direction of the light
  44195. * @param color the color of the light
  44196. * @param deltaSolidAngle the delta solid angle of the light
  44197. */
  44198. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44199. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44200. var c = colorVector.scale(deltaSolidAngle);
  44201. this.l00 = this.l00.add(c.scale(0.282095));
  44202. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44203. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44204. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44205. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44206. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44207. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44208. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44209. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44210. };
  44211. /**
  44212. * Scales the spherical harmonics by the given amount
  44213. * @param scale the amount to scale
  44214. */
  44215. SphericalHarmonics.prototype.scale = function (scale) {
  44216. this.l00 = this.l00.scale(scale);
  44217. this.l1_1 = this.l1_1.scale(scale);
  44218. this.l10 = this.l10.scale(scale);
  44219. this.l11 = this.l11.scale(scale);
  44220. this.l2_2 = this.l2_2.scale(scale);
  44221. this.l2_1 = this.l2_1.scale(scale);
  44222. this.l20 = this.l20.scale(scale);
  44223. this.l21 = this.l21.scale(scale);
  44224. this.lL22 = this.lL22.scale(scale);
  44225. };
  44226. /**
  44227. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44228. *
  44229. * ```
  44230. * E_lm = A_l * L_lm
  44231. * ```
  44232. *
  44233. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44234. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44235. * the scaling factors are given in equation 9.
  44236. */
  44237. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44238. // Constant (Band 0)
  44239. this.l00 = this.l00.scale(3.141593);
  44240. // Linear (Band 1)
  44241. this.l1_1 = this.l1_1.scale(2.094395);
  44242. this.l10 = this.l10.scale(2.094395);
  44243. this.l11 = this.l11.scale(2.094395);
  44244. // Quadratic (Band 2)
  44245. this.l2_2 = this.l2_2.scale(0.785398);
  44246. this.l2_1 = this.l2_1.scale(0.785398);
  44247. this.l20 = this.l20.scale(0.785398);
  44248. this.l21 = this.l21.scale(0.785398);
  44249. this.lL22 = this.lL22.scale(0.785398);
  44250. };
  44251. /**
  44252. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44253. *
  44254. * ```
  44255. * L = (1/pi) * E * rho
  44256. * ```
  44257. *
  44258. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44259. */
  44260. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44261. this.scale(1.0 / Math.PI);
  44262. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44263. // (The pixel shader must apply albedo after texture fetches, etc).
  44264. };
  44265. /**
  44266. * Gets the spherical harmonics from polynomial
  44267. * @param polynomial the spherical polynomial
  44268. * @returns the spherical harmonics
  44269. */
  44270. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44271. var result = new SphericalHarmonics();
  44272. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44273. result.l1_1 = polynomial.y.scale(0.977204);
  44274. result.l10 = polynomial.z.scale(0.977204);
  44275. result.l11 = polynomial.x.scale(0.977204);
  44276. result.l2_2 = polynomial.xy.scale(1.16538);
  44277. result.l2_1 = polynomial.yz.scale(1.16538);
  44278. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44279. result.l21 = polynomial.zx.scale(1.16538);
  44280. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44281. result.scale(Math.PI);
  44282. return result;
  44283. };
  44284. /**
  44285. * Constructs a spherical harmonics from an array.
  44286. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44287. * @returns the spherical harmonics
  44288. */
  44289. SphericalHarmonics.FromArray = function (data) {
  44290. var sh = new SphericalHarmonics();
  44291. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44292. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44293. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44294. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44295. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44296. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44297. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44298. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44299. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44300. return sh;
  44301. };
  44302. return SphericalHarmonics;
  44303. }());
  44304. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44305. })(BABYLON || (BABYLON = {}));
  44306. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44307. var BABYLON;
  44308. (function (BABYLON) {
  44309. var FileFaceOrientation = /** @class */ (function () {
  44310. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44311. this.name = name;
  44312. this.worldAxisForNormal = worldAxisForNormal;
  44313. this.worldAxisForFileX = worldAxisForFileX;
  44314. this.worldAxisForFileY = worldAxisForFileY;
  44315. }
  44316. return FileFaceOrientation;
  44317. }());
  44318. ;
  44319. /**
  44320. * Helper class dealing with the extraction of spherical polynomial dataArray
  44321. * from a cube map.
  44322. */
  44323. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44324. function CubeMapToSphericalPolynomialTools() {
  44325. }
  44326. /**
  44327. * Converts a texture to the according Spherical Polynomial data.
  44328. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44329. *
  44330. * @param texture The texture to extract the information from.
  44331. * @return The Spherical Polynomial data.
  44332. */
  44333. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44334. if (!texture.isCube) {
  44335. // Only supports cube Textures currently.
  44336. return null;
  44337. }
  44338. var size = texture.getSize().width;
  44339. var right = texture.readPixels(0);
  44340. var left = texture.readPixels(1);
  44341. var up;
  44342. var down;
  44343. if (texture.isRenderTarget) {
  44344. up = texture.readPixels(3);
  44345. down = texture.readPixels(2);
  44346. }
  44347. else {
  44348. up = texture.readPixels(2);
  44349. down = texture.readPixels(3);
  44350. }
  44351. var front = texture.readPixels(4);
  44352. var back = texture.readPixels(5);
  44353. var gammaSpace = texture.gammaSpace;
  44354. // Always read as RGBA.
  44355. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44356. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44357. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44358. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44359. }
  44360. var cubeInfo = {
  44361. size: size,
  44362. right: right,
  44363. left: left,
  44364. up: up,
  44365. down: down,
  44366. front: front,
  44367. back: back,
  44368. format: format,
  44369. type: type,
  44370. gammaSpace: gammaSpace,
  44371. };
  44372. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  44373. };
  44374. /**
  44375. * Converts a cubemap to the according Spherical Polynomial data.
  44376. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44377. *
  44378. * @param cubeInfo The Cube map to extract the information from.
  44379. * @return The Spherical Polynomial data.
  44380. */
  44381. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  44382. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  44383. var totalSolidAngle = 0.0;
  44384. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  44385. var du = 2.0 / cubeInfo.size;
  44386. var dv = du;
  44387. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  44388. var minUV = du * 0.5 - 1.0;
  44389. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44390. var fileFace = this.FileFaces[faceIndex];
  44391. var dataArray = cubeInfo[fileFace.name];
  44392. var v = minUV;
  44393. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  44394. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  44395. // Because SP is still linear, so summation is fine in that basis.
  44396. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  44397. for (var y = 0; y < cubeInfo.size; y++) {
  44398. var u = minUV;
  44399. for (var x = 0; x < cubeInfo.size; x++) {
  44400. // World direction (not normalised)
  44401. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  44402. worldDirection.normalize();
  44403. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  44404. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  44405. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  44406. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  44407. // Handle Integer types.
  44408. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44409. r /= 255;
  44410. g /= 255;
  44411. b /= 255;
  44412. }
  44413. // Handle Gamma space textures.
  44414. if (cubeInfo.gammaSpace) {
  44415. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  44416. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  44417. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  44418. }
  44419. var color = new BABYLON.Color3(r, g, b);
  44420. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  44421. totalSolidAngle += deltaSolidAngle;
  44422. u += du;
  44423. }
  44424. v += dv;
  44425. }
  44426. }
  44427. // Solid angle for entire sphere is 4*pi
  44428. var sphereSolidAngle = 4.0 * Math.PI;
  44429. // Adjust the solid angle to allow for how many faces we processed.
  44430. var facesProcessed = 6.0;
  44431. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  44432. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  44433. // This is needed because the numerical integration over the cube uses a
  44434. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  44435. // and also to compensate for accumulative error due to float precision in the summation.
  44436. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  44437. sphericalHarmonics.scale(correctionFactor);
  44438. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  44439. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  44440. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  44441. };
  44442. CubeMapToSphericalPolynomialTools.FileFaces = [
  44443. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  44444. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  44445. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  44446. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  44447. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  44448. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  44449. ];
  44450. return CubeMapToSphericalPolynomialTools;
  44451. }());
  44452. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  44453. })(BABYLON || (BABYLON = {}));
  44454. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  44455. var BABYLON;
  44456. (function (BABYLON) {
  44457. /**
  44458. * Manages the defines for the PBR Material.
  44459. * @hiddenChildren
  44460. */
  44461. var PBRMaterialDefines = /** @class */ (function (_super) {
  44462. __extends(PBRMaterialDefines, _super);
  44463. /**
  44464. * Initializes the PBR Material defines.
  44465. */
  44466. function PBRMaterialDefines() {
  44467. var _this = _super.call(this) || this;
  44468. _this.PBR = true;
  44469. _this.MAINUV1 = false;
  44470. _this.MAINUV2 = false;
  44471. _this.UV1 = false;
  44472. _this.UV2 = false;
  44473. _this.ALBEDO = false;
  44474. _this.ALBEDODIRECTUV = 0;
  44475. _this.VERTEXCOLOR = false;
  44476. _this.AMBIENT = false;
  44477. _this.AMBIENTDIRECTUV = 0;
  44478. _this.AMBIENTINGRAYSCALE = false;
  44479. _this.OPACITY = false;
  44480. _this.VERTEXALPHA = false;
  44481. _this.OPACITYDIRECTUV = 0;
  44482. _this.OPACITYRGB = false;
  44483. _this.ALPHATEST = false;
  44484. _this.DEPTHPREPASS = false;
  44485. _this.ALPHABLEND = false;
  44486. _this.ALPHAFROMALBEDO = false;
  44487. _this.ALPHATESTVALUE = "0.5";
  44488. _this.SPECULAROVERALPHA = false;
  44489. _this.RADIANCEOVERALPHA = false;
  44490. _this.ALPHAFRESNEL = false;
  44491. _this.LINEARALPHAFRESNEL = false;
  44492. _this.PREMULTIPLYALPHA = false;
  44493. _this.EMISSIVE = false;
  44494. _this.EMISSIVEDIRECTUV = 0;
  44495. _this.REFLECTIVITY = false;
  44496. _this.REFLECTIVITYDIRECTUV = 0;
  44497. _this.SPECULARTERM = false;
  44498. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44499. _this.MICROSURFACEAUTOMATIC = false;
  44500. _this.LODBASEDMICROSFURACE = false;
  44501. _this.MICROSURFACEMAP = false;
  44502. _this.MICROSURFACEMAPDIRECTUV = 0;
  44503. _this.METALLICWORKFLOW = false;
  44504. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44505. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44506. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44507. _this.AOSTOREINMETALMAPRED = false;
  44508. _this.ENVIRONMENTBRDF = false;
  44509. _this.NORMAL = false;
  44510. _this.TANGENT = false;
  44511. _this.BUMP = false;
  44512. _this.BUMPDIRECTUV = 0;
  44513. _this.OBJECTSPACE_NORMALMAP = false;
  44514. _this.PARALLAX = false;
  44515. _this.PARALLAXOCCLUSION = false;
  44516. _this.NORMALXYSCALE = true;
  44517. _this.LIGHTMAP = false;
  44518. _this.LIGHTMAPDIRECTUV = 0;
  44519. _this.USELIGHTMAPASSHADOWMAP = false;
  44520. _this.GAMMALIGHTMAP = false;
  44521. _this.REFLECTION = false;
  44522. _this.REFLECTIONMAP_3D = false;
  44523. _this.REFLECTIONMAP_SPHERICAL = false;
  44524. _this.REFLECTIONMAP_PLANAR = false;
  44525. _this.REFLECTIONMAP_CUBIC = false;
  44526. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44527. _this.REFLECTIONMAP_PROJECTION = false;
  44528. _this.REFLECTIONMAP_SKYBOX = false;
  44529. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44530. _this.REFLECTIONMAP_EXPLICIT = false;
  44531. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44532. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44533. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44534. _this.INVERTCUBICMAP = false;
  44535. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44536. _this.USESPHERICALINVERTEX = false;
  44537. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44538. _this.LODINREFLECTIONALPHA = false;
  44539. _this.GAMMAREFLECTION = false;
  44540. _this.RGBDREFLECTION = false;
  44541. _this.RADIANCEOCCLUSION = false;
  44542. _this.HORIZONOCCLUSION = false;
  44543. _this.REFRACTION = false;
  44544. _this.REFRACTIONMAP_3D = false;
  44545. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44546. _this.LODINREFRACTIONALPHA = false;
  44547. _this.GAMMAREFRACTION = false;
  44548. _this.RGBDREFRACTION = false;
  44549. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44550. _this.INSTANCES = false;
  44551. _this.NUM_BONE_INFLUENCERS = 0;
  44552. _this.BonesPerMesh = 0;
  44553. _this.NONUNIFORMSCALING = false;
  44554. _this.MORPHTARGETS = false;
  44555. _this.MORPHTARGETS_NORMAL = false;
  44556. _this.MORPHTARGETS_TANGENT = false;
  44557. _this.NUM_MORPH_INFLUENCERS = 0;
  44558. _this.IMAGEPROCESSING = false;
  44559. _this.VIGNETTE = false;
  44560. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44561. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44562. _this.TONEMAPPING = false;
  44563. _this.TONEMAPPING_ACES = false;
  44564. _this.CONTRAST = false;
  44565. _this.COLORCURVES = false;
  44566. _this.COLORGRADING = false;
  44567. _this.COLORGRADING3D = false;
  44568. _this.SAMPLER3DGREENDEPTH = false;
  44569. _this.SAMPLER3DBGRMAP = false;
  44570. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44571. _this.EXPOSURE = false;
  44572. _this.USEPHYSICALLIGHTFALLOFF = false;
  44573. _this.USEGLTFLIGHTFALLOFF = false;
  44574. _this.TWOSIDEDLIGHTING = false;
  44575. _this.SHADOWFLOAT = false;
  44576. _this.CLIPPLANE = false;
  44577. _this.CLIPPLANE2 = false;
  44578. _this.CLIPPLANE3 = false;
  44579. _this.CLIPPLANE4 = false;
  44580. _this.POINTSIZE = false;
  44581. _this.FOG = false;
  44582. _this.LOGARITHMICDEPTH = false;
  44583. _this.FORCENORMALFORWARD = false;
  44584. _this.SPECULARAA = false;
  44585. _this.UNLIT = false;
  44586. _this.rebuild();
  44587. return _this;
  44588. }
  44589. /**
  44590. * Resets the PBR Material defines.
  44591. */
  44592. PBRMaterialDefines.prototype.reset = function () {
  44593. _super.prototype.reset.call(this);
  44594. this.ALPHATESTVALUE = "0.5";
  44595. this.PBR = true;
  44596. };
  44597. return PBRMaterialDefines;
  44598. }(BABYLON.MaterialDefines));
  44599. /**
  44600. * The Physically based material base class of BJS.
  44601. *
  44602. * This offers the main features of a standard PBR material.
  44603. * For more information, please refer to the documentation :
  44604. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44605. */
  44606. var PBRBaseMaterial = /** @class */ (function (_super) {
  44607. __extends(PBRBaseMaterial, _super);
  44608. /**
  44609. * Instantiates a new PBRMaterial instance.
  44610. *
  44611. * @param name The material name
  44612. * @param scene The scene the material will be use in.
  44613. */
  44614. function PBRBaseMaterial(name, scene) {
  44615. var _this = _super.call(this, name, scene) || this;
  44616. /**
  44617. * Intensity of the direct lights e.g. the four lights available in your scene.
  44618. * This impacts both the direct diffuse and specular highlights.
  44619. */
  44620. _this._directIntensity = 1.0;
  44621. /**
  44622. * Intensity of the emissive part of the material.
  44623. * This helps controlling the emissive effect without modifying the emissive color.
  44624. */
  44625. _this._emissiveIntensity = 1.0;
  44626. /**
  44627. * Intensity of the environment e.g. how much the environment will light the object
  44628. * either through harmonics for rough material or through the refelction for shiny ones.
  44629. */
  44630. _this._environmentIntensity = 1.0;
  44631. /**
  44632. * This is a special control allowing the reduction of the specular highlights coming from the
  44633. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44634. */
  44635. _this._specularIntensity = 1.0;
  44636. /**
  44637. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44638. */
  44639. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44640. /**
  44641. * Debug Control allowing disabling the bump map on this material.
  44642. */
  44643. _this._disableBumpMap = false;
  44644. /**
  44645. * AKA Occlusion Texture Intensity in other nomenclature.
  44646. */
  44647. _this._ambientTextureStrength = 1.0;
  44648. /**
  44649. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44650. * 1 means it completely occludes it
  44651. * 0 mean it has no impact
  44652. */
  44653. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44654. /**
  44655. * The color of a material in ambient lighting.
  44656. */
  44657. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44658. /**
  44659. * AKA Diffuse Color in other nomenclature.
  44660. */
  44661. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44662. /**
  44663. * AKA Specular Color in other nomenclature.
  44664. */
  44665. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44666. /**
  44667. * The color applied when light is reflected from a material.
  44668. */
  44669. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44670. /**
  44671. * The color applied when light is emitted from a material.
  44672. */
  44673. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44674. /**
  44675. * AKA Glossiness in other nomenclature.
  44676. */
  44677. _this._microSurface = 0.9;
  44678. /**
  44679. * source material index of refraction (IOR)' / 'destination material IOR.
  44680. */
  44681. _this._indexOfRefraction = 0.66;
  44682. /**
  44683. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44684. */
  44685. _this._invertRefractionY = false;
  44686. /**
  44687. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44688. * Materials half opaque for instance using refraction could benefit from this control.
  44689. */
  44690. _this._linkRefractionWithTransparency = false;
  44691. /**
  44692. * Specifies that the material will use the light map as a show map.
  44693. */
  44694. _this._useLightmapAsShadowmap = false;
  44695. /**
  44696. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44697. * makes the reflect vector face the model (under horizon).
  44698. */
  44699. _this._useHorizonOcclusion = true;
  44700. /**
  44701. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44702. * too much the area relying on ambient texture to define their ambient occlusion.
  44703. */
  44704. _this._useRadianceOcclusion = true;
  44705. /**
  44706. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44707. */
  44708. _this._useAlphaFromAlbedoTexture = false;
  44709. /**
  44710. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44711. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44712. */
  44713. _this._useSpecularOverAlpha = true;
  44714. /**
  44715. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44716. */
  44717. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44718. /**
  44719. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44720. */
  44721. _this._useRoughnessFromMetallicTextureAlpha = true;
  44722. /**
  44723. * Specifies if the metallic texture contains the roughness information in its green channel.
  44724. */
  44725. _this._useRoughnessFromMetallicTextureGreen = false;
  44726. /**
  44727. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44728. */
  44729. _this._useMetallnessFromMetallicTextureBlue = false;
  44730. /**
  44731. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44732. */
  44733. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44734. /**
  44735. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44736. */
  44737. _this._useAmbientInGrayScale = false;
  44738. /**
  44739. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44740. * The material will try to infer what glossiness each pixel should be.
  44741. */
  44742. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44743. /**
  44744. * Defines the falloff type used in this material.
  44745. * It by default is Physical.
  44746. */
  44747. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44748. /**
  44749. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44750. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44751. */
  44752. _this._useRadianceOverAlpha = true;
  44753. /**
  44754. * Allows using an object space normal map (instead of tangent space).
  44755. */
  44756. _this._useObjectSpaceNormalMap = false;
  44757. /**
  44758. * Allows using the bump map in parallax mode.
  44759. */
  44760. _this._useParallax = false;
  44761. /**
  44762. * Allows using the bump map in parallax occlusion mode.
  44763. */
  44764. _this._useParallaxOcclusion = false;
  44765. /**
  44766. * Controls the scale bias of the parallax mode.
  44767. */
  44768. _this._parallaxScaleBias = 0.05;
  44769. /**
  44770. * If sets to true, disables all the lights affecting the material.
  44771. */
  44772. _this._disableLighting = false;
  44773. /**
  44774. * Number of Simultaneous lights allowed on the material.
  44775. */
  44776. _this._maxSimultaneousLights = 4;
  44777. /**
  44778. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44779. */
  44780. _this._invertNormalMapX = false;
  44781. /**
  44782. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44783. */
  44784. _this._invertNormalMapY = false;
  44785. /**
  44786. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44787. */
  44788. _this._twoSidedLighting = false;
  44789. /**
  44790. * Defines the alpha limits in alpha test mode.
  44791. */
  44792. _this._alphaCutOff = 0.4;
  44793. /**
  44794. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44795. */
  44796. _this._forceAlphaTest = false;
  44797. /**
  44798. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44799. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44800. */
  44801. _this._useAlphaFresnel = false;
  44802. /**
  44803. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44804. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44805. */
  44806. _this._useLinearAlphaFresnel = false;
  44807. /**
  44808. * The transparency mode of the material.
  44809. */
  44810. _this._transparencyMode = null;
  44811. /**
  44812. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44813. * from cos thetav and roughness:
  44814. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44815. */
  44816. _this._environmentBRDFTexture = null;
  44817. /**
  44818. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44819. */
  44820. _this._forceIrradianceInFragment = false;
  44821. /**
  44822. * Force normal to face away from face.
  44823. */
  44824. _this._forceNormalForward = false;
  44825. /**
  44826. * Enables specular anti aliasing in the PBR shader.
  44827. * It will both interacts on the Geometry for analytical and IBL lighting.
  44828. * It also prefilter the roughness map based on the bump values.
  44829. */
  44830. _this._enableSpecularAntiAliasing = false;
  44831. /**
  44832. * Stores the available render targets.
  44833. */
  44834. _this._renderTargets = new BABYLON.SmartArray(16);
  44835. /**
  44836. * Sets the global ambient color for the material used in lighting calculations.
  44837. */
  44838. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44839. /**
  44840. * If set to true, no lighting calculations will be applied.
  44841. */
  44842. _this._unlit = false;
  44843. // Setup the default processing configuration to the scene.
  44844. _this._attachImageProcessingConfiguration(null);
  44845. _this.getRenderTargetTextures = function () {
  44846. _this._renderTargets.reset();
  44847. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44848. _this._renderTargets.push(_this._reflectionTexture);
  44849. }
  44850. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44851. _this._renderTargets.push(_this._refractionTexture);
  44852. }
  44853. return _this._renderTargets;
  44854. };
  44855. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44856. return _this;
  44857. }
  44858. /**
  44859. * Attaches a new image processing configuration to the PBR Material.
  44860. * @param configuration
  44861. */
  44862. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44863. var _this = this;
  44864. if (configuration === this._imageProcessingConfiguration) {
  44865. return;
  44866. }
  44867. // Detaches observer.
  44868. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44869. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44870. }
  44871. // Pick the scene configuration if needed.
  44872. if (!configuration) {
  44873. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44874. }
  44875. else {
  44876. this._imageProcessingConfiguration = configuration;
  44877. }
  44878. // Attaches observer.
  44879. if (this._imageProcessingConfiguration) {
  44880. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44881. _this._markAllSubMeshesAsImageProcessingDirty();
  44882. });
  44883. }
  44884. };
  44885. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  44886. /**
  44887. * Gets a boolean indicating that current material needs to register RTT
  44888. */
  44889. get: function () {
  44890. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44891. return true;
  44892. }
  44893. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44894. return true;
  44895. }
  44896. return false;
  44897. },
  44898. enumerable: true,
  44899. configurable: true
  44900. });
  44901. /**
  44902. * Gets the name of the material class.
  44903. */
  44904. PBRBaseMaterial.prototype.getClassName = function () {
  44905. return "PBRBaseMaterial";
  44906. };
  44907. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44908. /**
  44909. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44910. */
  44911. get: function () {
  44912. return this._useLogarithmicDepth;
  44913. },
  44914. /**
  44915. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44916. */
  44917. set: function (value) {
  44918. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44919. },
  44920. enumerable: true,
  44921. configurable: true
  44922. });
  44923. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44924. /**
  44925. * Gets the current transparency mode.
  44926. */
  44927. get: function () {
  44928. return this._transparencyMode;
  44929. },
  44930. /**
  44931. * Sets the transparency mode of the material.
  44932. *
  44933. * | Value | Type | Description |
  44934. * | ----- | ----------------------------------- | ----------- |
  44935. * | 0 | OPAQUE | |
  44936. * | 1 | ALPHATEST | |
  44937. * | 2 | ALPHABLEND | |
  44938. * | 3 | ALPHATESTANDBLEND | |
  44939. *
  44940. */
  44941. set: function (value) {
  44942. if (this._transparencyMode === value) {
  44943. return;
  44944. }
  44945. this._transparencyMode = value;
  44946. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44947. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44948. },
  44949. enumerable: true,
  44950. configurable: true
  44951. });
  44952. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44953. /**
  44954. * Returns true if alpha blending should be disabled.
  44955. */
  44956. get: function () {
  44957. return (this._linkRefractionWithTransparency ||
  44958. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44959. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44960. },
  44961. enumerable: true,
  44962. configurable: true
  44963. });
  44964. /**
  44965. * Specifies whether or not this material should be rendered in alpha blend mode.
  44966. */
  44967. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44968. if (this._disableAlphaBlending) {
  44969. return false;
  44970. }
  44971. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44972. };
  44973. /**
  44974. * Specifies if the mesh will require alpha blending.
  44975. * @param mesh - BJS mesh.
  44976. */
  44977. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44978. if (this._disableAlphaBlending) {
  44979. return false;
  44980. }
  44981. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44982. };
  44983. /**
  44984. * Specifies whether or not this material should be rendered in alpha test mode.
  44985. */
  44986. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44987. if (this._forceAlphaTest) {
  44988. return true;
  44989. }
  44990. if (this._linkRefractionWithTransparency) {
  44991. return false;
  44992. }
  44993. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44994. };
  44995. /**
  44996. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44997. */
  44998. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44999. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45000. };
  45001. /**
  45002. * Gets the texture used for the alpha test.
  45003. */
  45004. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45005. return this._albedoTexture;
  45006. };
  45007. /**
  45008. * Specifies that the submesh is ready to be used.
  45009. * @param mesh - BJS mesh.
  45010. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45011. * @param useInstances - Specifies that instances should be used.
  45012. * @returns - boolean indicating that the submesh is ready or not.
  45013. */
  45014. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45015. if (subMesh.effect && this.isFrozen) {
  45016. if (this._wasPreviouslyReady) {
  45017. return true;
  45018. }
  45019. }
  45020. if (!subMesh._materialDefines) {
  45021. subMesh._materialDefines = new PBRMaterialDefines();
  45022. }
  45023. var defines = subMesh._materialDefines;
  45024. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45025. if (defines._renderId === this.getScene().getRenderId()) {
  45026. return true;
  45027. }
  45028. }
  45029. var scene = this.getScene();
  45030. var engine = scene.getEngine();
  45031. if (defines._areTexturesDirty) {
  45032. if (scene.texturesEnabled) {
  45033. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45034. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45035. return false;
  45036. }
  45037. }
  45038. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45039. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45040. return false;
  45041. }
  45042. }
  45043. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45044. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45045. return false;
  45046. }
  45047. }
  45048. var reflectionTexture = this._getReflectionTexture();
  45049. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45050. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45051. return false;
  45052. }
  45053. }
  45054. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45055. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45056. return false;
  45057. }
  45058. }
  45059. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45060. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45061. return false;
  45062. }
  45063. }
  45064. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45065. if (this._metallicTexture) {
  45066. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45067. return false;
  45068. }
  45069. }
  45070. else if (this._reflectivityTexture) {
  45071. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45072. return false;
  45073. }
  45074. }
  45075. if (this._microSurfaceTexture) {
  45076. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45077. return false;
  45078. }
  45079. }
  45080. }
  45081. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45082. // Bump texture cannot be not blocking.
  45083. if (!this._bumpTexture.isReady()) {
  45084. return false;
  45085. }
  45086. }
  45087. var refractionTexture = this._getRefractionTexture();
  45088. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45089. if (!refractionTexture.isReadyOrNotBlocking()) {
  45090. return false;
  45091. }
  45092. }
  45093. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45094. // This is blocking.
  45095. if (!this._environmentBRDFTexture.isReady()) {
  45096. return false;
  45097. }
  45098. }
  45099. }
  45100. }
  45101. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45102. if (!this._imageProcessingConfiguration.isReady()) {
  45103. return false;
  45104. }
  45105. }
  45106. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45107. mesh.createNormals(true);
  45108. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45109. }
  45110. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45111. if (effect) {
  45112. scene.resetCachedMaterial();
  45113. subMesh.setEffect(effect, defines);
  45114. this.buildUniformLayout();
  45115. }
  45116. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45117. return false;
  45118. }
  45119. defines._renderId = scene.getRenderId();
  45120. this._wasPreviouslyReady = true;
  45121. return true;
  45122. };
  45123. /**
  45124. * Specifies if the material uses metallic roughness workflow.
  45125. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45126. */
  45127. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45128. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45129. return true;
  45130. }
  45131. return false;
  45132. };
  45133. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45134. if (onCompiled === void 0) { onCompiled = null; }
  45135. if (onError === void 0) { onError = null; }
  45136. if (useInstances === void 0) { useInstances = null; }
  45137. if (useClipPlane === void 0) { useClipPlane = null; }
  45138. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45139. if (!defines.isDirty) {
  45140. return null;
  45141. }
  45142. defines.markAsProcessed();
  45143. var scene = this.getScene();
  45144. var engine = scene.getEngine();
  45145. // Fallbacks
  45146. var fallbacks = new BABYLON.EffectFallbacks();
  45147. var fallbackRank = 0;
  45148. if (defines.USESPHERICALINVERTEX) {
  45149. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45150. }
  45151. if (defines.FOG) {
  45152. fallbacks.addFallback(fallbackRank, "FOG");
  45153. }
  45154. if (defines.SPECULARAA) {
  45155. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45156. }
  45157. if (defines.POINTSIZE) {
  45158. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45159. }
  45160. if (defines.LOGARITHMICDEPTH) {
  45161. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45162. }
  45163. if (defines.PARALLAX) {
  45164. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45165. }
  45166. if (defines.PARALLAXOCCLUSION) {
  45167. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45168. }
  45169. if (defines.ENVIRONMENTBRDF) {
  45170. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45171. }
  45172. if (defines.TANGENT) {
  45173. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45174. }
  45175. if (defines.BUMP) {
  45176. fallbacks.addFallback(fallbackRank++, "BUMP");
  45177. }
  45178. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45179. if (defines.SPECULARTERM) {
  45180. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45181. }
  45182. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45183. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45184. }
  45185. if (defines.LIGHTMAP) {
  45186. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45187. }
  45188. if (defines.NORMAL) {
  45189. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45190. }
  45191. if (defines.AMBIENT) {
  45192. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45193. }
  45194. if (defines.EMISSIVE) {
  45195. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45196. }
  45197. if (defines.VERTEXCOLOR) {
  45198. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45199. }
  45200. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45201. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45202. }
  45203. if (defines.MORPHTARGETS) {
  45204. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45205. }
  45206. //Attributes
  45207. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45208. if (defines.NORMAL) {
  45209. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45210. }
  45211. if (defines.TANGENT) {
  45212. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45213. }
  45214. if (defines.UV1) {
  45215. attribs.push(BABYLON.VertexBuffer.UVKind);
  45216. }
  45217. if (defines.UV2) {
  45218. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45219. }
  45220. if (defines.VERTEXCOLOR) {
  45221. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45222. }
  45223. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45224. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45225. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45226. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45227. "vFogInfos", "vFogColor", "pointSize",
  45228. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45229. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45230. "mBones",
  45231. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45232. "vLightingIntensity",
  45233. "logarithmicDepthConstant",
  45234. "vSphericalX", "vSphericalY", "vSphericalZ",
  45235. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45236. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45237. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45238. "vTangentSpaceParams"
  45239. ];
  45240. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45241. "bumpSampler", "lightmapSampler", "opacitySampler",
  45242. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45243. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45244. "microSurfaceSampler", "environmentBrdfSampler"];
  45245. var uniformBuffers = ["Material", "Scene"];
  45246. if (BABYLON.ImageProcessingConfiguration) {
  45247. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45248. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45249. }
  45250. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45251. uniformsNames: uniforms,
  45252. uniformBuffersNames: uniformBuffers,
  45253. samplers: samplers,
  45254. defines: defines,
  45255. maxSimultaneousLights: this._maxSimultaneousLights
  45256. });
  45257. var join = defines.toString();
  45258. return engine.createEffect("pbr", {
  45259. attributes: attribs,
  45260. uniformsNames: uniforms,
  45261. uniformBuffersNames: uniformBuffers,
  45262. samplers: samplers,
  45263. defines: join,
  45264. fallbacks: fallbacks,
  45265. onCompiled: onCompiled,
  45266. onError: onError,
  45267. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45268. }, engine);
  45269. };
  45270. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45271. if (useInstances === void 0) { useInstances = null; }
  45272. if (useClipPlane === void 0) { useClipPlane = null; }
  45273. var scene = this.getScene();
  45274. var engine = scene.getEngine();
  45275. // Lights
  45276. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45277. defines._needNormals = true;
  45278. // Textures
  45279. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45280. if (defines._areTexturesDirty) {
  45281. defines._needUVs = false;
  45282. if (scene.texturesEnabled) {
  45283. if (scene.getEngine().getCaps().textureLOD) {
  45284. defines.LODBASEDMICROSFURACE = true;
  45285. }
  45286. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45287. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45288. }
  45289. else {
  45290. defines.ALBEDO = false;
  45291. }
  45292. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45293. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45294. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45295. }
  45296. else {
  45297. defines.AMBIENT = false;
  45298. }
  45299. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45300. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45301. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45302. }
  45303. else {
  45304. defines.OPACITY = false;
  45305. }
  45306. var reflectionTexture = this._getReflectionTexture();
  45307. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45308. defines.REFLECTION = true;
  45309. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45310. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45311. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45312. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45313. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45314. defines.INVERTCUBICMAP = true;
  45315. }
  45316. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45317. switch (reflectionTexture.coordinatesMode) {
  45318. case BABYLON.Texture.EXPLICIT_MODE:
  45319. defines.REFLECTIONMAP_EXPLICIT = true;
  45320. break;
  45321. case BABYLON.Texture.PLANAR_MODE:
  45322. defines.REFLECTIONMAP_PLANAR = true;
  45323. break;
  45324. case BABYLON.Texture.PROJECTION_MODE:
  45325. defines.REFLECTIONMAP_PROJECTION = true;
  45326. break;
  45327. case BABYLON.Texture.SKYBOX_MODE:
  45328. defines.REFLECTIONMAP_SKYBOX = true;
  45329. break;
  45330. case BABYLON.Texture.SPHERICAL_MODE:
  45331. defines.REFLECTIONMAP_SPHERICAL = true;
  45332. break;
  45333. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45334. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45335. break;
  45336. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45337. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45338. break;
  45339. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45340. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45341. break;
  45342. case BABYLON.Texture.CUBIC_MODE:
  45343. case BABYLON.Texture.INVCUBIC_MODE:
  45344. default:
  45345. defines.REFLECTIONMAP_CUBIC = true;
  45346. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45347. break;
  45348. }
  45349. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45350. if (reflectionTexture.sphericalPolynomial) {
  45351. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45352. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45353. defines.USESPHERICALINVERTEX = false;
  45354. }
  45355. else {
  45356. defines.USESPHERICALINVERTEX = true;
  45357. }
  45358. }
  45359. }
  45360. else {
  45361. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45362. }
  45363. }
  45364. else {
  45365. defines.REFLECTION = false;
  45366. defines.REFLECTIONMAP_3D = false;
  45367. defines.REFLECTIONMAP_SPHERICAL = false;
  45368. defines.REFLECTIONMAP_PLANAR = false;
  45369. defines.REFLECTIONMAP_CUBIC = false;
  45370. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45371. defines.REFLECTIONMAP_PROJECTION = false;
  45372. defines.REFLECTIONMAP_SKYBOX = false;
  45373. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45374. defines.REFLECTIONMAP_EXPLICIT = false;
  45375. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45376. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45377. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45378. defines.INVERTCUBICMAP = false;
  45379. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45380. defines.USESPHERICALINVERTEX = false;
  45381. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45382. defines.LODINREFLECTIONALPHA = false;
  45383. defines.GAMMAREFLECTION = false;
  45384. defines.RGBDREFLECTION = false;
  45385. }
  45386. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45387. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45388. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45389. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45390. }
  45391. else {
  45392. defines.LIGHTMAP = false;
  45393. }
  45394. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45395. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45396. }
  45397. else {
  45398. defines.EMISSIVE = false;
  45399. }
  45400. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45401. if (this._metallicTexture) {
  45402. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45403. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45404. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45405. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45406. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45407. }
  45408. else if (this._reflectivityTexture) {
  45409. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45410. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45411. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45412. }
  45413. else {
  45414. defines.REFLECTIVITY = false;
  45415. }
  45416. if (this._microSurfaceTexture) {
  45417. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45418. }
  45419. else {
  45420. defines.MICROSURFACEMAP = false;
  45421. }
  45422. }
  45423. else {
  45424. defines.REFLECTIVITY = false;
  45425. defines.MICROSURFACEMAP = false;
  45426. }
  45427. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45428. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45429. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45430. defines.PARALLAX = true;
  45431. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45432. }
  45433. else {
  45434. defines.PARALLAX = false;
  45435. }
  45436. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45437. }
  45438. else {
  45439. defines.BUMP = false;
  45440. }
  45441. var refractionTexture = this._getRefractionTexture();
  45442. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45443. defines.REFRACTION = true;
  45444. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45445. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45446. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45447. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45448. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45449. if (this._linkRefractionWithTransparency) {
  45450. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45451. }
  45452. }
  45453. else {
  45454. defines.REFRACTION = false;
  45455. }
  45456. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45457. defines.ENVIRONMENTBRDF = true;
  45458. }
  45459. else {
  45460. defines.ENVIRONMENTBRDF = false;
  45461. }
  45462. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45463. defines.ALPHAFROMALBEDO = true;
  45464. }
  45465. else {
  45466. defines.ALPHAFROMALBEDO = false;
  45467. }
  45468. }
  45469. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45470. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  45471. defines.USEPHYSICALLIGHTFALLOFF = false;
  45472. defines.USEGLTFLIGHTFALLOFF = false;
  45473. }
  45474. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  45475. defines.USEPHYSICALLIGHTFALLOFF = false;
  45476. defines.USEGLTFLIGHTFALLOFF = true;
  45477. }
  45478. else {
  45479. defines.USEPHYSICALLIGHTFALLOFF = true;
  45480. defines.USEGLTFLIGHTFALLOFF = false;
  45481. }
  45482. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45483. if (!this.backFaceCulling && this._twoSidedLighting) {
  45484. defines.TWOSIDEDLIGHTING = true;
  45485. }
  45486. else {
  45487. defines.TWOSIDEDLIGHTING = false;
  45488. }
  45489. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45490. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45491. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45492. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45493. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45494. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45495. }
  45496. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45497. this._imageProcessingConfiguration.prepareDefines(defines);
  45498. }
  45499. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45500. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45501. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45502. // Misc.
  45503. if (defines._areMiscDirty) {
  45504. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45505. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45506. }
  45507. // Values that need to be evaluated on every frame
  45508. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45509. // Attribs
  45510. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45511. };
  45512. /**
  45513. * Force shader compilation
  45514. */
  45515. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45516. var _this = this;
  45517. var localOptions = __assign({ clipPlane: false }, options);
  45518. var defines = new PBRMaterialDefines();
  45519. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45520. if (effect.isReady()) {
  45521. if (onCompiled) {
  45522. onCompiled(this);
  45523. }
  45524. }
  45525. else {
  45526. effect.onCompileObservable.add(function () {
  45527. if (onCompiled) {
  45528. onCompiled(_this);
  45529. }
  45530. });
  45531. }
  45532. };
  45533. /**
  45534. * Initializes the uniform buffer layout for the shader.
  45535. */
  45536. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45537. // Order is important !
  45538. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45539. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  45540. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45541. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45542. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45543. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45544. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45545. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45546. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45547. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45548. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45549. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45550. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45551. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45552. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45553. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45554. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45555. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45556. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45557. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45558. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45559. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45560. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45561. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45562. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45563. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45564. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45565. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45566. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45567. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45568. this._uniformBuffer.addUniform("pointSize", 1);
  45569. this._uniformBuffer.create();
  45570. };
  45571. /**
  45572. * Unbinds the textures.
  45573. */
  45574. PBRBaseMaterial.prototype.unbind = function () {
  45575. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45576. this._uniformBuffer.setTexture("reflectionSampler", null);
  45577. }
  45578. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45579. this._uniformBuffer.setTexture("refractionSampler", null);
  45580. }
  45581. _super.prototype.unbind.call(this);
  45582. };
  45583. /**
  45584. * Binds the submesh data.
  45585. * @param world - The world matrix.
  45586. * @param mesh - The BJS mesh.
  45587. * @param subMesh - A submesh of the BJS mesh.
  45588. */
  45589. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45590. var scene = this.getScene();
  45591. var defines = subMesh._materialDefines;
  45592. if (!defines) {
  45593. return;
  45594. }
  45595. var effect = subMesh.effect;
  45596. if (!effect) {
  45597. return;
  45598. }
  45599. this._activeEffect = effect;
  45600. // Matrices
  45601. this.bindOnlyWorldMatrix(world);
  45602. // Normal Matrix
  45603. if (defines.OBJECTSPACE_NORMALMAP) {
  45604. world.toNormalMatrix(this._normalMatrix);
  45605. this.bindOnlyNormalMatrix(this._normalMatrix);
  45606. }
  45607. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45608. // Bones
  45609. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45610. var reflectionTexture = null;
  45611. if (mustRebind) {
  45612. this._uniformBuffer.bindToEffect(effect, "Material");
  45613. this.bindViewProjection(effect);
  45614. reflectionTexture = this._getReflectionTexture();
  45615. var refractionTexture = this._getRefractionTexture();
  45616. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45617. // Texture uniforms
  45618. if (scene.texturesEnabled) {
  45619. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45620. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45621. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45622. }
  45623. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45624. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  45625. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45626. }
  45627. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45628. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45629. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45630. }
  45631. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45632. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45633. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45634. if (reflectionTexture.boundingBoxSize) {
  45635. var cubeTexture = reflectionTexture;
  45636. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45637. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45638. }
  45639. var polynomials = reflectionTexture.sphericalPolynomial;
  45640. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45641. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45642. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45643. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45644. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45645. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45646. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45647. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45648. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45649. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45650. }
  45651. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45652. }
  45653. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45654. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45655. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45656. }
  45657. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45658. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45659. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45660. }
  45661. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45662. if (this._metallicTexture) {
  45663. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45664. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45665. }
  45666. else if (this._reflectivityTexture) {
  45667. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45668. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45669. }
  45670. if (this._microSurfaceTexture) {
  45671. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45672. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45673. }
  45674. }
  45675. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45676. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45677. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45678. if (scene._mirroredCameraPosition) {
  45679. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45680. }
  45681. else {
  45682. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45683. }
  45684. }
  45685. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45686. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45687. var depth = 1.0;
  45688. if (!refractionTexture.isCube) {
  45689. if (refractionTexture.depth) {
  45690. depth = refractionTexture.depth;
  45691. }
  45692. }
  45693. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45694. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45695. }
  45696. }
  45697. // Point size
  45698. if (this.pointsCloud) {
  45699. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45700. }
  45701. // Colors
  45702. if (defines.METALLICWORKFLOW) {
  45703. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45704. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45705. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45706. }
  45707. else {
  45708. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45709. }
  45710. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45711. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45712. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45713. // Misc
  45714. this._lightingInfos.x = this._directIntensity;
  45715. this._lightingInfos.y = this._emissiveIntensity;
  45716. this._lightingInfos.z = this._environmentIntensity;
  45717. this._lightingInfos.w = this._specularIntensity;
  45718. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45719. }
  45720. // Textures
  45721. if (scene.texturesEnabled) {
  45722. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45723. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45724. }
  45725. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45726. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45727. }
  45728. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45729. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45730. }
  45731. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45732. if (defines.LODBASEDMICROSFURACE) {
  45733. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45734. }
  45735. else {
  45736. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45737. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45738. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45739. }
  45740. }
  45741. if (defines.ENVIRONMENTBRDF) {
  45742. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45743. }
  45744. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45745. if (defines.LODBASEDMICROSFURACE) {
  45746. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45747. }
  45748. else {
  45749. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45750. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45751. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45752. }
  45753. }
  45754. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45755. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45756. }
  45757. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45758. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45759. }
  45760. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45761. if (this._metallicTexture) {
  45762. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45763. }
  45764. else if (this._reflectivityTexture) {
  45765. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45766. }
  45767. if (this._microSurfaceTexture) {
  45768. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45769. }
  45770. }
  45771. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45772. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45773. }
  45774. }
  45775. // Clip plane
  45776. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45777. // Colors
  45778. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45779. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45780. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45781. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45782. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45783. }
  45784. if (mustRebind || !this.isFrozen) {
  45785. // Lights
  45786. if (scene.lightsEnabled && !this._disableLighting) {
  45787. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  45788. }
  45789. // View
  45790. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45791. this.bindView(effect);
  45792. }
  45793. // Fog
  45794. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  45795. // Morph targets
  45796. if (defines.NUM_MORPH_INFLUENCERS) {
  45797. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45798. }
  45799. // image processing
  45800. this._imageProcessingConfiguration.bind(this._activeEffect);
  45801. // Log. depth
  45802. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45803. }
  45804. this._uniformBuffer.update();
  45805. this._afterBind(mesh, this._activeEffect);
  45806. };
  45807. /**
  45808. * Returns the animatable textures.
  45809. * @returns - Array of animatable textures.
  45810. */
  45811. PBRBaseMaterial.prototype.getAnimatables = function () {
  45812. var results = [];
  45813. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45814. results.push(this._albedoTexture);
  45815. }
  45816. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45817. results.push(this._ambientTexture);
  45818. }
  45819. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45820. results.push(this._opacityTexture);
  45821. }
  45822. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45823. results.push(this._reflectionTexture);
  45824. }
  45825. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45826. results.push(this._emissiveTexture);
  45827. }
  45828. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45829. results.push(this._metallicTexture);
  45830. }
  45831. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45832. results.push(this._reflectivityTexture);
  45833. }
  45834. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45835. results.push(this._bumpTexture);
  45836. }
  45837. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45838. results.push(this._lightmapTexture);
  45839. }
  45840. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45841. results.push(this._refractionTexture);
  45842. }
  45843. return results;
  45844. };
  45845. /**
  45846. * Returns the texture used for reflections.
  45847. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45848. */
  45849. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45850. if (this._reflectionTexture) {
  45851. return this._reflectionTexture;
  45852. }
  45853. return this.getScene().environmentTexture;
  45854. };
  45855. /**
  45856. * Returns the texture used for refraction or null if none is used.
  45857. * @returns - Refection texture if present. If no refraction texture and refraction
  45858. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45859. */
  45860. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45861. if (this._refractionTexture) {
  45862. return this._refractionTexture;
  45863. }
  45864. if (this._linkRefractionWithTransparency) {
  45865. return this.getScene().environmentTexture;
  45866. }
  45867. return null;
  45868. };
  45869. /**
  45870. * Disposes the resources of the material.
  45871. * @param forceDisposeEffect - Forces the disposal of effects.
  45872. * @param forceDisposeTextures - Forces the disposal of all textures.
  45873. */
  45874. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45875. if (forceDisposeTextures) {
  45876. if (this._albedoTexture) {
  45877. this._albedoTexture.dispose();
  45878. }
  45879. if (this._ambientTexture) {
  45880. this._ambientTexture.dispose();
  45881. }
  45882. if (this._opacityTexture) {
  45883. this._opacityTexture.dispose();
  45884. }
  45885. if (this._reflectionTexture) {
  45886. this._reflectionTexture.dispose();
  45887. }
  45888. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45889. this._environmentBRDFTexture.dispose();
  45890. }
  45891. if (this._emissiveTexture) {
  45892. this._emissiveTexture.dispose();
  45893. }
  45894. if (this._metallicTexture) {
  45895. this._metallicTexture.dispose();
  45896. }
  45897. if (this._reflectivityTexture) {
  45898. this._reflectivityTexture.dispose();
  45899. }
  45900. if (this._bumpTexture) {
  45901. this._bumpTexture.dispose();
  45902. }
  45903. if (this._lightmapTexture) {
  45904. this._lightmapTexture.dispose();
  45905. }
  45906. if (this._refractionTexture) {
  45907. this._refractionTexture.dispose();
  45908. }
  45909. }
  45910. this._renderTargets.dispose();
  45911. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45912. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45913. }
  45914. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45915. };
  45916. /**
  45917. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45918. */
  45919. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45920. /**
  45921. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45922. * to enhance interoperability with other engines.
  45923. */
  45924. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45925. /**
  45926. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45927. * to enhance interoperability with other materials.
  45928. */
  45929. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45930. /**
  45931. * Stores the reflectivity values based on metallic roughness workflow.
  45932. */
  45933. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45934. __decorate([
  45935. BABYLON.serializeAsImageProcessingConfiguration()
  45936. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45937. __decorate([
  45938. BABYLON.serialize()
  45939. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45940. __decorate([
  45941. BABYLON.serialize()
  45942. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45943. return PBRBaseMaterial;
  45944. }(BABYLON.PushMaterial));
  45945. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45946. })(BABYLON || (BABYLON = {}));
  45947. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45948. var BABYLON;
  45949. (function (BABYLON) {
  45950. /**
  45951. * The Physically based simple base material of BJS.
  45952. *
  45953. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45954. * It is used as the base class for both the specGloss and metalRough conventions.
  45955. */
  45956. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45957. __extends(PBRBaseSimpleMaterial, _super);
  45958. /**
  45959. * Instantiates a new PBRMaterial instance.
  45960. *
  45961. * @param name The material name
  45962. * @param scene The scene the material will be use in.
  45963. */
  45964. function PBRBaseSimpleMaterial(name, scene) {
  45965. var _this = _super.call(this, name, scene) || this;
  45966. /**
  45967. * Number of Simultaneous lights allowed on the material.
  45968. */
  45969. _this.maxSimultaneousLights = 4;
  45970. /**
  45971. * If sets to true, disables all the lights affecting the material.
  45972. */
  45973. _this.disableLighting = false;
  45974. /**
  45975. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45976. */
  45977. _this.invertNormalMapX = false;
  45978. /**
  45979. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45980. */
  45981. _this.invertNormalMapY = false;
  45982. /**
  45983. * Emissivie color used to self-illuminate the model.
  45984. */
  45985. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45986. /**
  45987. * Occlusion Channel Strenght.
  45988. */
  45989. _this.occlusionStrength = 1.0;
  45990. /**
  45991. * If true, the light map contains occlusion information instead of lighting info.
  45992. */
  45993. _this.useLightmapAsShadowmap = false;
  45994. _this._useAlphaFromAlbedoTexture = true;
  45995. _this._useAmbientInGrayScale = true;
  45996. return _this;
  45997. }
  45998. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45999. /**
  46000. * Gets the current double sided mode.
  46001. */
  46002. get: function () {
  46003. return this._twoSidedLighting;
  46004. },
  46005. /**
  46006. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46007. */
  46008. set: function (value) {
  46009. if (this._twoSidedLighting === value) {
  46010. return;
  46011. }
  46012. this._twoSidedLighting = value;
  46013. this.backFaceCulling = !value;
  46014. this._markAllSubMeshesAsTexturesDirty();
  46015. },
  46016. enumerable: true,
  46017. configurable: true
  46018. });
  46019. /**
  46020. * Return the active textures of the material.
  46021. */
  46022. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46023. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46024. if (this.environmentTexture) {
  46025. activeTextures.push(this.environmentTexture);
  46026. }
  46027. if (this.normalTexture) {
  46028. activeTextures.push(this.normalTexture);
  46029. }
  46030. if (this.emissiveTexture) {
  46031. activeTextures.push(this.emissiveTexture);
  46032. }
  46033. if (this.occlusionTexture) {
  46034. activeTextures.push(this.occlusionTexture);
  46035. }
  46036. if (this.lightmapTexture) {
  46037. activeTextures.push(this.lightmapTexture);
  46038. }
  46039. return activeTextures;
  46040. };
  46041. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46042. if (_super.prototype.hasTexture.call(this, texture)) {
  46043. return true;
  46044. }
  46045. if (this.lightmapTexture === texture) {
  46046. return true;
  46047. }
  46048. return false;
  46049. };
  46050. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46051. return "PBRBaseSimpleMaterial";
  46052. };
  46053. __decorate([
  46054. BABYLON.serialize(),
  46055. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46056. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46057. __decorate([
  46058. BABYLON.serialize(),
  46059. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46060. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46061. __decorate([
  46062. BABYLON.serializeAsTexture(),
  46063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46064. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46065. __decorate([
  46066. BABYLON.serialize(),
  46067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46068. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46069. __decorate([
  46070. BABYLON.serialize(),
  46071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46072. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46073. __decorate([
  46074. BABYLON.serializeAsTexture(),
  46075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46076. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46077. __decorate([
  46078. BABYLON.serializeAsColor3("emissive"),
  46079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46080. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46081. __decorate([
  46082. BABYLON.serializeAsTexture(),
  46083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46084. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46085. __decorate([
  46086. BABYLON.serialize(),
  46087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46088. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46089. __decorate([
  46090. BABYLON.serializeAsTexture(),
  46091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46092. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46093. __decorate([
  46094. BABYLON.serialize(),
  46095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46096. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46097. __decorate([
  46098. BABYLON.serialize()
  46099. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46100. __decorate([
  46101. BABYLON.serializeAsTexture(),
  46102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46103. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46104. __decorate([
  46105. BABYLON.serialize(),
  46106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46107. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46108. return PBRBaseSimpleMaterial;
  46109. }(BABYLON.PBRBaseMaterial));
  46110. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46111. })(BABYLON || (BABYLON = {}));
  46112. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46113. var BABYLON;
  46114. (function (BABYLON) {
  46115. /**
  46116. * The Physically based material of BJS.
  46117. *
  46118. * This offers the main features of a standard PBR material.
  46119. * For more information, please refer to the documentation :
  46120. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46121. */
  46122. var PBRMaterial = /** @class */ (function (_super) {
  46123. __extends(PBRMaterial, _super);
  46124. /**
  46125. * Instantiates a new PBRMaterial instance.
  46126. *
  46127. * @param name The material name
  46128. * @param scene The scene the material will be use in.
  46129. */
  46130. function PBRMaterial(name, scene) {
  46131. var _this = _super.call(this, name, scene) || this;
  46132. /**
  46133. * Intensity of the direct lights e.g. the four lights available in your scene.
  46134. * This impacts both the direct diffuse and specular highlights.
  46135. */
  46136. _this.directIntensity = 1.0;
  46137. /**
  46138. * Intensity of the emissive part of the material.
  46139. * This helps controlling the emissive effect without modifying the emissive color.
  46140. */
  46141. _this.emissiveIntensity = 1.0;
  46142. /**
  46143. * Intensity of the environment e.g. how much the environment will light the object
  46144. * either through harmonics for rough material or through the refelction for shiny ones.
  46145. */
  46146. _this.environmentIntensity = 1.0;
  46147. /**
  46148. * This is a special control allowing the reduction of the specular highlights coming from the
  46149. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46150. */
  46151. _this.specularIntensity = 1.0;
  46152. /**
  46153. * Debug Control allowing disabling the bump map on this material.
  46154. */
  46155. _this.disableBumpMap = false;
  46156. /**
  46157. * AKA Occlusion Texture Intensity in other nomenclature.
  46158. */
  46159. _this.ambientTextureStrength = 1.0;
  46160. /**
  46161. * Defines how much the AO map is occluding the analytical lights (point spot...).
  46162. * 1 means it completely occludes it
  46163. * 0 mean it has no impact
  46164. */
  46165. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  46166. /**
  46167. * The color of a material in ambient lighting.
  46168. */
  46169. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46170. /**
  46171. * AKA Diffuse Color in other nomenclature.
  46172. */
  46173. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46174. /**
  46175. * AKA Specular Color in other nomenclature.
  46176. */
  46177. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46178. /**
  46179. * The color reflected from the material.
  46180. */
  46181. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46182. /**
  46183. * The color emitted from the material.
  46184. */
  46185. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46186. /**
  46187. * AKA Glossiness in other nomenclature.
  46188. */
  46189. _this.microSurface = 1.0;
  46190. /**
  46191. * source material index of refraction (IOR)' / 'destination material IOR.
  46192. */
  46193. _this.indexOfRefraction = 0.66;
  46194. /**
  46195. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46196. */
  46197. _this.invertRefractionY = false;
  46198. /**
  46199. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46200. * Materials half opaque for instance using refraction could benefit from this control.
  46201. */
  46202. _this.linkRefractionWithTransparency = false;
  46203. /**
  46204. * If true, the light map contains occlusion information instead of lighting info.
  46205. */
  46206. _this.useLightmapAsShadowmap = false;
  46207. /**
  46208. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46209. */
  46210. _this.useAlphaFromAlbedoTexture = false;
  46211. /**
  46212. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46213. */
  46214. _this.forceAlphaTest = false;
  46215. /**
  46216. * Defines the alpha limits in alpha test mode.
  46217. */
  46218. _this.alphaCutOff = 0.4;
  46219. /**
  46220. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46221. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46222. */
  46223. _this.useSpecularOverAlpha = true;
  46224. /**
  46225. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46226. */
  46227. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46228. /**
  46229. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46230. */
  46231. _this.useRoughnessFromMetallicTextureAlpha = true;
  46232. /**
  46233. * Specifies if the metallic texture contains the roughness information in its green channel.
  46234. */
  46235. _this.useRoughnessFromMetallicTextureGreen = false;
  46236. /**
  46237. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46238. */
  46239. _this.useMetallnessFromMetallicTextureBlue = false;
  46240. /**
  46241. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46242. */
  46243. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46244. /**
  46245. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46246. */
  46247. _this.useAmbientInGrayScale = false;
  46248. /**
  46249. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46250. * The material will try to infer what glossiness each pixel should be.
  46251. */
  46252. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46253. /**
  46254. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46255. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46256. */
  46257. _this.useRadianceOverAlpha = true;
  46258. /**
  46259. * Allows using an object space normal map (instead of tangent space).
  46260. */
  46261. _this.useObjectSpaceNormalMap = false;
  46262. /**
  46263. * Allows using the bump map in parallax mode.
  46264. */
  46265. _this.useParallax = false;
  46266. /**
  46267. * Allows using the bump map in parallax occlusion mode.
  46268. */
  46269. _this.useParallaxOcclusion = false;
  46270. /**
  46271. * Controls the scale bias of the parallax mode.
  46272. */
  46273. _this.parallaxScaleBias = 0.05;
  46274. /**
  46275. * If sets to true, disables all the lights affecting the material.
  46276. */
  46277. _this.disableLighting = false;
  46278. /**
  46279. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46280. */
  46281. _this.forceIrradianceInFragment = false;
  46282. /**
  46283. * Number of Simultaneous lights allowed on the material.
  46284. */
  46285. _this.maxSimultaneousLights = 4;
  46286. /**
  46287. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46288. */
  46289. _this.invertNormalMapX = false;
  46290. /**
  46291. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46292. */
  46293. _this.invertNormalMapY = false;
  46294. /**
  46295. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46296. */
  46297. _this.twoSidedLighting = false;
  46298. /**
  46299. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46300. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46301. */
  46302. _this.useAlphaFresnel = false;
  46303. /**
  46304. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46305. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46306. */
  46307. _this.useLinearAlphaFresnel = false;
  46308. /**
  46309. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46310. * And/Or occlude the blended part.
  46311. */
  46312. _this.environmentBRDFTexture = null;
  46313. /**
  46314. * Force normal to face away from face.
  46315. */
  46316. _this.forceNormalForward = false;
  46317. /**
  46318. * Enables specular anti aliasing in the PBR shader.
  46319. * It will both interacts on the Geometry for analytical and IBL lighting.
  46320. * It also prefilter the roughness map based on the bump values.
  46321. */
  46322. _this.enableSpecularAntiAliasing = false;
  46323. /**
  46324. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46325. * makes the reflect vector face the model (under horizon).
  46326. */
  46327. _this.useHorizonOcclusion = true;
  46328. /**
  46329. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46330. * too much the area relying on ambient texture to define their ambient occlusion.
  46331. */
  46332. _this.useRadianceOcclusion = true;
  46333. /**
  46334. * If set to true, no lighting calculations will be applied.
  46335. */
  46336. _this.unlit = false;
  46337. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46338. return _this;
  46339. }
  46340. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46341. /**
  46342. * BJS is using an harcoded light falloff based on a manually sets up range.
  46343. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46344. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46345. */
  46346. get: function () {
  46347. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46348. },
  46349. /**
  46350. * BJS is using an harcoded light falloff based on a manually sets up range.
  46351. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46352. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46353. */
  46354. set: function (value) {
  46355. if (value !== this.usePhysicalLightFalloff) {
  46356. // Ensure the effect will be rebuilt.
  46357. this._markAllSubMeshesAsTexturesDirty();
  46358. if (value) {
  46359. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46360. }
  46361. else {
  46362. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46363. }
  46364. }
  46365. },
  46366. enumerable: true,
  46367. configurable: true
  46368. });
  46369. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  46370. /**
  46371. * In order to support the falloff compatibility with gltf, a special mode has been added
  46372. * to reproduce the gltf light falloff.
  46373. */
  46374. get: function () {
  46375. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46376. },
  46377. /**
  46378. * In order to support the falloff compatibility with gltf, a special mode has been added
  46379. * to reproduce the gltf light falloff.
  46380. */
  46381. set: function (value) {
  46382. if (value !== this.useGLTFLightFalloff) {
  46383. // Ensure the effect will be rebuilt.
  46384. this._markAllSubMeshesAsTexturesDirty();
  46385. if (value) {
  46386. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46387. }
  46388. else {
  46389. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46390. }
  46391. }
  46392. },
  46393. enumerable: true,
  46394. configurable: true
  46395. });
  46396. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46397. /**
  46398. * Gets the image processing configuration used either in this material.
  46399. */
  46400. get: function () {
  46401. return this._imageProcessingConfiguration;
  46402. },
  46403. /**
  46404. * Sets the Default image processing configuration used either in the this material.
  46405. *
  46406. * If sets to null, the scene one is in use.
  46407. */
  46408. set: function (value) {
  46409. this._attachImageProcessingConfiguration(value);
  46410. // Ensure the effect will be rebuilt.
  46411. this._markAllSubMeshesAsTexturesDirty();
  46412. },
  46413. enumerable: true,
  46414. configurable: true
  46415. });
  46416. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46417. /**
  46418. * Gets wether the color curves effect is enabled.
  46419. */
  46420. get: function () {
  46421. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46422. },
  46423. /**
  46424. * Sets wether the color curves effect is enabled.
  46425. */
  46426. set: function (value) {
  46427. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46428. },
  46429. enumerable: true,
  46430. configurable: true
  46431. });
  46432. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46433. /**
  46434. * Gets wether the color grading effect is enabled.
  46435. */
  46436. get: function () {
  46437. return this.imageProcessingConfiguration.colorGradingEnabled;
  46438. },
  46439. /**
  46440. * Gets wether the color grading effect is enabled.
  46441. */
  46442. set: function (value) {
  46443. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46444. },
  46445. enumerable: true,
  46446. configurable: true
  46447. });
  46448. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46449. /**
  46450. * Gets wether tonemapping is enabled or not.
  46451. */
  46452. get: function () {
  46453. return this._imageProcessingConfiguration.toneMappingEnabled;
  46454. },
  46455. /**
  46456. * Sets wether tonemapping is enabled or not
  46457. */
  46458. set: function (value) {
  46459. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46460. },
  46461. enumerable: true,
  46462. configurable: true
  46463. });
  46464. ;
  46465. ;
  46466. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46467. /**
  46468. * The camera exposure used on this material.
  46469. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46470. * This corresponds to a photographic exposure.
  46471. */
  46472. get: function () {
  46473. return this._imageProcessingConfiguration.exposure;
  46474. },
  46475. /**
  46476. * The camera exposure used on this material.
  46477. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46478. * This corresponds to a photographic exposure.
  46479. */
  46480. set: function (value) {
  46481. this._imageProcessingConfiguration.exposure = value;
  46482. },
  46483. enumerable: true,
  46484. configurable: true
  46485. });
  46486. ;
  46487. ;
  46488. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46489. /**
  46490. * Gets The camera contrast used on this material.
  46491. */
  46492. get: function () {
  46493. return this._imageProcessingConfiguration.contrast;
  46494. },
  46495. /**
  46496. * Sets The camera contrast used on this material.
  46497. */
  46498. set: function (value) {
  46499. this._imageProcessingConfiguration.contrast = value;
  46500. },
  46501. enumerable: true,
  46502. configurable: true
  46503. });
  46504. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46505. /**
  46506. * Gets the Color Grading 2D Lookup Texture.
  46507. */
  46508. get: function () {
  46509. return this._imageProcessingConfiguration.colorGradingTexture;
  46510. },
  46511. /**
  46512. * Sets the Color Grading 2D Lookup Texture.
  46513. */
  46514. set: function (value) {
  46515. this._imageProcessingConfiguration.colorGradingTexture = value;
  46516. },
  46517. enumerable: true,
  46518. configurable: true
  46519. });
  46520. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46521. /**
  46522. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46523. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46524. * 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;
  46525. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46526. */
  46527. get: function () {
  46528. return this._imageProcessingConfiguration.colorCurves;
  46529. },
  46530. /**
  46531. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46532. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46533. * 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;
  46534. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46535. */
  46536. set: function (value) {
  46537. this._imageProcessingConfiguration.colorCurves = value;
  46538. },
  46539. enumerable: true,
  46540. configurable: true
  46541. });
  46542. /**
  46543. * Returns the name of this material class.
  46544. */
  46545. PBRMaterial.prototype.getClassName = function () {
  46546. return "PBRMaterial";
  46547. };
  46548. /**
  46549. * Returns an array of the actively used textures.
  46550. * @returns - Array of BaseTextures
  46551. */
  46552. PBRMaterial.prototype.getActiveTextures = function () {
  46553. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46554. if (this._albedoTexture) {
  46555. activeTextures.push(this._albedoTexture);
  46556. }
  46557. if (this._ambientTexture) {
  46558. activeTextures.push(this._ambientTexture);
  46559. }
  46560. if (this._opacityTexture) {
  46561. activeTextures.push(this._opacityTexture);
  46562. }
  46563. if (this._reflectionTexture) {
  46564. activeTextures.push(this._reflectionTexture);
  46565. }
  46566. if (this._emissiveTexture) {
  46567. activeTextures.push(this._emissiveTexture);
  46568. }
  46569. if (this._reflectivityTexture) {
  46570. activeTextures.push(this._reflectivityTexture);
  46571. }
  46572. if (this._metallicTexture) {
  46573. activeTextures.push(this._metallicTexture);
  46574. }
  46575. if (this._microSurfaceTexture) {
  46576. activeTextures.push(this._microSurfaceTexture);
  46577. }
  46578. if (this._bumpTexture) {
  46579. activeTextures.push(this._bumpTexture);
  46580. }
  46581. if (this._lightmapTexture) {
  46582. activeTextures.push(this._lightmapTexture);
  46583. }
  46584. if (this._refractionTexture) {
  46585. activeTextures.push(this._refractionTexture);
  46586. }
  46587. return activeTextures;
  46588. };
  46589. /**
  46590. * Checks to see if a texture is used in the material.
  46591. * @param texture - Base texture to use.
  46592. * @returns - Boolean specifying if a texture is used in the material.
  46593. */
  46594. PBRMaterial.prototype.hasTexture = function (texture) {
  46595. if (_super.prototype.hasTexture.call(this, texture)) {
  46596. return true;
  46597. }
  46598. if (this._albedoTexture === texture) {
  46599. return true;
  46600. }
  46601. if (this._ambientTexture === texture) {
  46602. return true;
  46603. }
  46604. if (this._opacityTexture === texture) {
  46605. return true;
  46606. }
  46607. if (this._reflectionTexture === texture) {
  46608. return true;
  46609. }
  46610. if (this._reflectivityTexture === texture) {
  46611. return true;
  46612. }
  46613. if (this._metallicTexture === texture) {
  46614. return true;
  46615. }
  46616. if (this._microSurfaceTexture === texture) {
  46617. return true;
  46618. }
  46619. if (this._bumpTexture === texture) {
  46620. return true;
  46621. }
  46622. if (this._lightmapTexture === texture) {
  46623. return true;
  46624. }
  46625. if (this._refractionTexture === texture) {
  46626. return true;
  46627. }
  46628. return false;
  46629. };
  46630. /**
  46631. * Makes a duplicate of the current material.
  46632. * @param name - name to use for the new material.
  46633. */
  46634. PBRMaterial.prototype.clone = function (name) {
  46635. var _this = this;
  46636. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46637. clone.id = name;
  46638. clone.name = name;
  46639. return clone;
  46640. };
  46641. /**
  46642. * Serializes this PBR Material.
  46643. * @returns - An object with the serialized material.
  46644. */
  46645. PBRMaterial.prototype.serialize = function () {
  46646. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46647. serializationObject.customType = "BABYLON.PBRMaterial";
  46648. return serializationObject;
  46649. };
  46650. // Statics
  46651. /**
  46652. * Parses a PBR Material from a serialized object.
  46653. * @param source - Serialized object.
  46654. * @param scene - BJS scene instance.
  46655. * @param rootUrl - url for the scene object
  46656. * @returns - PBRMaterial
  46657. */
  46658. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46659. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46660. };
  46661. /**
  46662. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46663. */
  46664. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  46665. /**
  46666. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46667. */
  46668. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  46669. /**
  46670. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46671. */
  46672. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  46673. /**
  46674. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46675. * They are also discarded below the alpha cutoff threshold to improve performances.
  46676. */
  46677. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46678. /**
  46679. * Defines the default value of how much AO map is occluding the analytical lights
  46680. * (point spot...).
  46681. */
  46682. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  46683. __decorate([
  46684. BABYLON.serialize(),
  46685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46686. ], PBRMaterial.prototype, "directIntensity", void 0);
  46687. __decorate([
  46688. BABYLON.serialize(),
  46689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46690. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46691. __decorate([
  46692. BABYLON.serialize(),
  46693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46694. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46695. __decorate([
  46696. BABYLON.serialize(),
  46697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46698. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46699. __decorate([
  46700. BABYLON.serialize(),
  46701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46702. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46703. __decorate([
  46704. BABYLON.serializeAsTexture(),
  46705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46706. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46707. __decorate([
  46708. BABYLON.serializeAsTexture(),
  46709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46710. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46711. __decorate([
  46712. BABYLON.serialize(),
  46713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46714. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46715. __decorate([
  46716. BABYLON.serialize(),
  46717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46718. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  46719. __decorate([
  46720. BABYLON.serializeAsTexture(),
  46721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46722. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46723. __decorate([
  46724. BABYLON.serializeAsTexture(),
  46725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46726. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46727. __decorate([
  46728. BABYLON.serializeAsTexture(),
  46729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46730. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46731. __decorate([
  46732. BABYLON.serializeAsTexture(),
  46733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46734. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46735. __decorate([
  46736. BABYLON.serializeAsTexture(),
  46737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46738. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46739. __decorate([
  46740. BABYLON.serialize(),
  46741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46742. ], PBRMaterial.prototype, "metallic", void 0);
  46743. __decorate([
  46744. BABYLON.serialize(),
  46745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46746. ], PBRMaterial.prototype, "roughness", void 0);
  46747. __decorate([
  46748. BABYLON.serializeAsTexture(),
  46749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46750. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46751. __decorate([
  46752. BABYLON.serializeAsTexture(),
  46753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46754. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46755. __decorate([
  46756. BABYLON.serializeAsTexture(),
  46757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46758. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46759. __decorate([
  46760. BABYLON.serializeAsTexture(),
  46761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46762. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46763. __decorate([
  46764. BABYLON.serializeAsColor3("ambient"),
  46765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46766. ], PBRMaterial.prototype, "ambientColor", void 0);
  46767. __decorate([
  46768. BABYLON.serializeAsColor3("albedo"),
  46769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46770. ], PBRMaterial.prototype, "albedoColor", void 0);
  46771. __decorate([
  46772. BABYLON.serializeAsColor3("reflectivity"),
  46773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46774. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46775. __decorate([
  46776. BABYLON.serializeAsColor3("reflection"),
  46777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46778. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46779. __decorate([
  46780. BABYLON.serializeAsColor3("emissive"),
  46781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46782. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46783. __decorate([
  46784. BABYLON.serialize(),
  46785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46786. ], PBRMaterial.prototype, "microSurface", void 0);
  46787. __decorate([
  46788. BABYLON.serialize(),
  46789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46790. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46791. __decorate([
  46792. BABYLON.serialize(),
  46793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46794. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46795. __decorate([
  46796. BABYLON.serialize(),
  46797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46798. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46799. __decorate([
  46800. BABYLON.serialize(),
  46801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46802. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46803. __decorate([
  46804. BABYLON.serialize(),
  46805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46806. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46807. __decorate([
  46808. BABYLON.serialize(),
  46809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46810. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46811. __decorate([
  46812. BABYLON.serialize(),
  46813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46814. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46815. __decorate([
  46816. BABYLON.serialize(),
  46817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46818. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46819. __decorate([
  46820. BABYLON.serialize(),
  46821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46822. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46823. __decorate([
  46824. BABYLON.serialize(),
  46825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46826. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46827. __decorate([
  46828. BABYLON.serialize(),
  46829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46830. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46831. __decorate([
  46832. BABYLON.serialize(),
  46833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46834. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46835. __decorate([
  46836. BABYLON.serialize(),
  46837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46838. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46839. __decorate([
  46840. BABYLON.serialize(),
  46841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46842. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46843. __decorate([
  46844. BABYLON.serialize(),
  46845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46846. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46847. __decorate([
  46848. BABYLON.serialize()
  46849. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  46850. __decorate([
  46851. BABYLON.serialize()
  46852. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  46853. __decorate([
  46854. BABYLON.serialize(),
  46855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46856. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46857. __decorate([
  46858. BABYLON.serialize(),
  46859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46860. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46861. __decorate([
  46862. BABYLON.serialize(),
  46863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46864. ], PBRMaterial.prototype, "useParallax", void 0);
  46865. __decorate([
  46866. BABYLON.serialize(),
  46867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46868. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46869. __decorate([
  46870. BABYLON.serialize(),
  46871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46872. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46873. __decorate([
  46874. BABYLON.serialize(),
  46875. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46876. ], PBRMaterial.prototype, "disableLighting", void 0);
  46877. __decorate([
  46878. BABYLON.serialize(),
  46879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46880. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46881. __decorate([
  46882. BABYLON.serialize(),
  46883. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46884. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46885. __decorate([
  46886. BABYLON.serialize(),
  46887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46888. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46889. __decorate([
  46890. BABYLON.serialize(),
  46891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46892. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46893. __decorate([
  46894. BABYLON.serialize(),
  46895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46896. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46897. __decorate([
  46898. BABYLON.serialize(),
  46899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46900. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46901. __decorate([
  46902. BABYLON.serialize(),
  46903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46904. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46905. __decorate([
  46906. BABYLON.serializeAsTexture(),
  46907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46908. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46909. __decorate([
  46910. BABYLON.serialize(),
  46911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46912. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46913. __decorate([
  46914. BABYLON.serialize(),
  46915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46916. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46917. __decorate([
  46918. BABYLON.serialize(),
  46919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46920. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46921. __decorate([
  46922. BABYLON.serialize(),
  46923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46924. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46925. __decorate([
  46926. BABYLON.serialize(),
  46927. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46928. ], PBRMaterial.prototype, "unlit", void 0);
  46929. return PBRMaterial;
  46930. }(BABYLON.PBRBaseMaterial));
  46931. BABYLON.PBRMaterial = PBRMaterial;
  46932. })(BABYLON || (BABYLON = {}));
  46933. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46934. var BABYLON;
  46935. (function (BABYLON) {
  46936. /**
  46937. * The PBR material of BJS following the metal roughness convention.
  46938. *
  46939. * This fits to the PBR convention in the GLTF definition:
  46940. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46941. */
  46942. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46943. __extends(PBRMetallicRoughnessMaterial, _super);
  46944. /**
  46945. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46946. *
  46947. * @param name The material name
  46948. * @param scene The scene the material will be use in.
  46949. */
  46950. function PBRMetallicRoughnessMaterial(name, scene) {
  46951. var _this = _super.call(this, name, scene) || this;
  46952. _this._useRoughnessFromMetallicTextureAlpha = false;
  46953. _this._useRoughnessFromMetallicTextureGreen = true;
  46954. _this._useMetallnessFromMetallicTextureBlue = true;
  46955. _this.metallic = 1.0;
  46956. _this.roughness = 1.0;
  46957. return _this;
  46958. }
  46959. /**
  46960. * Return the currrent class name of the material.
  46961. */
  46962. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46963. return "PBRMetallicRoughnessMaterial";
  46964. };
  46965. /**
  46966. * Return the active textures of the material.
  46967. */
  46968. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46969. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46970. if (this.baseTexture) {
  46971. activeTextures.push(this.baseTexture);
  46972. }
  46973. if (this.metallicRoughnessTexture) {
  46974. activeTextures.push(this.metallicRoughnessTexture);
  46975. }
  46976. return activeTextures;
  46977. };
  46978. /**
  46979. * Checks to see if a texture is used in the material.
  46980. * @param texture - Base texture to use.
  46981. * @returns - Boolean specifying if a texture is used in the material.
  46982. */
  46983. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46984. if (_super.prototype.hasTexture.call(this, texture)) {
  46985. return true;
  46986. }
  46987. if (this.baseTexture === texture) {
  46988. return true;
  46989. }
  46990. if (this.metallicRoughnessTexture === texture) {
  46991. return true;
  46992. }
  46993. return false;
  46994. };
  46995. /**
  46996. * Makes a duplicate of the current material.
  46997. * @param name - name to use for the new material.
  46998. */
  46999. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47000. var _this = this;
  47001. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47002. clone.id = name;
  47003. clone.name = name;
  47004. return clone;
  47005. };
  47006. /**
  47007. * Serialize the material to a parsable JSON object.
  47008. */
  47009. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47010. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47011. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47012. return serializationObject;
  47013. };
  47014. /**
  47015. * Parses a JSON object correponding to the serialize function.
  47016. */
  47017. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47018. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47019. };
  47020. __decorate([
  47021. BABYLON.serializeAsColor3(),
  47022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47023. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47024. __decorate([
  47025. BABYLON.serializeAsTexture(),
  47026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47027. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47028. __decorate([
  47029. BABYLON.serialize(),
  47030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47031. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47032. __decorate([
  47033. BABYLON.serialize(),
  47034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47035. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47036. __decorate([
  47037. BABYLON.serializeAsTexture(),
  47038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47039. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47040. return PBRMetallicRoughnessMaterial;
  47041. }(BABYLON.PBRBaseSimpleMaterial));
  47042. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47043. })(BABYLON || (BABYLON = {}));
  47044. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47045. var BABYLON;
  47046. (function (BABYLON) {
  47047. /**
  47048. * The PBR material of BJS following the specular glossiness convention.
  47049. *
  47050. * This fits to the PBR convention in the GLTF definition:
  47051. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47052. */
  47053. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47054. __extends(PBRSpecularGlossinessMaterial, _super);
  47055. /**
  47056. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47057. *
  47058. * @param name The material name
  47059. * @param scene The scene the material will be use in.
  47060. */
  47061. function PBRSpecularGlossinessMaterial(name, scene) {
  47062. var _this = _super.call(this, name, scene) || this;
  47063. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47064. return _this;
  47065. }
  47066. /**
  47067. * Return the currrent class name of the material.
  47068. */
  47069. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47070. return "PBRSpecularGlossinessMaterial";
  47071. };
  47072. /**
  47073. * Return the active textures of the material.
  47074. */
  47075. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47076. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47077. if (this.diffuseTexture) {
  47078. activeTextures.push(this.diffuseTexture);
  47079. }
  47080. if (this.specularGlossinessTexture) {
  47081. activeTextures.push(this.specularGlossinessTexture);
  47082. }
  47083. return activeTextures;
  47084. };
  47085. /**
  47086. * Checks to see if a texture is used in the material.
  47087. * @param texture - Base texture to use.
  47088. * @returns - Boolean specifying if a texture is used in the material.
  47089. */
  47090. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47091. if (_super.prototype.hasTexture.call(this, texture)) {
  47092. return true;
  47093. }
  47094. if (this.diffuseTexture === texture) {
  47095. return true;
  47096. }
  47097. if (this.specularGlossinessTexture === texture) {
  47098. return true;
  47099. }
  47100. return false;
  47101. };
  47102. /**
  47103. * Makes a duplicate of the current material.
  47104. * @param name - name to use for the new material.
  47105. */
  47106. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47107. var _this = this;
  47108. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47109. clone.id = name;
  47110. clone.name = name;
  47111. return clone;
  47112. };
  47113. /**
  47114. * Serialize the material to a parsable JSON object.
  47115. */
  47116. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47117. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47118. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47119. return serializationObject;
  47120. };
  47121. /**
  47122. * Parses a JSON object correponding to the serialize function.
  47123. */
  47124. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47125. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47126. };
  47127. __decorate([
  47128. BABYLON.serializeAsColor3("diffuse"),
  47129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47130. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47131. __decorate([
  47132. BABYLON.serializeAsTexture(),
  47133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47134. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47135. __decorate([
  47136. BABYLON.serializeAsColor3("specular"),
  47137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47138. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47139. __decorate([
  47140. BABYLON.serialize(),
  47141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47142. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47143. __decorate([
  47144. BABYLON.serializeAsTexture(),
  47145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47146. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47147. return PBRSpecularGlossinessMaterial;
  47148. }(BABYLON.PBRBaseSimpleMaterial));
  47149. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47150. })(BABYLON || (BABYLON = {}));
  47151. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47152. var BABYLON;
  47153. (function (BABYLON) {
  47154. /**
  47155. * This is a list of all the different input types that are available in the application.
  47156. * Fo instance: ArcRotateCameraGamepadInput...
  47157. */
  47158. BABYLON.CameraInputTypes = {};
  47159. /**
  47160. * This represents the input manager used within a camera.
  47161. * It helps dealing with all the different kind of input attached to a camera.
  47162. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47163. */
  47164. var CameraInputsManager = /** @class */ (function () {
  47165. /**
  47166. * Instantiate a new Camera Input Manager.
  47167. * @param camera Defines the camera the input manager blongs to
  47168. */
  47169. function CameraInputsManager(camera) {
  47170. this.attached = {};
  47171. this.camera = camera;
  47172. this.checkInputs = function () { };
  47173. }
  47174. /**
  47175. * Add an input method to a camera
  47176. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47177. * @param input camera input method
  47178. */
  47179. CameraInputsManager.prototype.add = function (input) {
  47180. var type = input.getSimpleName();
  47181. if (this.attached[type]) {
  47182. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47183. return;
  47184. }
  47185. this.attached[type] = input;
  47186. input.camera = this.camera;
  47187. //for checkInputs, we are dynamically creating a function
  47188. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47189. if (input.checkInputs) {
  47190. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47191. }
  47192. if (this.attachedElement) {
  47193. input.attachControl(this.attachedElement);
  47194. }
  47195. };
  47196. /**
  47197. * Remove a specific input method from a camera
  47198. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47199. * @param inputToRemove camera input method
  47200. */
  47201. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47202. for (var cam in this.attached) {
  47203. var input = this.attached[cam];
  47204. if (input === inputToRemove) {
  47205. input.detachControl(this.attachedElement);
  47206. input.camera = null;
  47207. delete this.attached[cam];
  47208. this.rebuildInputCheck();
  47209. }
  47210. }
  47211. };
  47212. /**
  47213. * Remove a specific input type from a camera
  47214. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47215. * @param inputType the type of the input to remove
  47216. */
  47217. CameraInputsManager.prototype.removeByType = function (inputType) {
  47218. for (var cam in this.attached) {
  47219. var input = this.attached[cam];
  47220. if (input.getClassName() === inputType) {
  47221. input.detachControl(this.attachedElement);
  47222. input.camera = null;
  47223. delete this.attached[cam];
  47224. this.rebuildInputCheck();
  47225. }
  47226. }
  47227. };
  47228. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47229. var current = this.checkInputs;
  47230. return function () {
  47231. current();
  47232. fn();
  47233. };
  47234. };
  47235. /**
  47236. * Attach the input controls to the currently attached dom element to listen the events from.
  47237. * @param input Defines the input to attach
  47238. */
  47239. CameraInputsManager.prototype.attachInput = function (input) {
  47240. if (this.attachedElement) {
  47241. input.attachControl(this.attachedElement, this.noPreventDefault);
  47242. }
  47243. };
  47244. /**
  47245. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47246. * @param element Defines the dom element to collect the events from
  47247. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47248. */
  47249. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47250. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47251. if (this.attachedElement) {
  47252. return;
  47253. }
  47254. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47255. this.attachedElement = element;
  47256. this.noPreventDefault = noPreventDefault;
  47257. for (var cam in this.attached) {
  47258. this.attached[cam].attachControl(element, noPreventDefault);
  47259. }
  47260. };
  47261. /**
  47262. * Detach the current manager inputs controls from a specific dom element.
  47263. * @param element Defines the dom element to collect the events from
  47264. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47265. */
  47266. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47267. if (disconnect === void 0) { disconnect = false; }
  47268. if (this.attachedElement !== element) {
  47269. return;
  47270. }
  47271. for (var cam in this.attached) {
  47272. this.attached[cam].detachControl(element);
  47273. if (disconnect) {
  47274. this.attached[cam].camera = null;
  47275. }
  47276. }
  47277. this.attachedElement = null;
  47278. };
  47279. /**
  47280. * Rebuild the dynamic inputCheck function from the current list of
  47281. * defined inputs in the manager.
  47282. */
  47283. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47284. this.checkInputs = function () { };
  47285. for (var cam in this.attached) {
  47286. var input = this.attached[cam];
  47287. if (input.checkInputs) {
  47288. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47289. }
  47290. }
  47291. };
  47292. /**
  47293. * Remove all attached input methods from a camera
  47294. */
  47295. CameraInputsManager.prototype.clear = function () {
  47296. if (this.attachedElement) {
  47297. this.detachElement(this.attachedElement, true);
  47298. }
  47299. this.attached = {};
  47300. this.attachedElement = null;
  47301. this.checkInputs = function () { };
  47302. };
  47303. /**
  47304. * Serialize the current input manager attached to a camera.
  47305. * This ensures than once parsed,
  47306. * the input associated to the camera will be identical to the current ones
  47307. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47308. */
  47309. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47310. var inputs = {};
  47311. for (var cam in this.attached) {
  47312. var input = this.attached[cam];
  47313. var res = BABYLON.SerializationHelper.Serialize(input);
  47314. inputs[input.getClassName()] = res;
  47315. }
  47316. serializedCamera.inputsmgr = inputs;
  47317. };
  47318. /**
  47319. * Parses an input manager serialized JSON to restore the previous list of inputs
  47320. * and states associated to a camera.
  47321. * @param parsedCamera Defines the JSON to parse
  47322. */
  47323. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47324. var parsedInputs = parsedCamera.inputsmgr;
  47325. if (parsedInputs) {
  47326. this.clear();
  47327. for (var n in parsedInputs) {
  47328. var construct = BABYLON.CameraInputTypes[n];
  47329. if (construct) {
  47330. var parsedinput = parsedInputs[n];
  47331. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47332. this.add(input);
  47333. }
  47334. }
  47335. }
  47336. else {
  47337. //2016-03-08 this part is for managing backward compatibility
  47338. for (var n in this.attached) {
  47339. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47340. if (construct) {
  47341. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47342. this.remove(this.attached[n]);
  47343. this.add(input);
  47344. }
  47345. }
  47346. }
  47347. };
  47348. return CameraInputsManager;
  47349. }());
  47350. BABYLON.CameraInputsManager = CameraInputsManager;
  47351. })(BABYLON || (BABYLON = {}));
  47352. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47353. var BABYLON;
  47354. (function (BABYLON) {
  47355. /**
  47356. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47357. * This is the base of the follow, arc rotate cameras and Free camera
  47358. * @see http://doc.babylonjs.com/features/cameras
  47359. */
  47360. var TargetCamera = /** @class */ (function (_super) {
  47361. __extends(TargetCamera, _super);
  47362. /**
  47363. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47364. * This is the base of the follow, arc rotate cameras and Free camera
  47365. * @see http://doc.babylonjs.com/features/cameras
  47366. * @param name Defines the name of the camera in the scene
  47367. * @param position Defines the start position of the camera in the scene
  47368. * @param scene Defines the scene the camera belongs to
  47369. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47370. */
  47371. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47372. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47373. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47374. /**
  47375. * Define the current direction the camera is moving to
  47376. */
  47377. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47378. /**
  47379. * Define the current rotation the camera is rotating to
  47380. */
  47381. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47382. /**
  47383. * Define the current rotation of the camera
  47384. */
  47385. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47386. /**
  47387. * Define the current speed of the camera
  47388. */
  47389. _this.speed = 2.0;
  47390. /**
  47391. * Add cconstraint to the camera to prevent it to move freely in all directions and
  47392. * around all axis.
  47393. */
  47394. _this.noRotationConstraint = false;
  47395. /**
  47396. * Define the current target of the camera as an object or a position.
  47397. */
  47398. _this.lockedTarget = null;
  47399. /** @hidden */
  47400. _this._currentTarget = BABYLON.Vector3.Zero();
  47401. /** @hidden */
  47402. _this._viewMatrix = BABYLON.Matrix.Zero();
  47403. /** @hidden */
  47404. _this._camMatrix = BABYLON.Matrix.Zero();
  47405. /** @hidden */
  47406. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47407. /** @hidden */
  47408. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47409. /** @hidden */
  47410. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47411. /** @hidden */
  47412. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47413. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47414. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47415. _this._defaultUp = BABYLON.Vector3.Up();
  47416. _this._cachedRotationZ = 0;
  47417. return _this;
  47418. }
  47419. /**
  47420. * Gets the position in front of the camera at a given distance.
  47421. * @param distance The distance from the camera we want the position to be
  47422. * @returns the position
  47423. */
  47424. TargetCamera.prototype.getFrontPosition = function (distance) {
  47425. this.getWorldMatrix();
  47426. var direction = this.getTarget().subtract(this.position);
  47427. direction.normalize();
  47428. direction.scaleInPlace(distance);
  47429. return this.globalPosition.add(direction);
  47430. };
  47431. /** @hidden */
  47432. TargetCamera.prototype._getLockedTargetPosition = function () {
  47433. if (!this.lockedTarget) {
  47434. return null;
  47435. }
  47436. if (this.lockedTarget.absolutePosition) {
  47437. this.lockedTarget.computeWorldMatrix();
  47438. }
  47439. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47440. };
  47441. /**
  47442. * Store current camera state of the camera (fov, position, rotation, etc..)
  47443. * @returns the camera
  47444. */
  47445. TargetCamera.prototype.storeState = function () {
  47446. this._storedPosition = this.position.clone();
  47447. this._storedRotation = this.rotation.clone();
  47448. if (this.rotationQuaternion) {
  47449. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47450. }
  47451. return _super.prototype.storeState.call(this);
  47452. };
  47453. /**
  47454. * Restored camera state. You must call storeState() first
  47455. * @returns whether it was successful or not
  47456. * @hidden
  47457. */
  47458. TargetCamera.prototype._restoreStateValues = function () {
  47459. if (!_super.prototype._restoreStateValues.call(this)) {
  47460. return false;
  47461. }
  47462. this.position = this._storedPosition.clone();
  47463. this.rotation = this._storedRotation.clone();
  47464. if (this.rotationQuaternion) {
  47465. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47466. }
  47467. this.cameraDirection.copyFromFloats(0, 0, 0);
  47468. this.cameraRotation.copyFromFloats(0, 0);
  47469. return true;
  47470. };
  47471. /** @hidden */
  47472. TargetCamera.prototype._initCache = function () {
  47473. _super.prototype._initCache.call(this);
  47474. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47475. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47476. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47477. };
  47478. /** @hidden */
  47479. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47480. if (!ignoreParentClass) {
  47481. _super.prototype._updateCache.call(this);
  47482. }
  47483. var lockedTargetPosition = this._getLockedTargetPosition();
  47484. if (!lockedTargetPosition) {
  47485. this._cache.lockedTarget = null;
  47486. }
  47487. else {
  47488. if (!this._cache.lockedTarget) {
  47489. this._cache.lockedTarget = lockedTargetPosition.clone();
  47490. }
  47491. else {
  47492. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47493. }
  47494. }
  47495. this._cache.rotation.copyFrom(this.rotation);
  47496. if (this.rotationQuaternion)
  47497. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47498. };
  47499. // Synchronized
  47500. /** @hidden */
  47501. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47502. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47503. return false;
  47504. }
  47505. var lockedTargetPosition = this._getLockedTargetPosition();
  47506. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47507. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47508. };
  47509. // Methods
  47510. /** @hidden */
  47511. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47512. var engine = this.getEngine();
  47513. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47514. };
  47515. // Target
  47516. /** @hidden */
  47517. TargetCamera.prototype.setTarget = function (target) {
  47518. this.upVector.normalize();
  47519. if (this.position.z === target.z) {
  47520. this.position.z += BABYLON.Epsilon;
  47521. }
  47522. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  47523. this._camMatrix.invert();
  47524. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47525. var vDir = target.subtract(this.position);
  47526. if (vDir.x >= 0.0) {
  47527. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47528. }
  47529. else {
  47530. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47531. }
  47532. this.rotation.z = 0;
  47533. if (isNaN(this.rotation.x)) {
  47534. this.rotation.x = 0;
  47535. }
  47536. if (isNaN(this.rotation.y)) {
  47537. this.rotation.y = 0;
  47538. }
  47539. if (isNaN(this.rotation.z)) {
  47540. this.rotation.z = 0;
  47541. }
  47542. if (this.rotationQuaternion) {
  47543. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47544. }
  47545. };
  47546. /**
  47547. * Return the current target position of the camera. This value is expressed in local space.
  47548. * @returns the target position
  47549. */
  47550. TargetCamera.prototype.getTarget = function () {
  47551. return this._currentTarget;
  47552. };
  47553. /** @hidden */
  47554. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47555. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47556. };
  47557. /** @hidden */
  47558. TargetCamera.prototype._updatePosition = function () {
  47559. if (this.parent) {
  47560. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47561. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47562. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47563. return;
  47564. }
  47565. this.position.addInPlace(this.cameraDirection);
  47566. };
  47567. /** @hidden */
  47568. TargetCamera.prototype._checkInputs = function () {
  47569. var needToMove = this._decideIfNeedsToMove();
  47570. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47571. // Move
  47572. if (needToMove) {
  47573. this._updatePosition();
  47574. }
  47575. // Rotate
  47576. if (needToRotate) {
  47577. this.rotation.x += this.cameraRotation.x;
  47578. this.rotation.y += this.cameraRotation.y;
  47579. //rotate, if quaternion is set and rotation was used
  47580. if (this.rotationQuaternion) {
  47581. var len = this.rotation.lengthSquared();
  47582. if (len) {
  47583. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47584. }
  47585. }
  47586. if (!this.noRotationConstraint) {
  47587. var limit = (Math.PI / 2) * 0.95;
  47588. if (this.rotation.x > limit)
  47589. this.rotation.x = limit;
  47590. if (this.rotation.x < -limit)
  47591. this.rotation.x = -limit;
  47592. }
  47593. }
  47594. // Inertia
  47595. if (needToMove) {
  47596. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47597. this.cameraDirection.x = 0;
  47598. }
  47599. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47600. this.cameraDirection.y = 0;
  47601. }
  47602. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47603. this.cameraDirection.z = 0;
  47604. }
  47605. this.cameraDirection.scaleInPlace(this.inertia);
  47606. }
  47607. if (needToRotate) {
  47608. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47609. this.cameraRotation.x = 0;
  47610. }
  47611. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47612. this.cameraRotation.y = 0;
  47613. }
  47614. this.cameraRotation.scaleInPlace(this.inertia);
  47615. }
  47616. _super.prototype._checkInputs.call(this);
  47617. };
  47618. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47619. if (this.rotationQuaternion) {
  47620. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47621. }
  47622. else {
  47623. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47624. }
  47625. };
  47626. /**
  47627. * 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)
  47628. * @returns the current camera
  47629. */
  47630. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  47631. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  47632. return this;
  47633. };
  47634. /** @hidden */
  47635. TargetCamera.prototype._getViewMatrix = function () {
  47636. if (this.lockedTarget) {
  47637. this.setTarget(this._getLockedTargetPosition());
  47638. }
  47639. // Compute
  47640. this._updateCameraRotationMatrix();
  47641. // Apply the changed rotation to the upVector.
  47642. if (this._cachedRotationZ != this.rotation.z) {
  47643. this._rotateUpVectorWithCameraRotationMatrix();
  47644. this._cachedRotationZ = this.rotation.z;
  47645. }
  47646. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47647. // Computing target and final matrix
  47648. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47649. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  47650. return this._viewMatrix;
  47651. };
  47652. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47653. if (this.parent) {
  47654. var parentWorldMatrix = this.parent.getWorldMatrix();
  47655. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  47656. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47657. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47658. this._markSyncedWithParent();
  47659. }
  47660. else {
  47661. this._globalPosition.copyFrom(position);
  47662. this._globalCurrentTarget.copyFrom(target);
  47663. this._globalCurrentUpVector.copyFrom(up);
  47664. }
  47665. if (this.getScene().useRightHandedSystem) {
  47666. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47667. }
  47668. else {
  47669. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47670. }
  47671. };
  47672. /**
  47673. * @hidden
  47674. */
  47675. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47676. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47677. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47678. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47679. if (!this.rotationQuaternion) {
  47680. this.rotationQuaternion = new BABYLON.Quaternion();
  47681. }
  47682. rigCamera._cameraRigParams = {};
  47683. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47684. }
  47685. return rigCamera;
  47686. }
  47687. return null;
  47688. };
  47689. /**
  47690. * @hidden
  47691. */
  47692. TargetCamera.prototype._updateRigCameras = function () {
  47693. var camLeft = this._rigCameras[0];
  47694. var camRight = this._rigCameras[1];
  47695. switch (this.cameraRigMode) {
  47696. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47697. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47698. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47699. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47700. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47701. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47702. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47703. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47704. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47705. camLeft.setTarget(this.getTarget());
  47706. camRight.setTarget(this.getTarget());
  47707. break;
  47708. case BABYLON.Camera.RIG_MODE_VR:
  47709. if (camLeft.rotationQuaternion) {
  47710. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47711. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47712. }
  47713. else {
  47714. camLeft.rotation.copyFrom(this.rotation);
  47715. camRight.rotation.copyFrom(this.rotation);
  47716. }
  47717. camLeft.position.copyFrom(this.position);
  47718. camRight.position.copyFrom(this.position);
  47719. break;
  47720. }
  47721. _super.prototype._updateRigCameras.call(this);
  47722. };
  47723. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47724. if (!this._rigCamTransformMatrix) {
  47725. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47726. }
  47727. var target = this.getTarget();
  47728. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47729. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47730. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47731. };
  47732. /**
  47733. * Gets the current object class name.
  47734. * @return the class name
  47735. */
  47736. TargetCamera.prototype.getClassName = function () {
  47737. return "TargetCamera";
  47738. };
  47739. __decorate([
  47740. BABYLON.serializeAsVector3()
  47741. ], TargetCamera.prototype, "rotation", void 0);
  47742. __decorate([
  47743. BABYLON.serialize()
  47744. ], TargetCamera.prototype, "speed", void 0);
  47745. __decorate([
  47746. BABYLON.serializeAsMeshReference("lockedTargetId")
  47747. ], TargetCamera.prototype, "lockedTarget", void 0);
  47748. return TargetCamera;
  47749. }(BABYLON.Camera));
  47750. BABYLON.TargetCamera = TargetCamera;
  47751. })(BABYLON || (BABYLON = {}));
  47752. //# sourceMappingURL=babylon.targetCamera.js.map
  47753. var BABYLON;
  47754. (function (BABYLON) {
  47755. /**
  47756. * Manage the mouse inputs to control the movement of a free camera.
  47757. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47758. */
  47759. var FreeCameraMouseInput = /** @class */ (function () {
  47760. /**
  47761. * Manage the mouse inputs to control the movement of a free camera.
  47762. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47763. * @param touchEnabled Defines if touch is enabled or not
  47764. */
  47765. function FreeCameraMouseInput(
  47766. /**
  47767. * Define if touch is enabled in the mouse input
  47768. */
  47769. touchEnabled) {
  47770. if (touchEnabled === void 0) { touchEnabled = true; }
  47771. this.touchEnabled = touchEnabled;
  47772. /**
  47773. * Defines the buttons associated with the input to handle camera move.
  47774. */
  47775. this.buttons = [0, 1, 2];
  47776. /**
  47777. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  47778. */
  47779. this.angularSensibility = 2000.0;
  47780. this.previousPosition = null;
  47781. }
  47782. /**
  47783. * Attach the input controls to a specific dom element to get the input from.
  47784. * @param element Defines the element the controls should be listened from
  47785. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47786. */
  47787. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47788. var _this = this;
  47789. var engine = this.camera.getEngine();
  47790. if (!this._pointerInput) {
  47791. this._pointerInput = function (p, s) {
  47792. var evt = p.event;
  47793. if (engine.isInVRExclusivePointerMode) {
  47794. return;
  47795. }
  47796. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47797. return;
  47798. }
  47799. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47800. return;
  47801. }
  47802. var srcElement = (evt.srcElement || evt.target);
  47803. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47804. try {
  47805. srcElement.setPointerCapture(evt.pointerId);
  47806. }
  47807. catch (e) {
  47808. //Nothing to do with the error. Execution will continue.
  47809. }
  47810. _this.previousPosition = {
  47811. x: evt.clientX,
  47812. y: evt.clientY
  47813. };
  47814. if (!noPreventDefault) {
  47815. evt.preventDefault();
  47816. element.focus();
  47817. }
  47818. }
  47819. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47820. try {
  47821. srcElement.releasePointerCapture(evt.pointerId);
  47822. }
  47823. catch (e) {
  47824. //Nothing to do with the error.
  47825. }
  47826. _this.previousPosition = null;
  47827. if (!noPreventDefault) {
  47828. evt.preventDefault();
  47829. }
  47830. }
  47831. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47832. if (!_this.previousPosition || engine.isPointerLock) {
  47833. return;
  47834. }
  47835. var offsetX = evt.clientX - _this.previousPosition.x;
  47836. if (_this.camera.getScene().useRightHandedSystem)
  47837. offsetX *= -1;
  47838. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47839. offsetX *= -1;
  47840. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47841. var offsetY = evt.clientY - _this.previousPosition.y;
  47842. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47843. _this.previousPosition = {
  47844. x: evt.clientX,
  47845. y: evt.clientY
  47846. };
  47847. if (!noPreventDefault) {
  47848. evt.preventDefault();
  47849. }
  47850. }
  47851. };
  47852. }
  47853. this._onMouseMove = function (evt) {
  47854. if (!engine.isPointerLock) {
  47855. return;
  47856. }
  47857. if (engine.isInVRExclusivePointerMode) {
  47858. return;
  47859. }
  47860. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47861. if (_this.camera.getScene().useRightHandedSystem)
  47862. offsetX *= -1;
  47863. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47864. offsetX *= -1;
  47865. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47866. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47867. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47868. _this.previousPosition = null;
  47869. if (!noPreventDefault) {
  47870. evt.preventDefault();
  47871. }
  47872. };
  47873. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47874. element.addEventListener("mousemove", this._onMouseMove, false);
  47875. };
  47876. /**
  47877. * Detach the current controls from the specified dom element.
  47878. * @param element Defines the element to stop listening the inputs from
  47879. */
  47880. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47881. if (this._observer && element) {
  47882. this.camera.getScene().onPointerObservable.remove(this._observer);
  47883. if (this._onMouseMove) {
  47884. element.removeEventListener("mousemove", this._onMouseMove);
  47885. }
  47886. this._observer = null;
  47887. this._onMouseMove = null;
  47888. this.previousPosition = null;
  47889. }
  47890. };
  47891. /**
  47892. * Gets the class name of the current intput.
  47893. * @returns the class name
  47894. */
  47895. FreeCameraMouseInput.prototype.getClassName = function () {
  47896. return "FreeCameraMouseInput";
  47897. };
  47898. /**
  47899. * Get the friendly name associated with the input class.
  47900. * @returns the input friendly name
  47901. */
  47902. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47903. return "mouse";
  47904. };
  47905. __decorate([
  47906. BABYLON.serialize()
  47907. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47908. __decorate([
  47909. BABYLON.serialize()
  47910. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47911. return FreeCameraMouseInput;
  47912. }());
  47913. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47914. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47915. })(BABYLON || (BABYLON = {}));
  47916. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47917. var BABYLON;
  47918. (function (BABYLON) {
  47919. /**
  47920. * Manage the keyboard inputs to control the movement of a free camera.
  47921. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47922. */
  47923. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47924. function FreeCameraKeyboardMoveInput() {
  47925. /**
  47926. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47927. */
  47928. this.keysUp = [38];
  47929. /**
  47930. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47931. */
  47932. this.keysDown = [40];
  47933. /**
  47934. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47935. */
  47936. this.keysLeft = [37];
  47937. /**
  47938. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47939. */
  47940. this.keysRight = [39];
  47941. this._keys = new Array();
  47942. }
  47943. /**
  47944. * Attach the input controls to a specific dom element to get the input from.
  47945. * @param element Defines the element the controls should be listened from
  47946. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47947. */
  47948. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47949. var _this = this;
  47950. if (this._onCanvasBlurObserver) {
  47951. return;
  47952. }
  47953. this._scene = this.camera.getScene();
  47954. this._engine = this._scene.getEngine();
  47955. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47956. _this._keys = [];
  47957. });
  47958. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47959. var evt = info.event;
  47960. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47961. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47962. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47963. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47964. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47965. var index = _this._keys.indexOf(evt.keyCode);
  47966. if (index === -1) {
  47967. _this._keys.push(evt.keyCode);
  47968. }
  47969. if (!noPreventDefault) {
  47970. evt.preventDefault();
  47971. }
  47972. }
  47973. }
  47974. else {
  47975. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47976. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47977. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47978. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47979. var index = _this._keys.indexOf(evt.keyCode);
  47980. if (index >= 0) {
  47981. _this._keys.splice(index, 1);
  47982. }
  47983. if (!noPreventDefault) {
  47984. evt.preventDefault();
  47985. }
  47986. }
  47987. }
  47988. });
  47989. };
  47990. /**
  47991. * Detach the current controls from the specified dom element.
  47992. * @param element Defines the element to stop listening the inputs from
  47993. */
  47994. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47995. if (this._scene) {
  47996. if (this._onKeyboardObserver) {
  47997. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47998. }
  47999. if (this._onCanvasBlurObserver) {
  48000. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48001. }
  48002. this._onKeyboardObserver = null;
  48003. this._onCanvasBlurObserver = null;
  48004. }
  48005. this._keys = [];
  48006. };
  48007. /**
  48008. * Update the current camera state depending on the inputs that have been used this frame.
  48009. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48010. */
  48011. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48012. if (this._onKeyboardObserver) {
  48013. var camera = this.camera;
  48014. // Keyboard
  48015. for (var index = 0; index < this._keys.length; index++) {
  48016. var keyCode = this._keys[index];
  48017. var speed = camera._computeLocalCameraSpeed();
  48018. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48019. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48020. }
  48021. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48022. camera._localDirection.copyFromFloats(0, 0, speed);
  48023. }
  48024. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48025. camera._localDirection.copyFromFloats(speed, 0, 0);
  48026. }
  48027. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48028. camera._localDirection.copyFromFloats(0, 0, -speed);
  48029. }
  48030. if (camera.getScene().useRightHandedSystem) {
  48031. camera._localDirection.z *= -1;
  48032. }
  48033. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48034. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48035. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48036. }
  48037. }
  48038. };
  48039. /**
  48040. * Gets the class name of the current intput.
  48041. * @returns the class name
  48042. */
  48043. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48044. return "FreeCameraKeyboardMoveInput";
  48045. };
  48046. /** @hidden */
  48047. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48048. this._keys = [];
  48049. };
  48050. /**
  48051. * Get the friendly name associated with the input class.
  48052. * @returns the input friendly name
  48053. */
  48054. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48055. return "keyboard";
  48056. };
  48057. __decorate([
  48058. BABYLON.serialize()
  48059. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48060. __decorate([
  48061. BABYLON.serialize()
  48062. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48063. __decorate([
  48064. BABYLON.serialize()
  48065. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48066. __decorate([
  48067. BABYLON.serialize()
  48068. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48069. return FreeCameraKeyboardMoveInput;
  48070. }());
  48071. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48072. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48073. })(BABYLON || (BABYLON = {}));
  48074. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48075. var BABYLON;
  48076. (function (BABYLON) {
  48077. /**
  48078. * Default Inputs manager for the FreeCamera.
  48079. * It groups all the default supported inputs for ease of use.
  48080. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48081. */
  48082. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48083. __extends(FreeCameraInputsManager, _super);
  48084. /**
  48085. * Instantiates a new FreeCameraInputsManager.
  48086. * @param camera Defines the camera the inputs belong to
  48087. */
  48088. function FreeCameraInputsManager(camera) {
  48089. return _super.call(this, camera) || this;
  48090. }
  48091. /**
  48092. * Add keyboard input support to the input manager.
  48093. * @returns the current input manager
  48094. */
  48095. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48096. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48097. return this;
  48098. };
  48099. /**
  48100. * Add mouse input support to the input manager.
  48101. * @returns the current input manager
  48102. */
  48103. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48104. if (touchEnabled === void 0) { touchEnabled = true; }
  48105. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48106. return this;
  48107. };
  48108. /**
  48109. * Add orientation input support to the input manager.
  48110. * @returns the current input manager
  48111. */
  48112. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48113. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48114. return this;
  48115. };
  48116. /**
  48117. * Add touch input support to the input manager.
  48118. * @returns the current input manager
  48119. */
  48120. FreeCameraInputsManager.prototype.addTouch = function () {
  48121. this.add(new BABYLON.FreeCameraTouchInput());
  48122. return this;
  48123. };
  48124. /**
  48125. * Add virtual joystick input support to the input manager.
  48126. * @returns the current input manager
  48127. */
  48128. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48129. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48130. return this;
  48131. };
  48132. return FreeCameraInputsManager;
  48133. }(BABYLON.CameraInputsManager));
  48134. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48135. })(BABYLON || (BABYLON = {}));
  48136. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48137. var BABYLON;
  48138. (function (BABYLON) {
  48139. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  48140. // Forcing to use the Universal camera
  48141. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  48142. });
  48143. /**
  48144. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48145. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  48146. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48147. */
  48148. var FreeCamera = /** @class */ (function (_super) {
  48149. __extends(FreeCamera, _super);
  48150. /**
  48151. * Instantiates a Free Camera.
  48152. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48153. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  48154. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48155. * @param name Define the name of the camera in the scene
  48156. * @param position Define the start position of the camera in the scene
  48157. * @param scene Define the scene the camera belongs to
  48158. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48159. */
  48160. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48161. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48162. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48163. /**
  48164. * Define the collision ellipsoid of the camera.
  48165. * This is helpful to simulate a camera body like the player body around the camera
  48166. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48167. */
  48168. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48169. /**
  48170. * Define an offset for the position of the ellipsoid around the camera.
  48171. * This can be helpful to determine the center of the body near the gravity center of the body
  48172. * instead of its head.
  48173. */
  48174. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48175. /**
  48176. * Enable or disable collisions of the camera with the rest of the scene objects.
  48177. */
  48178. _this.checkCollisions = false;
  48179. /**
  48180. * Enable or disable gravity on the camera.
  48181. */
  48182. _this.applyGravity = false;
  48183. _this._needMoveForGravity = false;
  48184. _this._oldPosition = BABYLON.Vector3.Zero();
  48185. _this._diffPosition = BABYLON.Vector3.Zero();
  48186. _this._newPosition = BABYLON.Vector3.Zero();
  48187. // Collisions
  48188. _this._collisionMask = -1;
  48189. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48190. if (collidedMesh === void 0) { collidedMesh = null; }
  48191. //TODO move this to the collision coordinator!
  48192. if (_this.getScene().workerCollisions)
  48193. newPosition.multiplyInPlace(_this._collider._radius);
  48194. var updatePosition = function (newPos) {
  48195. _this._newPosition.copyFrom(newPos);
  48196. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48197. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48198. _this.position.addInPlace(_this._diffPosition);
  48199. if (_this.onCollide && collidedMesh) {
  48200. _this.onCollide(collidedMesh);
  48201. }
  48202. }
  48203. };
  48204. updatePosition(newPosition);
  48205. };
  48206. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48207. _this.inputs.addKeyboard().addMouse();
  48208. return _this;
  48209. }
  48210. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48211. /**
  48212. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48213. * Higher values reduce sensitivity.
  48214. */
  48215. get: function () {
  48216. var mouse = this.inputs.attached["mouse"];
  48217. if (mouse)
  48218. return mouse.angularSensibility;
  48219. return 0;
  48220. },
  48221. /**
  48222. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48223. * Higher values reduce sensitivity.
  48224. */
  48225. set: function (value) {
  48226. var mouse = this.inputs.attached["mouse"];
  48227. if (mouse)
  48228. mouse.angularSensibility = value;
  48229. },
  48230. enumerable: true,
  48231. configurable: true
  48232. });
  48233. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48234. /**
  48235. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48236. */
  48237. get: function () {
  48238. var keyboard = this.inputs.attached["keyboard"];
  48239. if (keyboard)
  48240. return keyboard.keysUp;
  48241. return [];
  48242. },
  48243. set: function (value) {
  48244. var keyboard = this.inputs.attached["keyboard"];
  48245. if (keyboard)
  48246. keyboard.keysUp = value;
  48247. },
  48248. enumerable: true,
  48249. configurable: true
  48250. });
  48251. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48252. /**
  48253. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48254. */
  48255. get: function () {
  48256. var keyboard = this.inputs.attached["keyboard"];
  48257. if (keyboard)
  48258. return keyboard.keysDown;
  48259. return [];
  48260. },
  48261. set: function (value) {
  48262. var keyboard = this.inputs.attached["keyboard"];
  48263. if (keyboard)
  48264. keyboard.keysDown = value;
  48265. },
  48266. enumerable: true,
  48267. configurable: true
  48268. });
  48269. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48270. /**
  48271. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48272. */
  48273. get: function () {
  48274. var keyboard = this.inputs.attached["keyboard"];
  48275. if (keyboard)
  48276. return keyboard.keysLeft;
  48277. return [];
  48278. },
  48279. set: function (value) {
  48280. var keyboard = this.inputs.attached["keyboard"];
  48281. if (keyboard)
  48282. keyboard.keysLeft = value;
  48283. },
  48284. enumerable: true,
  48285. configurable: true
  48286. });
  48287. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48288. /**
  48289. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48290. */
  48291. get: function () {
  48292. var keyboard = this.inputs.attached["keyboard"];
  48293. if (keyboard)
  48294. return keyboard.keysRight;
  48295. return [];
  48296. },
  48297. set: function (value) {
  48298. var keyboard = this.inputs.attached["keyboard"];
  48299. if (keyboard)
  48300. keyboard.keysRight = value;
  48301. },
  48302. enumerable: true,
  48303. configurable: true
  48304. });
  48305. /**
  48306. * Attached controls to the current camera.
  48307. * @param element Defines the element the controls should be listened from
  48308. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48309. */
  48310. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48311. this.inputs.attachElement(element, noPreventDefault);
  48312. };
  48313. /**
  48314. * Detach the current controls from the camera.
  48315. * The camera will stop reacting to inputs.
  48316. * @param element Defines the element to stop listening the inputs from
  48317. */
  48318. FreeCamera.prototype.detachControl = function (element) {
  48319. this.inputs.detachElement(element);
  48320. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48321. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48322. };
  48323. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48324. /**
  48325. * Define a collision mask to limit the list of object the camera can collide with
  48326. */
  48327. get: function () {
  48328. return this._collisionMask;
  48329. },
  48330. set: function (mask) {
  48331. this._collisionMask = !isNaN(mask) ? mask : -1;
  48332. },
  48333. enumerable: true,
  48334. configurable: true
  48335. });
  48336. /** @hidden */
  48337. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48338. var globalPosition;
  48339. if (this.parent) {
  48340. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48341. }
  48342. else {
  48343. globalPosition = this.position;
  48344. }
  48345. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48346. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48347. if (!this._collider) {
  48348. this._collider = new BABYLON.Collider();
  48349. }
  48350. this._collider._radius = this.ellipsoid;
  48351. this._collider.collisionMask = this._collisionMask;
  48352. //no need for clone, as long as gravity is not on.
  48353. var actualDisplacement = displacement;
  48354. //add gravity to the direction to prevent the dual-collision checking
  48355. if (this.applyGravity) {
  48356. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48357. actualDisplacement = displacement.add(this.getScene().gravity);
  48358. }
  48359. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48360. };
  48361. /** @hidden */
  48362. FreeCamera.prototype._checkInputs = function () {
  48363. if (!this._localDirection) {
  48364. this._localDirection = BABYLON.Vector3.Zero();
  48365. this._transformedDirection = BABYLON.Vector3.Zero();
  48366. }
  48367. this.inputs.checkInputs();
  48368. _super.prototype._checkInputs.call(this);
  48369. };
  48370. /** @hidden */
  48371. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48372. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48373. };
  48374. /** @hidden */
  48375. FreeCamera.prototype._updatePosition = function () {
  48376. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48377. this._collideWithWorld(this.cameraDirection);
  48378. }
  48379. else {
  48380. _super.prototype._updatePosition.call(this);
  48381. }
  48382. };
  48383. /**
  48384. * Destroy the camera and release the current resources hold by it.
  48385. */
  48386. FreeCamera.prototype.dispose = function () {
  48387. this.inputs.clear();
  48388. _super.prototype.dispose.call(this);
  48389. };
  48390. /**
  48391. * Gets the current object class name.
  48392. * @return the class name
  48393. */
  48394. FreeCamera.prototype.getClassName = function () {
  48395. return "FreeCamera";
  48396. };
  48397. __decorate([
  48398. BABYLON.serializeAsVector3()
  48399. ], FreeCamera.prototype, "ellipsoid", void 0);
  48400. __decorate([
  48401. BABYLON.serializeAsVector3()
  48402. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48403. __decorate([
  48404. BABYLON.serialize()
  48405. ], FreeCamera.prototype, "checkCollisions", void 0);
  48406. __decorate([
  48407. BABYLON.serialize()
  48408. ], FreeCamera.prototype, "applyGravity", void 0);
  48409. return FreeCamera;
  48410. }(BABYLON.TargetCamera));
  48411. BABYLON.FreeCamera = FreeCamera;
  48412. })(BABYLON || (BABYLON = {}));
  48413. //# sourceMappingURL=babylon.freeCamera.js.map
  48414. var BABYLON;
  48415. (function (BABYLON) {
  48416. /**
  48417. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  48418. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48419. */
  48420. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48421. function ArcRotateCameraKeyboardMoveInput() {
  48422. /**
  48423. * Defines the list of key codes associated with the up action (increase alpha)
  48424. */
  48425. this.keysUp = [38];
  48426. /**
  48427. * Defines the list of key codes associated with the down action (decrease alpha)
  48428. */
  48429. this.keysDown = [40];
  48430. /**
  48431. * Defines the list of key codes associated with the left action (increase beta)
  48432. */
  48433. this.keysLeft = [37];
  48434. /**
  48435. * Defines the list of key codes associated with the right action (decrease beta)
  48436. */
  48437. this.keysRight = [39];
  48438. /**
  48439. * Defines the list of key codes associated with the reset action.
  48440. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  48441. */
  48442. this.keysReset = [220];
  48443. /**
  48444. * Defines the panning sensibility of the inputs.
  48445. * (How fast is the camera paning)
  48446. */
  48447. this.panningSensibility = 50.0;
  48448. /**
  48449. * Defines the zooming sensibility of the inputs.
  48450. * (How fast is the camera zooming)
  48451. */
  48452. this.zoomingSensibility = 25.0;
  48453. /**
  48454. * Defines wether maintaining the alt key down switch the movement mode from
  48455. * orientation to zoom.
  48456. */
  48457. this.useAltToZoom = true;
  48458. /**
  48459. * Rotation speed of the camera
  48460. */
  48461. this.angularSpeed = 0.01;
  48462. this._keys = new Array();
  48463. }
  48464. /**
  48465. * Attach the input controls to a specific dom element to get the input from.
  48466. * @param element Defines the element the controls should be listened from
  48467. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48468. */
  48469. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48470. var _this = this;
  48471. if (this._onCanvasBlurObserver) {
  48472. return;
  48473. }
  48474. this._scene = this.camera.getScene();
  48475. this._engine = this._scene.getEngine();
  48476. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48477. _this._keys = [];
  48478. });
  48479. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48480. var evt = info.event;
  48481. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48482. _this._ctrlPressed = evt.ctrlKey;
  48483. _this._altPressed = evt.altKey;
  48484. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48485. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48486. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48487. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48488. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48489. var index = _this._keys.indexOf(evt.keyCode);
  48490. if (index === -1) {
  48491. _this._keys.push(evt.keyCode);
  48492. }
  48493. if (evt.preventDefault) {
  48494. if (!noPreventDefault) {
  48495. evt.preventDefault();
  48496. }
  48497. }
  48498. }
  48499. }
  48500. else {
  48501. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48502. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48503. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48504. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48505. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48506. var index = _this._keys.indexOf(evt.keyCode);
  48507. if (index >= 0) {
  48508. _this._keys.splice(index, 1);
  48509. }
  48510. if (evt.preventDefault) {
  48511. if (!noPreventDefault) {
  48512. evt.preventDefault();
  48513. }
  48514. }
  48515. }
  48516. }
  48517. });
  48518. };
  48519. /**
  48520. * Detach the current controls from the specified dom element.
  48521. * @param element Defines the element to stop listening the inputs from
  48522. */
  48523. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48524. if (this._scene) {
  48525. if (this._onKeyboardObserver) {
  48526. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48527. }
  48528. if (this._onCanvasBlurObserver) {
  48529. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48530. }
  48531. this._onKeyboardObserver = null;
  48532. this._onCanvasBlurObserver = null;
  48533. }
  48534. this._keys = [];
  48535. };
  48536. /**
  48537. * Update the current camera state depending on the inputs that have been used this frame.
  48538. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48539. */
  48540. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48541. if (this._onKeyboardObserver) {
  48542. var camera = this.camera;
  48543. for (var index = 0; index < this._keys.length; index++) {
  48544. var keyCode = this._keys[index];
  48545. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48546. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48547. camera.inertialPanningX -= 1 / this.panningSensibility;
  48548. }
  48549. else {
  48550. camera.inertialAlphaOffset -= this.angularSpeed;
  48551. }
  48552. }
  48553. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48554. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48555. camera.inertialPanningY += 1 / this.panningSensibility;
  48556. }
  48557. else if (this._altPressed && this.useAltToZoom) {
  48558. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48559. }
  48560. else {
  48561. camera.inertialBetaOffset -= this.angularSpeed;
  48562. }
  48563. }
  48564. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48565. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48566. camera.inertialPanningX += 1 / this.panningSensibility;
  48567. }
  48568. else {
  48569. camera.inertialAlphaOffset += this.angularSpeed;
  48570. }
  48571. }
  48572. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48573. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48574. camera.inertialPanningY -= 1 / this.panningSensibility;
  48575. }
  48576. else if (this._altPressed && this.useAltToZoom) {
  48577. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48578. }
  48579. else {
  48580. camera.inertialBetaOffset += this.angularSpeed;
  48581. }
  48582. }
  48583. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48584. if (camera.useInputToRestoreState) {
  48585. camera.restoreState();
  48586. }
  48587. }
  48588. }
  48589. }
  48590. };
  48591. /**
  48592. * Gets the class name of the current intput.
  48593. * @returns the class name
  48594. */
  48595. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48596. return "ArcRotateCameraKeyboardMoveInput";
  48597. };
  48598. /**
  48599. * Get the friendly name associated with the input class.
  48600. * @returns the input friendly name
  48601. */
  48602. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48603. return "keyboard";
  48604. };
  48605. __decorate([
  48606. BABYLON.serialize()
  48607. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48608. __decorate([
  48609. BABYLON.serialize()
  48610. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48611. __decorate([
  48612. BABYLON.serialize()
  48613. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48614. __decorate([
  48615. BABYLON.serialize()
  48616. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48617. __decorate([
  48618. BABYLON.serialize()
  48619. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48620. __decorate([
  48621. BABYLON.serialize()
  48622. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48623. __decorate([
  48624. BABYLON.serialize()
  48625. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48626. __decorate([
  48627. BABYLON.serialize()
  48628. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48629. __decorate([
  48630. BABYLON.serialize()
  48631. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  48632. return ArcRotateCameraKeyboardMoveInput;
  48633. }());
  48634. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48635. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48636. })(BABYLON || (BABYLON = {}));
  48637. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48638. var BABYLON;
  48639. (function (BABYLON) {
  48640. /**
  48641. * Manage the mouse wheel inputs to control an arc rotate camera.
  48642. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48643. */
  48644. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48645. function ArcRotateCameraMouseWheelInput() {
  48646. /**
  48647. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48648. */
  48649. this.wheelPrecision = 3.0;
  48650. /**
  48651. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48652. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48653. */
  48654. this.wheelDeltaPercentage = 0;
  48655. }
  48656. /**
  48657. * Attach the input controls to a specific dom element to get the input from.
  48658. * @param element Defines the element the controls should be listened from
  48659. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48660. */
  48661. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48662. var _this = this;
  48663. this._wheel = function (p, s) {
  48664. //sanity check - this should be a PointerWheel event.
  48665. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48666. return;
  48667. var event = p.event;
  48668. var delta = 0;
  48669. if (event.wheelDelta) {
  48670. if (_this.wheelDeltaPercentage) {
  48671. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48672. if (event.wheelDelta > 0) {
  48673. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48674. }
  48675. else {
  48676. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48677. }
  48678. }
  48679. else {
  48680. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48681. }
  48682. }
  48683. else if (event.detail) {
  48684. delta = -event.detail / _this.wheelPrecision;
  48685. }
  48686. if (delta)
  48687. _this.camera.inertialRadiusOffset += delta;
  48688. if (event.preventDefault) {
  48689. if (!noPreventDefault) {
  48690. event.preventDefault();
  48691. }
  48692. }
  48693. };
  48694. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48695. };
  48696. /**
  48697. * Detach the current controls from the specified dom element.
  48698. * @param element Defines the element to stop listening the inputs from
  48699. */
  48700. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48701. if (this._observer && element) {
  48702. this.camera.getScene().onPointerObservable.remove(this._observer);
  48703. this._observer = null;
  48704. this._wheel = null;
  48705. }
  48706. };
  48707. /**
  48708. * Gets the class name of the current intput.
  48709. * @returns the class name
  48710. */
  48711. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48712. return "ArcRotateCameraMouseWheelInput";
  48713. };
  48714. /**
  48715. * Get the friendly name associated with the input class.
  48716. * @returns the input friendly name
  48717. */
  48718. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48719. return "mousewheel";
  48720. };
  48721. __decorate([
  48722. BABYLON.serialize()
  48723. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48724. __decorate([
  48725. BABYLON.serialize()
  48726. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48727. return ArcRotateCameraMouseWheelInput;
  48728. }());
  48729. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48730. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48731. })(BABYLON || (BABYLON = {}));
  48732. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48733. var BABYLON;
  48734. (function (BABYLON) {
  48735. /**
  48736. * Manage the pointers inputs to control an arc rotate camera.
  48737. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48738. */
  48739. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48740. function ArcRotateCameraPointersInput() {
  48741. /**
  48742. * Defines the buttons associated with the input to handle camera move.
  48743. */
  48744. this.buttons = [0, 1, 2];
  48745. /**
  48746. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48747. */
  48748. this.angularSensibilityX = 1000.0;
  48749. /**
  48750. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48751. */
  48752. this.angularSensibilityY = 1000.0;
  48753. /**
  48754. * Defines the pointer pinch precision or how fast is the camera zooming.
  48755. */
  48756. this.pinchPrecision = 12.0;
  48757. /**
  48758. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48759. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48760. */
  48761. this.pinchDeltaPercentage = 0;
  48762. /**
  48763. * Defines the pointer panning sensibility or how fast is the camera moving.
  48764. */
  48765. this.panningSensibility = 1000.0;
  48766. /**
  48767. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  48768. */
  48769. this.multiTouchPanning = true;
  48770. /**
  48771. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  48772. */
  48773. this.multiTouchPanAndZoom = true;
  48774. /**
  48775. * Revers pinch action direction.
  48776. */
  48777. this.pinchInwards = true;
  48778. this._isPanClick = false;
  48779. }
  48780. /**
  48781. * Attach the input controls to a specific dom element to get the input from.
  48782. * @param element Defines the element the controls should be listened from
  48783. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48784. */
  48785. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48786. var _this = this;
  48787. var engine = this.camera.getEngine();
  48788. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48789. var pointA = null;
  48790. var pointB = null;
  48791. var previousPinchSquaredDistance = 0;
  48792. var initialDistance = 0;
  48793. var twoFingerActivityCount = 0;
  48794. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48795. this._pointerInput = function (p, s) {
  48796. var evt = p.event;
  48797. var isTouch = p.event.pointerType === "touch";
  48798. if (engine.isInVRExclusivePointerMode) {
  48799. return;
  48800. }
  48801. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48802. return;
  48803. }
  48804. var srcElement = (evt.srcElement || evt.target);
  48805. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48806. try {
  48807. srcElement.setPointerCapture(evt.pointerId);
  48808. }
  48809. catch (e) {
  48810. //Nothing to do with the error. Execution will continue.
  48811. }
  48812. // Manage panning with pan button click
  48813. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48814. // manage pointers
  48815. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48816. if (pointA === null) {
  48817. pointA = cacheSoloPointer;
  48818. }
  48819. else if (pointB === null) {
  48820. pointB = cacheSoloPointer;
  48821. }
  48822. if (!noPreventDefault) {
  48823. evt.preventDefault();
  48824. element.focus();
  48825. }
  48826. }
  48827. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48828. if (_this.camera.useInputToRestoreState) {
  48829. _this.camera.restoreState();
  48830. }
  48831. }
  48832. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48833. try {
  48834. srcElement.releasePointerCapture(evt.pointerId);
  48835. }
  48836. catch (e) {
  48837. //Nothing to do with the error.
  48838. }
  48839. cacheSoloPointer = null;
  48840. previousPinchSquaredDistance = 0;
  48841. previousMultiTouchPanPosition.isPaning = false;
  48842. previousMultiTouchPanPosition.isPinching = false;
  48843. twoFingerActivityCount = 0;
  48844. initialDistance = 0;
  48845. if (!isTouch) {
  48846. pointB = null; // Mouse and pen are mono pointer
  48847. }
  48848. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48849. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48850. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48851. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48852. if (engine._badOS) {
  48853. pointA = pointB = null;
  48854. }
  48855. else {
  48856. //only remove the impacted pointer in case of multitouch allowing on most
  48857. //platforms switching from rotate to zoom and pan seamlessly.
  48858. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48859. pointA = pointB;
  48860. pointB = null;
  48861. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48862. }
  48863. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48864. pointB = null;
  48865. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48866. }
  48867. else {
  48868. pointA = pointB = null;
  48869. }
  48870. }
  48871. if (!noPreventDefault) {
  48872. evt.preventDefault();
  48873. }
  48874. }
  48875. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48876. if (!noPreventDefault) {
  48877. evt.preventDefault();
  48878. }
  48879. // One button down
  48880. if (pointA && pointB === null && cacheSoloPointer) {
  48881. if (_this.panningSensibility !== 0 &&
  48882. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48883. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48884. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48885. }
  48886. else {
  48887. var offsetX = evt.clientX - cacheSoloPointer.x;
  48888. var offsetY = evt.clientY - cacheSoloPointer.y;
  48889. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48890. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48891. }
  48892. cacheSoloPointer.x = evt.clientX;
  48893. cacheSoloPointer.y = evt.clientY;
  48894. }
  48895. // Two buttons down: pinch/pan
  48896. else if (pointA && pointB) {
  48897. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48898. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48899. ed.x = evt.clientX;
  48900. ed.y = evt.clientY;
  48901. var direction = _this.pinchInwards ? 1 : -1;
  48902. var distX = pointA.x - pointB.x;
  48903. var distY = pointA.y - pointB.y;
  48904. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48905. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48906. if (previousPinchSquaredDistance === 0) {
  48907. initialDistance = pinchDistance;
  48908. previousPinchSquaredDistance = pinchSquaredDistance;
  48909. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48910. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48911. return;
  48912. }
  48913. if (_this.multiTouchPanAndZoom) {
  48914. if (_this.pinchDeltaPercentage) {
  48915. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48916. }
  48917. else {
  48918. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48919. (_this.pinchPrecision *
  48920. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48921. direction);
  48922. }
  48923. if (_this.panningSensibility !== 0) {
  48924. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48925. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48926. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48927. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48928. previousMultiTouchPanPosition.x = pointersCenterX;
  48929. previousMultiTouchPanPosition.y = pointersCenterY;
  48930. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48931. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48932. }
  48933. }
  48934. else {
  48935. twoFingerActivityCount++;
  48936. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48937. if (_this.pinchDeltaPercentage) {
  48938. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48939. }
  48940. else {
  48941. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48942. (_this.pinchPrecision *
  48943. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48944. direction);
  48945. }
  48946. previousMultiTouchPanPosition.isPaning = false;
  48947. previousMultiTouchPanPosition.isPinching = true;
  48948. }
  48949. else {
  48950. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48951. if (!previousMultiTouchPanPosition.isPaning) {
  48952. previousMultiTouchPanPosition.isPaning = true;
  48953. previousMultiTouchPanPosition.isPinching = false;
  48954. previousMultiTouchPanPosition.x = ed.x;
  48955. previousMultiTouchPanPosition.y = ed.y;
  48956. return;
  48957. }
  48958. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48959. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48960. }
  48961. }
  48962. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48963. previousMultiTouchPanPosition.x = ed.x;
  48964. previousMultiTouchPanPosition.y = ed.y;
  48965. }
  48966. }
  48967. previousPinchSquaredDistance = pinchSquaredDistance;
  48968. }
  48969. }
  48970. };
  48971. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  48972. this._onContextMenu = function (evt) {
  48973. evt.preventDefault();
  48974. };
  48975. if (!this.camera._useCtrlForPanning) {
  48976. element.addEventListener("contextmenu", this._onContextMenu, false);
  48977. }
  48978. this._onLostFocus = function () {
  48979. //this._keys = [];
  48980. pointA = pointB = null;
  48981. previousPinchSquaredDistance = 0;
  48982. previousMultiTouchPanPosition.isPaning = false;
  48983. previousMultiTouchPanPosition.isPinching = false;
  48984. twoFingerActivityCount = 0;
  48985. cacheSoloPointer = null;
  48986. initialDistance = 0;
  48987. };
  48988. this._onMouseMove = function (evt) {
  48989. if (!engine.isPointerLock) {
  48990. return;
  48991. }
  48992. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48993. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48994. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48995. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48996. if (!noPreventDefault) {
  48997. evt.preventDefault();
  48998. }
  48999. };
  49000. this._onGestureStart = function (e) {
  49001. if (window.MSGesture === undefined) {
  49002. return;
  49003. }
  49004. if (!_this._MSGestureHandler) {
  49005. _this._MSGestureHandler = new MSGesture();
  49006. _this._MSGestureHandler.target = element;
  49007. }
  49008. _this._MSGestureHandler.addPointer(e.pointerId);
  49009. };
  49010. this._onGesture = function (e) {
  49011. _this.camera.radius *= e.scale;
  49012. if (e.preventDefault) {
  49013. if (!noPreventDefault) {
  49014. e.stopPropagation();
  49015. e.preventDefault();
  49016. }
  49017. }
  49018. };
  49019. element.addEventListener("mousemove", this._onMouseMove, false);
  49020. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  49021. element.addEventListener("MSGestureChange", this._onGesture, false);
  49022. BABYLON.Tools.RegisterTopRootEvents([
  49023. { name: "blur", handler: this._onLostFocus }
  49024. ]);
  49025. };
  49026. /**
  49027. * Detach the current controls from the specified dom element.
  49028. * @param element Defines the element to stop listening the inputs from
  49029. */
  49030. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  49031. if (this._onLostFocus) {
  49032. BABYLON.Tools.UnregisterTopRootEvents([
  49033. { name: "blur", handler: this._onLostFocus }
  49034. ]);
  49035. }
  49036. if (element && this._observer) {
  49037. this.camera.getScene().onPointerObservable.remove(this._observer);
  49038. this._observer = null;
  49039. if (this._onContextMenu) {
  49040. element.removeEventListener("contextmenu", this._onContextMenu);
  49041. }
  49042. if (this._onMouseMove) {
  49043. element.removeEventListener("mousemove", this._onMouseMove);
  49044. }
  49045. if (this._onGestureStart) {
  49046. element.removeEventListener("MSPointerDown", this._onGestureStart);
  49047. }
  49048. if (this._onGesture) {
  49049. element.removeEventListener("MSGestureChange", this._onGesture);
  49050. }
  49051. this._isPanClick = false;
  49052. this.pinchInwards = true;
  49053. this._onMouseMove = null;
  49054. this._onGestureStart = null;
  49055. this._onGesture = null;
  49056. this._MSGestureHandler = null;
  49057. this._onLostFocus = null;
  49058. this._onContextMenu = null;
  49059. }
  49060. };
  49061. /**
  49062. * Gets the class name of the current intput.
  49063. * @returns the class name
  49064. */
  49065. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  49066. return "ArcRotateCameraPointersInput";
  49067. };
  49068. /**
  49069. * Get the friendly name associated with the input class.
  49070. * @returns the input friendly name
  49071. */
  49072. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  49073. return "pointers";
  49074. };
  49075. __decorate([
  49076. BABYLON.serialize()
  49077. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  49078. __decorate([
  49079. BABYLON.serialize()
  49080. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  49081. __decorate([
  49082. BABYLON.serialize()
  49083. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  49084. __decorate([
  49085. BABYLON.serialize()
  49086. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  49087. __decorate([
  49088. BABYLON.serialize()
  49089. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  49090. __decorate([
  49091. BABYLON.serialize()
  49092. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  49093. __decorate([
  49094. BABYLON.serialize()
  49095. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  49096. __decorate([
  49097. BABYLON.serialize()
  49098. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  49099. return ArcRotateCameraPointersInput;
  49100. }());
  49101. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  49102. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  49103. })(BABYLON || (BABYLON = {}));
  49104. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  49105. var BABYLON;
  49106. (function (BABYLON) {
  49107. /**
  49108. * Default Inputs manager for the ArcRotateCamera.
  49109. * It groups all the default supported inputs for ease of use.
  49110. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49111. */
  49112. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  49113. __extends(ArcRotateCameraInputsManager, _super);
  49114. /**
  49115. * Instantiates a new ArcRotateCameraInputsManager.
  49116. * @param camera Defines the camera the inputs belong to
  49117. */
  49118. function ArcRotateCameraInputsManager(camera) {
  49119. return _super.call(this, camera) || this;
  49120. }
  49121. /**
  49122. * Add mouse wheel input support to the input manager.
  49123. * @returns the current input manager
  49124. */
  49125. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  49126. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  49127. return this;
  49128. };
  49129. /**
  49130. * Add pointers input support to the input manager.
  49131. * @returns the current input manager
  49132. */
  49133. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  49134. this.add(new BABYLON.ArcRotateCameraPointersInput());
  49135. return this;
  49136. };
  49137. /**
  49138. * Add keyboard input support to the input manager.
  49139. * @returns the current input manager
  49140. */
  49141. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  49142. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  49143. return this;
  49144. };
  49145. /**
  49146. * Add orientation input support to the input manager.
  49147. * @returns the current input manager
  49148. */
  49149. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  49150. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  49151. return this;
  49152. };
  49153. return ArcRotateCameraInputsManager;
  49154. }(BABYLON.CameraInputsManager));
  49155. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  49156. })(BABYLON || (BABYLON = {}));
  49157. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  49158. var BABYLON;
  49159. (function (BABYLON) {
  49160. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  49161. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  49162. });
  49163. /**
  49164. * This represents an orbital type of camera.
  49165. *
  49166. * 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.
  49167. * 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.
  49168. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  49169. */
  49170. var ArcRotateCamera = /** @class */ (function (_super) {
  49171. __extends(ArcRotateCamera, _super);
  49172. /**
  49173. * Instantiates a new ArcRotateCamera in a given scene
  49174. * @param name Defines the name of the camera
  49175. * @param alpha Defines the camera rotation along the logitudinal axis
  49176. * @param beta Defines the camera rotation along the latitudinal axis
  49177. * @param radius Defines the camera distance from its target
  49178. * @param target Defines the camera target
  49179. * @param scene Defines the scene the camera belongs to
  49180. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49181. */
  49182. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  49183. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49184. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  49185. /**
  49186. * Current inertia value on the longitudinal axis.
  49187. * The bigger this number the longer it will take for the camera to stop.
  49188. */
  49189. _this.inertialAlphaOffset = 0;
  49190. /**
  49191. * Current inertia value on the latitudinal axis.
  49192. * The bigger this number the longer it will take for the camera to stop.
  49193. */
  49194. _this.inertialBetaOffset = 0;
  49195. /**
  49196. * Current inertia value on the radius axis.
  49197. * The bigger this number the longer it will take for the camera to stop.
  49198. */
  49199. _this.inertialRadiusOffset = 0;
  49200. /**
  49201. * Minimum allowed angle on the longitudinal axis.
  49202. * This can help limiting how the Camera is able to move in the scene.
  49203. */
  49204. _this.lowerAlphaLimit = null;
  49205. /**
  49206. * Maximum allowed angle on the longitudinal axis.
  49207. * This can help limiting how the Camera is able to move in the scene.
  49208. */
  49209. _this.upperAlphaLimit = null;
  49210. /**
  49211. * Minimum allowed angle on the latitudinal axis.
  49212. * This can help limiting how the Camera is able to move in the scene.
  49213. */
  49214. _this.lowerBetaLimit = 0.01;
  49215. /**
  49216. * Maximum allowed angle on the latitudinal axis.
  49217. * This can help limiting how the Camera is able to move in the scene.
  49218. */
  49219. _this.upperBetaLimit = Math.PI;
  49220. /**
  49221. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49222. * This can help limiting how the Camera is able to move in the scene.
  49223. */
  49224. _this.lowerRadiusLimit = null;
  49225. /**
  49226. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49227. * This can help limiting how the Camera is able to move in the scene.
  49228. */
  49229. _this.upperRadiusLimit = null;
  49230. /**
  49231. * Defines the current inertia value used during panning of the camera along the X axis.
  49232. */
  49233. _this.inertialPanningX = 0;
  49234. /**
  49235. * Defines the current inertia value used during panning of the camera along the Y axis.
  49236. */
  49237. _this.inertialPanningY = 0;
  49238. /**
  49239. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49240. * Basically if your fingers moves away from more than this distance you will be considered
  49241. * in pinch mode.
  49242. */
  49243. _this.pinchToPanMaxDistance = 20;
  49244. /**
  49245. * Defines the maximum distance the camera can pan.
  49246. * This could help keeping the cammera always in your scene.
  49247. */
  49248. _this.panningDistanceLimit = null;
  49249. /**
  49250. * Defines the target of the camera before paning.
  49251. */
  49252. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49253. /**
  49254. * Defines the value of the inertia used during panning.
  49255. * 0 would mean stop inertia and one would mean no decelleration at all.
  49256. */
  49257. _this.panningInertia = 0.9;
  49258. //-- end properties for backward compatibility for inputs
  49259. /**
  49260. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49261. */
  49262. _this.zoomOnFactor = 1;
  49263. /**
  49264. * Defines a screen offset for the camera position.
  49265. */
  49266. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49267. /**
  49268. * Allows the camera to be completely reversed.
  49269. * If false the camera can not arrive upside down.
  49270. */
  49271. _this.allowUpsideDown = true;
  49272. /**
  49273. * Define if double tap/click is used to restore the previously saved state of the camera.
  49274. */
  49275. _this.useInputToRestoreState = true;
  49276. /** @hidden */
  49277. _this._viewMatrix = new BABYLON.Matrix();
  49278. /**
  49279. * Defines the allowed panning axis.
  49280. */
  49281. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49282. /**
  49283. * Observable triggered when the mesh target has been changed on the camera.
  49284. */
  49285. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49286. /**
  49287. * Defines whether the camera should check collision with the objects oh the scene.
  49288. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49289. */
  49290. _this.checkCollisions = false;
  49291. /**
  49292. * Defines the collision radius of the camera.
  49293. * This simulates a sphere around the camera.
  49294. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49295. */
  49296. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49297. _this._previousPosition = BABYLON.Vector3.Zero();
  49298. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49299. _this._newPosition = BABYLON.Vector3.Zero();
  49300. _this._computationVector = BABYLON.Vector3.Zero();
  49301. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49302. if (collidedMesh === void 0) { collidedMesh = null; }
  49303. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49304. newPosition.multiplyInPlace(_this._collider._radius);
  49305. }
  49306. if (!collidedMesh) {
  49307. _this._previousPosition.copyFrom(_this.position);
  49308. }
  49309. else {
  49310. _this.setPosition(newPosition);
  49311. if (_this.onCollide) {
  49312. _this.onCollide(collidedMesh);
  49313. }
  49314. }
  49315. // Recompute because of constraints
  49316. var cosa = Math.cos(_this.alpha);
  49317. var sina = Math.sin(_this.alpha);
  49318. var cosb = Math.cos(_this.beta);
  49319. var sinb = Math.sin(_this.beta);
  49320. if (sinb === 0) {
  49321. sinb = 0.0001;
  49322. }
  49323. var target = _this._getTargetPosition();
  49324. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49325. target.addToRef(_this._computationVector, _this._newPosition);
  49326. _this.position.copyFrom(_this._newPosition);
  49327. var up = _this.upVector;
  49328. if (_this.allowUpsideDown && _this.beta < 0) {
  49329. up = up.clone();
  49330. up = up.negate();
  49331. }
  49332. _this._computeViewMatrix(_this.position, target, up);
  49333. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49334. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49335. _this._collisionTriggered = false;
  49336. };
  49337. _this._target = BABYLON.Vector3.Zero();
  49338. if (target) {
  49339. _this.setTarget(target);
  49340. }
  49341. _this.alpha = alpha;
  49342. _this.beta = beta;
  49343. _this.radius = radius;
  49344. _this.getViewMatrix();
  49345. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  49346. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  49347. return _this;
  49348. }
  49349. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  49350. /**
  49351. * Defines the target point of the camera.
  49352. * The camera looks towards it form the radius distance.
  49353. */
  49354. get: function () {
  49355. return this._target;
  49356. },
  49357. set: function (value) {
  49358. this.setTarget(value);
  49359. },
  49360. enumerable: true,
  49361. configurable: true
  49362. });
  49363. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  49364. //-- begin properties for backward compatibility for inputs
  49365. /**
  49366. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49367. */
  49368. get: function () {
  49369. var pointers = this.inputs.attached["pointers"];
  49370. if (pointers)
  49371. return pointers.angularSensibilityX;
  49372. return 0;
  49373. },
  49374. set: function (value) {
  49375. var pointers = this.inputs.attached["pointers"];
  49376. if (pointers) {
  49377. pointers.angularSensibilityX = value;
  49378. }
  49379. },
  49380. enumerable: true,
  49381. configurable: true
  49382. });
  49383. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  49384. /**
  49385. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49386. */
  49387. get: function () {
  49388. var pointers = this.inputs.attached["pointers"];
  49389. if (pointers)
  49390. return pointers.angularSensibilityY;
  49391. return 0;
  49392. },
  49393. set: function (value) {
  49394. var pointers = this.inputs.attached["pointers"];
  49395. if (pointers) {
  49396. pointers.angularSensibilityY = value;
  49397. }
  49398. },
  49399. enumerable: true,
  49400. configurable: true
  49401. });
  49402. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  49403. /**
  49404. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  49405. */
  49406. get: function () {
  49407. var pointers = this.inputs.attached["pointers"];
  49408. if (pointers)
  49409. return pointers.pinchPrecision;
  49410. return 0;
  49411. },
  49412. set: function (value) {
  49413. var pointers = this.inputs.attached["pointers"];
  49414. if (pointers) {
  49415. pointers.pinchPrecision = value;
  49416. }
  49417. },
  49418. enumerable: true,
  49419. configurable: true
  49420. });
  49421. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  49422. /**
  49423. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  49424. * It will be used instead of pinchDeltaPrecision if different from 0.
  49425. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49426. */
  49427. get: function () {
  49428. var pointers = this.inputs.attached["pointers"];
  49429. if (pointers)
  49430. return pointers.pinchDeltaPercentage;
  49431. return 0;
  49432. },
  49433. set: function (value) {
  49434. var pointers = this.inputs.attached["pointers"];
  49435. if (pointers) {
  49436. pointers.pinchDeltaPercentage = value;
  49437. }
  49438. },
  49439. enumerable: true,
  49440. configurable: true
  49441. });
  49442. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  49443. /**
  49444. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  49445. */
  49446. get: function () {
  49447. var pointers = this.inputs.attached["pointers"];
  49448. if (pointers)
  49449. return pointers.panningSensibility;
  49450. return 0;
  49451. },
  49452. set: function (value) {
  49453. var pointers = this.inputs.attached["pointers"];
  49454. if (pointers) {
  49455. pointers.panningSensibility = value;
  49456. }
  49457. },
  49458. enumerable: true,
  49459. configurable: true
  49460. });
  49461. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  49462. /**
  49463. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  49464. */
  49465. get: function () {
  49466. var keyboard = this.inputs.attached["keyboard"];
  49467. if (keyboard)
  49468. return keyboard.keysUp;
  49469. return [];
  49470. },
  49471. set: function (value) {
  49472. var keyboard = this.inputs.attached["keyboard"];
  49473. if (keyboard)
  49474. keyboard.keysUp = value;
  49475. },
  49476. enumerable: true,
  49477. configurable: true
  49478. });
  49479. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49480. /**
  49481. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  49482. */
  49483. get: function () {
  49484. var keyboard = this.inputs.attached["keyboard"];
  49485. if (keyboard)
  49486. return keyboard.keysDown;
  49487. return [];
  49488. },
  49489. set: function (value) {
  49490. var keyboard = this.inputs.attached["keyboard"];
  49491. if (keyboard)
  49492. keyboard.keysDown = value;
  49493. },
  49494. enumerable: true,
  49495. configurable: true
  49496. });
  49497. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49498. /**
  49499. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  49500. */
  49501. get: function () {
  49502. var keyboard = this.inputs.attached["keyboard"];
  49503. if (keyboard)
  49504. return keyboard.keysLeft;
  49505. return [];
  49506. },
  49507. set: function (value) {
  49508. var keyboard = this.inputs.attached["keyboard"];
  49509. if (keyboard)
  49510. keyboard.keysLeft = value;
  49511. },
  49512. enumerable: true,
  49513. configurable: true
  49514. });
  49515. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49516. /**
  49517. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  49518. */
  49519. get: function () {
  49520. var keyboard = this.inputs.attached["keyboard"];
  49521. if (keyboard)
  49522. return keyboard.keysRight;
  49523. return [];
  49524. },
  49525. set: function (value) {
  49526. var keyboard = this.inputs.attached["keyboard"];
  49527. if (keyboard)
  49528. keyboard.keysRight = value;
  49529. },
  49530. enumerable: true,
  49531. configurable: true
  49532. });
  49533. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49534. /**
  49535. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49536. */
  49537. get: function () {
  49538. var mousewheel = this.inputs.attached["mousewheel"];
  49539. if (mousewheel)
  49540. return mousewheel.wheelPrecision;
  49541. return 0;
  49542. },
  49543. set: function (value) {
  49544. var mousewheel = this.inputs.attached["mousewheel"];
  49545. if (mousewheel)
  49546. mousewheel.wheelPrecision = value;
  49547. },
  49548. enumerable: true,
  49549. configurable: true
  49550. });
  49551. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49552. /**
  49553. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  49554. * It will be used instead of pinchDeltaPrecision if different from 0.
  49555. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49556. */
  49557. get: function () {
  49558. var mousewheel = this.inputs.attached["mousewheel"];
  49559. if (mousewheel)
  49560. return mousewheel.wheelDeltaPercentage;
  49561. return 0;
  49562. },
  49563. set: function (value) {
  49564. var mousewheel = this.inputs.attached["mousewheel"];
  49565. if (mousewheel)
  49566. mousewheel.wheelDeltaPercentage = value;
  49567. },
  49568. enumerable: true,
  49569. configurable: true
  49570. });
  49571. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49572. /**
  49573. * Gets the bouncing behavior of the camera if it has been enabled.
  49574. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  49575. */
  49576. get: function () {
  49577. return this._bouncingBehavior;
  49578. },
  49579. enumerable: true,
  49580. configurable: true
  49581. });
  49582. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49583. /**
  49584. * Defines if the bouncing behavior of the camera is enabled on the camera.
  49585. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  49586. */
  49587. get: function () {
  49588. return this._bouncingBehavior != null;
  49589. },
  49590. set: function (value) {
  49591. if (value === this.useBouncingBehavior) {
  49592. return;
  49593. }
  49594. if (value) {
  49595. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49596. this.addBehavior(this._bouncingBehavior);
  49597. }
  49598. else if (this._bouncingBehavior) {
  49599. this.removeBehavior(this._bouncingBehavior);
  49600. this._bouncingBehavior = null;
  49601. }
  49602. },
  49603. enumerable: true,
  49604. configurable: true
  49605. });
  49606. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49607. /**
  49608. * Gets the framing behavior of the camera if it has been enabled.
  49609. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  49610. */
  49611. get: function () {
  49612. return this._framingBehavior;
  49613. },
  49614. enumerable: true,
  49615. configurable: true
  49616. });
  49617. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49618. /**
  49619. * Defines if the framing behavior of the camera is enabled on the camera.
  49620. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  49621. */
  49622. get: function () {
  49623. return this._framingBehavior != null;
  49624. },
  49625. set: function (value) {
  49626. if (value === this.useFramingBehavior) {
  49627. return;
  49628. }
  49629. if (value) {
  49630. this._framingBehavior = new BABYLON.FramingBehavior();
  49631. this.addBehavior(this._framingBehavior);
  49632. }
  49633. else if (this._framingBehavior) {
  49634. this.removeBehavior(this._framingBehavior);
  49635. this._framingBehavior = null;
  49636. }
  49637. },
  49638. enumerable: true,
  49639. configurable: true
  49640. });
  49641. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49642. /**
  49643. * Gets the auto rotation behavior of the camera if it has been enabled.
  49644. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  49645. */
  49646. get: function () {
  49647. return this._autoRotationBehavior;
  49648. },
  49649. enumerable: true,
  49650. configurable: true
  49651. });
  49652. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49653. /**
  49654. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  49655. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  49656. */
  49657. get: function () {
  49658. return this._autoRotationBehavior != null;
  49659. },
  49660. set: function (value) {
  49661. if (value === this.useAutoRotationBehavior) {
  49662. return;
  49663. }
  49664. if (value) {
  49665. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49666. this.addBehavior(this._autoRotationBehavior);
  49667. }
  49668. else if (this._autoRotationBehavior) {
  49669. this.removeBehavior(this._autoRotationBehavior);
  49670. this._autoRotationBehavior = null;
  49671. }
  49672. },
  49673. enumerable: true,
  49674. configurable: true
  49675. });
  49676. // Cache
  49677. /** @hidden */
  49678. ArcRotateCamera.prototype._initCache = function () {
  49679. _super.prototype._initCache.call(this);
  49680. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49681. this._cache.alpha = undefined;
  49682. this._cache.beta = undefined;
  49683. this._cache.radius = undefined;
  49684. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49685. };
  49686. /** @hidden */
  49687. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49688. if (!ignoreParentClass) {
  49689. _super.prototype._updateCache.call(this);
  49690. }
  49691. this._cache._target.copyFrom(this._getTargetPosition());
  49692. this._cache.alpha = this.alpha;
  49693. this._cache.beta = this.beta;
  49694. this._cache.radius = this.radius;
  49695. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49696. };
  49697. ArcRotateCamera.prototype._getTargetPosition = function () {
  49698. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49699. var pos = this._targetHost.getAbsolutePosition();
  49700. if (this._targetBoundingCenter) {
  49701. pos.addToRef(this._targetBoundingCenter, this._target);
  49702. }
  49703. else {
  49704. this._target.copyFrom(pos);
  49705. }
  49706. }
  49707. var lockedTargetPosition = this._getLockedTargetPosition();
  49708. if (lockedTargetPosition) {
  49709. return lockedTargetPosition;
  49710. }
  49711. return this._target;
  49712. };
  49713. /**
  49714. * Stores the current state of the camera (alpha, beta, radius and target)
  49715. * @returns the camera itself
  49716. */
  49717. ArcRotateCamera.prototype.storeState = function () {
  49718. this._storedAlpha = this.alpha;
  49719. this._storedBeta = this.beta;
  49720. this._storedRadius = this.radius;
  49721. this._storedTarget = this._getTargetPosition().clone();
  49722. return _super.prototype.storeState.call(this);
  49723. };
  49724. /**
  49725. * @hidden
  49726. * Restored camera state. You must call storeState() first
  49727. */
  49728. ArcRotateCamera.prototype._restoreStateValues = function () {
  49729. if (!_super.prototype._restoreStateValues.call(this)) {
  49730. return false;
  49731. }
  49732. this.alpha = this._storedAlpha;
  49733. this.beta = this._storedBeta;
  49734. this.radius = this._storedRadius;
  49735. this.setTarget(this._storedTarget.clone());
  49736. this.inertialAlphaOffset = 0;
  49737. this.inertialBetaOffset = 0;
  49738. this.inertialRadiusOffset = 0;
  49739. this.inertialPanningX = 0;
  49740. this.inertialPanningY = 0;
  49741. return true;
  49742. };
  49743. // Synchronized
  49744. /** @hidden */
  49745. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49746. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49747. return false;
  49748. return this._cache._target.equals(this._getTargetPosition())
  49749. && this._cache.alpha === this.alpha
  49750. && this._cache.beta === this.beta
  49751. && this._cache.radius === this.radius
  49752. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49753. };
  49754. /**
  49755. * Attached controls to the current camera.
  49756. * @param element Defines the element the controls should be listened from
  49757. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49758. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  49759. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  49760. */
  49761. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49762. var _this = this;
  49763. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49764. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49765. this._useCtrlForPanning = useCtrlForPanning;
  49766. this._panningMouseButton = panningMouseButton;
  49767. this.inputs.attachElement(element, noPreventDefault);
  49768. this._reset = function () {
  49769. _this.inertialAlphaOffset = 0;
  49770. _this.inertialBetaOffset = 0;
  49771. _this.inertialRadiusOffset = 0;
  49772. _this.inertialPanningX = 0;
  49773. _this.inertialPanningY = 0;
  49774. };
  49775. };
  49776. /**
  49777. * Detach the current controls from the camera.
  49778. * The camera will stop reacting to inputs.
  49779. * @param element Defines the element to stop listening the inputs from
  49780. */
  49781. ArcRotateCamera.prototype.detachControl = function (element) {
  49782. this.inputs.detachElement(element);
  49783. if (this._reset) {
  49784. this._reset();
  49785. }
  49786. };
  49787. /** @hidden */
  49788. ArcRotateCamera.prototype._checkInputs = function () {
  49789. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49790. if (this._collisionTriggered) {
  49791. return;
  49792. }
  49793. this.inputs.checkInputs();
  49794. // Inertia
  49795. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49796. var inertialAlphaOffset = this.inertialAlphaOffset;
  49797. if (this.beta <= 0)
  49798. inertialAlphaOffset *= -1;
  49799. if (this.getScene().useRightHandedSystem)
  49800. inertialAlphaOffset *= -1;
  49801. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49802. inertialAlphaOffset *= -1;
  49803. this.alpha += inertialAlphaOffset;
  49804. this.beta += this.inertialBetaOffset;
  49805. this.radius -= this.inertialRadiusOffset;
  49806. this.inertialAlphaOffset *= this.inertia;
  49807. this.inertialBetaOffset *= this.inertia;
  49808. this.inertialRadiusOffset *= this.inertia;
  49809. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49810. this.inertialAlphaOffset = 0;
  49811. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49812. this.inertialBetaOffset = 0;
  49813. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49814. this.inertialRadiusOffset = 0;
  49815. }
  49816. // Panning inertia
  49817. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49818. if (!this._localDirection) {
  49819. this._localDirection = BABYLON.Vector3.Zero();
  49820. this._transformedDirection = BABYLON.Vector3.Zero();
  49821. }
  49822. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49823. this._localDirection.multiplyInPlace(this.panningAxis);
  49824. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49825. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49826. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49827. if (!this.panningAxis.y) {
  49828. this._transformedDirection.y = 0;
  49829. }
  49830. if (!this._targetHost) {
  49831. if (this.panningDistanceLimit) {
  49832. this._transformedDirection.addInPlace(this._target);
  49833. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49834. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49835. this._target.copyFrom(this._transformedDirection);
  49836. }
  49837. }
  49838. else {
  49839. this._target.addInPlace(this._transformedDirection);
  49840. }
  49841. }
  49842. this.inertialPanningX *= this.panningInertia;
  49843. this.inertialPanningY *= this.panningInertia;
  49844. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49845. this.inertialPanningX = 0;
  49846. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49847. this.inertialPanningY = 0;
  49848. }
  49849. // Limits
  49850. this._checkLimits();
  49851. _super.prototype._checkInputs.call(this);
  49852. };
  49853. ArcRotateCamera.prototype._checkLimits = function () {
  49854. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49855. if (this.allowUpsideDown && this.beta > Math.PI) {
  49856. this.beta = this.beta - (2 * Math.PI);
  49857. }
  49858. }
  49859. else {
  49860. if (this.beta < this.lowerBetaLimit) {
  49861. this.beta = this.lowerBetaLimit;
  49862. }
  49863. }
  49864. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49865. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49866. this.beta = this.beta + (2 * Math.PI);
  49867. }
  49868. }
  49869. else {
  49870. if (this.beta > this.upperBetaLimit) {
  49871. this.beta = this.upperBetaLimit;
  49872. }
  49873. }
  49874. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  49875. this.alpha = this.lowerAlphaLimit;
  49876. }
  49877. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  49878. this.alpha = this.upperAlphaLimit;
  49879. }
  49880. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  49881. this.radius = this.lowerRadiusLimit;
  49882. }
  49883. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  49884. this.radius = this.upperRadiusLimit;
  49885. }
  49886. };
  49887. /**
  49888. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  49889. */
  49890. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49891. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49892. this.radius = this._computationVector.length();
  49893. if (this.radius === 0) {
  49894. this.radius = 0.0001; // Just to avoid division by zero
  49895. }
  49896. // Alpha
  49897. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49898. if (this._computationVector.z < 0) {
  49899. this.alpha = 2 * Math.PI - this.alpha;
  49900. }
  49901. // Beta
  49902. this.beta = Math.acos(this._computationVector.y / this.radius);
  49903. this._checkLimits();
  49904. };
  49905. /**
  49906. * Use a position to define the current camera related information like aplha, beta and radius
  49907. * @param position Defines the position to set the camera at
  49908. */
  49909. ArcRotateCamera.prototype.setPosition = function (position) {
  49910. if (this.position.equals(position)) {
  49911. return;
  49912. }
  49913. this.position.copyFrom(position);
  49914. this.rebuildAnglesAndRadius();
  49915. };
  49916. /**
  49917. * Defines the target the camera should look at.
  49918. * This will automatically adapt alpha beta and radius to fit within the new target.
  49919. * @param target Defines the new target as a Vector or a mesh
  49920. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  49921. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  49922. */
  49923. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49924. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49925. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49926. if (target.getBoundingInfo) {
  49927. if (toBoundingCenter) {
  49928. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49929. }
  49930. else {
  49931. this._targetBoundingCenter = null;
  49932. }
  49933. this._targetHost = target;
  49934. this._target = this._getTargetPosition();
  49935. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49936. }
  49937. else {
  49938. var newTarget = target;
  49939. var currentTarget = this._getTargetPosition();
  49940. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49941. return;
  49942. }
  49943. this._targetHost = null;
  49944. this._target = newTarget;
  49945. this._targetBoundingCenter = null;
  49946. this.onMeshTargetChangedObservable.notifyObservers(null);
  49947. }
  49948. this.rebuildAnglesAndRadius();
  49949. };
  49950. /** @hidden */
  49951. ArcRotateCamera.prototype._getViewMatrix = function () {
  49952. // Compute
  49953. var cosa = Math.cos(this.alpha);
  49954. var sina = Math.sin(this.alpha);
  49955. var cosb = Math.cos(this.beta);
  49956. var sinb = Math.sin(this.beta);
  49957. if (sinb === 0) {
  49958. sinb = 0.0001;
  49959. }
  49960. var target = this._getTargetPosition();
  49961. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49962. target.addToRef(this._computationVector, this._newPosition);
  49963. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49964. if (!this._collider) {
  49965. this._collider = new BABYLON.Collider();
  49966. }
  49967. this._collider._radius = this.collisionRadius;
  49968. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49969. this._collisionTriggered = true;
  49970. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49971. }
  49972. else {
  49973. this.position.copyFrom(this._newPosition);
  49974. var up = this.upVector;
  49975. if (this.allowUpsideDown && sinb < 0) {
  49976. up = up.clone();
  49977. up = up.negate();
  49978. }
  49979. this._computeViewMatrix(this.position, target, up);
  49980. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49981. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49982. }
  49983. this._currentTarget = target;
  49984. return this._viewMatrix;
  49985. };
  49986. /**
  49987. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  49988. * @param meshes Defines the mesh to zoom on
  49989. * @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)
  49990. */
  49991. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49992. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49993. meshes = meshes || this.getScene().meshes;
  49994. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49995. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49996. this.radius = distance * this.zoomOnFactor;
  49997. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49998. };
  49999. /**
  50000. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  50001. * The target will be changed but the radius
  50002. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  50003. * @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)
  50004. */
  50005. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  50006. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50007. var meshesOrMinMaxVector;
  50008. var distance;
  50009. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  50010. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  50011. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  50012. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  50013. }
  50014. else { //minMaxVector and distance
  50015. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  50016. meshesOrMinMaxVector = minMaxVectorAndDistance;
  50017. distance = minMaxVectorAndDistance.distance;
  50018. }
  50019. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  50020. if (!doNotUpdateMaxZ) {
  50021. this.maxZ = distance * 2;
  50022. }
  50023. };
  50024. /**
  50025. * @override
  50026. * Override Camera.createRigCamera
  50027. */
  50028. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  50029. var alphaShift = 0;
  50030. switch (this.cameraRigMode) {
  50031. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50032. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50033. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50034. case BABYLON.Camera.RIG_MODE_VR:
  50035. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  50036. break;
  50037. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50038. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  50039. break;
  50040. }
  50041. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  50042. rigCam._cameraRigParams = {};
  50043. return rigCam;
  50044. };
  50045. /**
  50046. * @hidden
  50047. * @override
  50048. * Override Camera._updateRigCameras
  50049. */
  50050. ArcRotateCamera.prototype._updateRigCameras = function () {
  50051. var camLeft = this._rigCameras[0];
  50052. var camRight = this._rigCameras[1];
  50053. camLeft.beta = camRight.beta = this.beta;
  50054. camLeft.radius = camRight.radius = this.radius;
  50055. switch (this.cameraRigMode) {
  50056. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50057. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50058. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50059. case BABYLON.Camera.RIG_MODE_VR:
  50060. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50061. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50062. break;
  50063. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50064. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50065. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50066. break;
  50067. }
  50068. _super.prototype._updateRigCameras.call(this);
  50069. };
  50070. /**
  50071. * Destroy the camera and release the current resources hold by it.
  50072. */
  50073. ArcRotateCamera.prototype.dispose = function () {
  50074. this.inputs.clear();
  50075. _super.prototype.dispose.call(this);
  50076. };
  50077. /**
  50078. * Gets the current object class name.
  50079. * @return the class name
  50080. */
  50081. ArcRotateCamera.prototype.getClassName = function () {
  50082. return "ArcRotateCamera";
  50083. };
  50084. __decorate([
  50085. BABYLON.serialize()
  50086. ], ArcRotateCamera.prototype, "alpha", void 0);
  50087. __decorate([
  50088. BABYLON.serialize()
  50089. ], ArcRotateCamera.prototype, "beta", void 0);
  50090. __decorate([
  50091. BABYLON.serialize()
  50092. ], ArcRotateCamera.prototype, "radius", void 0);
  50093. __decorate([
  50094. BABYLON.serializeAsVector3("target")
  50095. ], ArcRotateCamera.prototype, "_target", void 0);
  50096. __decorate([
  50097. BABYLON.serialize()
  50098. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  50099. __decorate([
  50100. BABYLON.serialize()
  50101. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  50102. __decorate([
  50103. BABYLON.serialize()
  50104. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  50105. __decorate([
  50106. BABYLON.serialize()
  50107. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  50108. __decorate([
  50109. BABYLON.serialize()
  50110. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  50111. __decorate([
  50112. BABYLON.serialize()
  50113. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  50114. __decorate([
  50115. BABYLON.serialize()
  50116. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  50117. __decorate([
  50118. BABYLON.serialize()
  50119. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  50120. __decorate([
  50121. BABYLON.serialize()
  50122. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  50123. __decorate([
  50124. BABYLON.serialize()
  50125. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  50126. __decorate([
  50127. BABYLON.serialize()
  50128. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  50129. __decorate([
  50130. BABYLON.serialize()
  50131. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  50132. __decorate([
  50133. BABYLON.serialize()
  50134. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  50135. __decorate([
  50136. BABYLON.serializeAsVector3()
  50137. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  50138. __decorate([
  50139. BABYLON.serialize()
  50140. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  50141. __decorate([
  50142. BABYLON.serialize()
  50143. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  50144. __decorate([
  50145. BABYLON.serialize()
  50146. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  50147. __decorate([
  50148. BABYLON.serialize()
  50149. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  50150. __decorate([
  50151. BABYLON.serialize()
  50152. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  50153. return ArcRotateCamera;
  50154. }(BABYLON.TargetCamera));
  50155. BABYLON.ArcRotateCamera = ArcRotateCamera;
  50156. })(BABYLON || (BABYLON = {}));
  50157. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  50158. var BABYLON;
  50159. (function (BABYLON) {
  50160. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  50161. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  50162. });
  50163. /**
  50164. * The HemisphericLight simulates the ambient environment light,
  50165. * so the passed direction is the light reflection direction, not the incoming direction.
  50166. */
  50167. var HemisphericLight = /** @class */ (function (_super) {
  50168. __extends(HemisphericLight, _super);
  50169. /**
  50170. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  50171. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  50172. * The HemisphericLight can't cast shadows.
  50173. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50174. * @param name The friendly name of the light
  50175. * @param direction The direction of the light reflection
  50176. * @param scene The scene the light belongs to
  50177. */
  50178. function HemisphericLight(name, direction, scene) {
  50179. var _this = _super.call(this, name, scene) || this;
  50180. /**
  50181. * The groundColor is the light in the opposite direction to the one specified during creation.
  50182. * 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.
  50183. */
  50184. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  50185. _this.direction = direction || BABYLON.Vector3.Up();
  50186. return _this;
  50187. }
  50188. HemisphericLight.prototype._buildUniformLayout = function () {
  50189. this._uniformBuffer.addUniform("vLightData", 4);
  50190. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50191. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50192. this._uniformBuffer.addUniform("vLightGround", 3);
  50193. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50194. this._uniformBuffer.addUniform("depthValues", 2);
  50195. this._uniformBuffer.create();
  50196. };
  50197. /**
  50198. * Returns the string "HemisphericLight".
  50199. * @return The class name
  50200. */
  50201. HemisphericLight.prototype.getClassName = function () {
  50202. return "HemisphericLight";
  50203. };
  50204. /**
  50205. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50206. * Returns the updated direction.
  50207. * @param target The target the direction should point to
  50208. * @return The computed direction
  50209. */
  50210. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50211. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50212. return this.direction;
  50213. };
  50214. /**
  50215. * Returns the shadow generator associated to the light.
  50216. * @returns Always null for hemispheric lights because it does not support shadows.
  50217. */
  50218. HemisphericLight.prototype.getShadowGenerator = function () {
  50219. return null;
  50220. };
  50221. /**
  50222. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50223. * @param effect The effect to update
  50224. * @param lightIndex The index of the light in the effect to update
  50225. * @returns The hemispheric light
  50226. */
  50227. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50228. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50229. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50230. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50231. return this;
  50232. };
  50233. /**
  50234. * Computes the world matrix of the node
  50235. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50236. * @param useWasUpdatedFlag defines a reserved property
  50237. * @returns the world matrix
  50238. */
  50239. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50240. if (!this._worldMatrix) {
  50241. this._worldMatrix = BABYLON.Matrix.Identity();
  50242. }
  50243. return this._worldMatrix;
  50244. };
  50245. /**
  50246. * Returns the integer 3.
  50247. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50248. */
  50249. HemisphericLight.prototype.getTypeID = function () {
  50250. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50251. };
  50252. /**
  50253. * Prepares the list of defines specific to the light type.
  50254. * @param defines the list of defines
  50255. * @param lightIndex defines the index of the light for the effect
  50256. */
  50257. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50258. defines["HEMILIGHT" + lightIndex] = true;
  50259. };
  50260. __decorate([
  50261. BABYLON.serializeAsColor3()
  50262. ], HemisphericLight.prototype, "groundColor", void 0);
  50263. __decorate([
  50264. BABYLON.serializeAsVector3()
  50265. ], HemisphericLight.prototype, "direction", void 0);
  50266. return HemisphericLight;
  50267. }(BABYLON.Light));
  50268. BABYLON.HemisphericLight = HemisphericLight;
  50269. })(BABYLON || (BABYLON = {}));
  50270. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50271. var BABYLON;
  50272. (function (BABYLON) {
  50273. /**
  50274. * Base implementation IShadowLight
  50275. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50276. */
  50277. var ShadowLight = /** @class */ (function (_super) {
  50278. __extends(ShadowLight, _super);
  50279. function ShadowLight() {
  50280. var _this = _super !== null && _super.apply(this, arguments) || this;
  50281. _this._needProjectionMatrixCompute = true;
  50282. return _this;
  50283. }
  50284. ShadowLight.prototype._setPosition = function (value) {
  50285. this._position = value;
  50286. };
  50287. Object.defineProperty(ShadowLight.prototype, "position", {
  50288. /**
  50289. * Sets the position the shadow will be casted from. Also use as the light position for both
  50290. * point and spot lights.
  50291. */
  50292. get: function () {
  50293. return this._position;
  50294. },
  50295. /**
  50296. * Sets the position the shadow will be casted from. Also use as the light position for both
  50297. * point and spot lights.
  50298. */
  50299. set: function (value) {
  50300. this._setPosition(value);
  50301. },
  50302. enumerable: true,
  50303. configurable: true
  50304. });
  50305. ShadowLight.prototype._setDirection = function (value) {
  50306. this._direction = value;
  50307. };
  50308. Object.defineProperty(ShadowLight.prototype, "direction", {
  50309. /**
  50310. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50311. * Also use as the light direction on spot and directional lights.
  50312. */
  50313. get: function () {
  50314. return this._direction;
  50315. },
  50316. /**
  50317. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  50318. * Also use as the light direction on spot and directional lights.
  50319. */
  50320. set: function (value) {
  50321. this._setDirection(value);
  50322. },
  50323. enumerable: true,
  50324. configurable: true
  50325. });
  50326. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  50327. /**
  50328. * Gets the shadow projection clipping minimum z value.
  50329. */
  50330. get: function () {
  50331. return this._shadowMinZ;
  50332. },
  50333. /**
  50334. * Sets the shadow projection clipping minimum z value.
  50335. */
  50336. set: function (value) {
  50337. this._shadowMinZ = value;
  50338. this.forceProjectionMatrixCompute();
  50339. },
  50340. enumerable: true,
  50341. configurable: true
  50342. });
  50343. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  50344. /**
  50345. * Sets the shadow projection clipping maximum z value.
  50346. */
  50347. get: function () {
  50348. return this._shadowMaxZ;
  50349. },
  50350. /**
  50351. * Gets the shadow projection clipping maximum z value.
  50352. */
  50353. set: function (value) {
  50354. this._shadowMaxZ = value;
  50355. this.forceProjectionMatrixCompute();
  50356. },
  50357. enumerable: true,
  50358. configurable: true
  50359. });
  50360. /**
  50361. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  50362. * @returns true if the information has been computed, false if it does not need to (no parenting)
  50363. */
  50364. ShadowLight.prototype.computeTransformedInformation = function () {
  50365. if (this.parent && this.parent.getWorldMatrix) {
  50366. if (!this.transformedPosition) {
  50367. this.transformedPosition = BABYLON.Vector3.Zero();
  50368. }
  50369. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  50370. // In case the direction is present.
  50371. if (this.direction) {
  50372. if (!this.transformedDirection) {
  50373. this.transformedDirection = BABYLON.Vector3.Zero();
  50374. }
  50375. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  50376. }
  50377. return true;
  50378. }
  50379. return false;
  50380. };
  50381. /**
  50382. * Return the depth scale used for the shadow map.
  50383. * @returns the depth scale.
  50384. */
  50385. ShadowLight.prototype.getDepthScale = function () {
  50386. return 50.0;
  50387. };
  50388. /**
  50389. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  50390. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50391. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50392. */
  50393. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  50394. return this.transformedDirection ? this.transformedDirection : this.direction;
  50395. };
  50396. /**
  50397. * Returns the ShadowLight absolute position in the World.
  50398. * @returns the position vector in world space
  50399. */
  50400. ShadowLight.prototype.getAbsolutePosition = function () {
  50401. return this.transformedPosition ? this.transformedPosition : this.position;
  50402. };
  50403. /**
  50404. * Sets the ShadowLight direction toward the passed target.
  50405. * @param target The point tot target in local space
  50406. * @returns the updated ShadowLight direction
  50407. */
  50408. ShadowLight.prototype.setDirectionToTarget = function (target) {
  50409. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  50410. return this.direction;
  50411. };
  50412. /**
  50413. * Returns the light rotation in euler definition.
  50414. * @returns the x y z rotation in local space.
  50415. */
  50416. ShadowLight.prototype.getRotation = function () {
  50417. this.direction.normalize();
  50418. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  50419. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  50420. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  50421. };
  50422. /**
  50423. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  50424. * @returns true if a cube texture needs to be use
  50425. */
  50426. ShadowLight.prototype.needCube = function () {
  50427. return false;
  50428. };
  50429. /**
  50430. * Detects if the projection matrix requires to be recomputed this frame.
  50431. * @returns true if it requires to be recomputed otherwise, false.
  50432. */
  50433. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  50434. return this._needProjectionMatrixCompute;
  50435. };
  50436. /**
  50437. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  50438. */
  50439. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  50440. this._needProjectionMatrixCompute = true;
  50441. };
  50442. /** @hidden */
  50443. ShadowLight.prototype._initCache = function () {
  50444. _super.prototype._initCache.call(this);
  50445. this._cache.position = BABYLON.Vector3.Zero();
  50446. };
  50447. /** @hidden */
  50448. ShadowLight.prototype._isSynchronized = function () {
  50449. if (!this._cache.position.equals(this.position))
  50450. return false;
  50451. return true;
  50452. };
  50453. /**
  50454. * Computes the world matrix of the node
  50455. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50456. * @returns the world matrix
  50457. */
  50458. ShadowLight.prototype.computeWorldMatrix = function (force) {
  50459. if (!force && this.isSynchronized()) {
  50460. this._currentRenderId = this.getScene().getRenderId();
  50461. return this._worldMatrix;
  50462. }
  50463. this._updateCache();
  50464. this._cache.position.copyFrom(this.position);
  50465. if (!this._worldMatrix) {
  50466. this._worldMatrix = BABYLON.Matrix.Identity();
  50467. }
  50468. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  50469. if (this.parent && this.parent.getWorldMatrix) {
  50470. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  50471. this._markSyncedWithParent();
  50472. }
  50473. // Cache the determinant
  50474. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  50475. return this._worldMatrix;
  50476. };
  50477. /**
  50478. * Gets the minZ used for shadow according to both the scene and the light.
  50479. * @param activeCamera The camera we are returning the min for
  50480. * @returns the depth min z
  50481. */
  50482. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  50483. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  50484. };
  50485. /**
  50486. * Gets the maxZ used for shadow according to both the scene and the light.
  50487. * @param activeCamera The camera we are returning the max for
  50488. * @returns the depth max z
  50489. */
  50490. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  50491. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  50492. };
  50493. /**
  50494. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  50495. * @param matrix The materix to updated with the projection information
  50496. * @param viewMatrix The transform matrix of the light
  50497. * @param renderList The list of mesh to render in the map
  50498. * @returns The current light
  50499. */
  50500. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50501. if (this.customProjectionMatrixBuilder) {
  50502. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  50503. }
  50504. else {
  50505. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50506. }
  50507. return this;
  50508. };
  50509. __decorate([
  50510. BABYLON.serializeAsVector3()
  50511. ], ShadowLight.prototype, "position", null);
  50512. __decorate([
  50513. BABYLON.serializeAsVector3()
  50514. ], ShadowLight.prototype, "direction", null);
  50515. __decorate([
  50516. BABYLON.serialize()
  50517. ], ShadowLight.prototype, "shadowMinZ", null);
  50518. __decorate([
  50519. BABYLON.serialize()
  50520. ], ShadowLight.prototype, "shadowMaxZ", null);
  50521. return ShadowLight;
  50522. }(BABYLON.Light));
  50523. BABYLON.ShadowLight = ShadowLight;
  50524. })(BABYLON || (BABYLON = {}));
  50525. //# sourceMappingURL=babylon.shadowLight.js.map
  50526. var BABYLON;
  50527. (function (BABYLON) {
  50528. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  50529. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  50530. });
  50531. /**
  50532. * A point light is a light defined by an unique point in world space.
  50533. * The light is emitted in every direction from this point.
  50534. * A good example of a point light is a standard light bulb.
  50535. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50536. */
  50537. var PointLight = /** @class */ (function (_super) {
  50538. __extends(PointLight, _super);
  50539. /**
  50540. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  50541. * A PointLight emits the light in every direction.
  50542. * It can cast shadows.
  50543. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  50544. * ```javascript
  50545. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  50546. * ```
  50547. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50548. * @param name The light friendly name
  50549. * @param position The position of the point light in the scene
  50550. * @param scene The scene the lights belongs to
  50551. */
  50552. function PointLight(name, position, scene) {
  50553. var _this = _super.call(this, name, scene) || this;
  50554. _this._shadowAngle = Math.PI / 2;
  50555. _this.position = position;
  50556. return _this;
  50557. }
  50558. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  50559. /**
  50560. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50561. * This specifies what angle the shadow will use to be created.
  50562. *
  50563. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50564. */
  50565. get: function () {
  50566. return this._shadowAngle;
  50567. },
  50568. /**
  50569. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50570. * This specifies what angle the shadow will use to be created.
  50571. *
  50572. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50573. */
  50574. set: function (value) {
  50575. this._shadowAngle = value;
  50576. this.forceProjectionMatrixCompute();
  50577. },
  50578. enumerable: true,
  50579. configurable: true
  50580. });
  50581. Object.defineProperty(PointLight.prototype, "direction", {
  50582. /**
  50583. * Gets the direction if it has been set.
  50584. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50585. */
  50586. get: function () {
  50587. return this._direction;
  50588. },
  50589. /**
  50590. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50591. */
  50592. set: function (value) {
  50593. var previousNeedCube = this.needCube();
  50594. this._direction = value;
  50595. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  50596. this._shadowGenerator.recreateShadowMap();
  50597. }
  50598. },
  50599. enumerable: true,
  50600. configurable: true
  50601. });
  50602. /**
  50603. * Returns the string "PointLight"
  50604. * @returns the class name
  50605. */
  50606. PointLight.prototype.getClassName = function () {
  50607. return "PointLight";
  50608. };
  50609. /**
  50610. * Returns the integer 0.
  50611. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50612. */
  50613. PointLight.prototype.getTypeID = function () {
  50614. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  50615. };
  50616. /**
  50617. * Specifies wether or not the shadowmap should be a cube texture.
  50618. * @returns true if the shadowmap needs to be a cube texture.
  50619. */
  50620. PointLight.prototype.needCube = function () {
  50621. return !this.direction;
  50622. };
  50623. /**
  50624. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  50625. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50626. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50627. */
  50628. PointLight.prototype.getShadowDirection = function (faceIndex) {
  50629. if (this.direction) {
  50630. return _super.prototype.getShadowDirection.call(this, faceIndex);
  50631. }
  50632. else {
  50633. switch (faceIndex) {
  50634. case 0:
  50635. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  50636. case 1:
  50637. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  50638. case 2:
  50639. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  50640. case 3:
  50641. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  50642. case 4:
  50643. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  50644. case 5:
  50645. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  50646. }
  50647. }
  50648. return BABYLON.Vector3.Zero();
  50649. };
  50650. /**
  50651. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  50652. * - fov = PI / 2
  50653. * - aspect ratio : 1.0
  50654. * - z-near and far equal to the active camera minZ and maxZ.
  50655. * Returns the PointLight.
  50656. */
  50657. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50658. var activeCamera = this.getScene().activeCamera;
  50659. if (!activeCamera) {
  50660. return;
  50661. }
  50662. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50663. };
  50664. PointLight.prototype._buildUniformLayout = function () {
  50665. this._uniformBuffer.addUniform("vLightData", 4);
  50666. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50667. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50668. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50669. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50670. this._uniformBuffer.addUniform("depthValues", 2);
  50671. this._uniformBuffer.create();
  50672. };
  50673. /**
  50674. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50675. * @param effect The effect to update
  50676. * @param lightIndex The index of the light in the effect to update
  50677. * @returns The point light
  50678. */
  50679. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50680. if (this.computeTransformedInformation()) {
  50681. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50682. }
  50683. else {
  50684. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50685. }
  50686. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  50687. return this;
  50688. };
  50689. /**
  50690. * Prepares the list of defines specific to the light type.
  50691. * @param defines the list of defines
  50692. * @param lightIndex defines the index of the light for the effect
  50693. */
  50694. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50695. defines["POINTLIGHT" + lightIndex] = true;
  50696. };
  50697. __decorate([
  50698. BABYLON.serialize()
  50699. ], PointLight.prototype, "shadowAngle", null);
  50700. return PointLight;
  50701. }(BABYLON.ShadowLight));
  50702. BABYLON.PointLight = PointLight;
  50703. })(BABYLON || (BABYLON = {}));
  50704. //# sourceMappingURL=babylon.pointLight.js.map
  50705. var BABYLON;
  50706. (function (BABYLON) {
  50707. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  50708. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  50709. });
  50710. /**
  50711. * A directional light is defined by a direction (what a surprise!).
  50712. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50713. * 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.
  50714. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50715. */
  50716. var DirectionalLight = /** @class */ (function (_super) {
  50717. __extends(DirectionalLight, _super);
  50718. /**
  50719. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50720. * The directional light is emitted from everywhere in the given direction.
  50721. * It can cast shadows.
  50722. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50723. * @param name The friendly name of the light
  50724. * @param direction The direction of the light
  50725. * @param scene The scene the light belongs to
  50726. */
  50727. function DirectionalLight(name, direction, scene) {
  50728. var _this = _super.call(this, name, scene) || this;
  50729. _this._shadowFrustumSize = 0;
  50730. _this._shadowOrthoScale = 0.1;
  50731. /**
  50732. * Automatically compute the projection matrix to best fit (including all the casters)
  50733. * on each frame.
  50734. */
  50735. _this.autoUpdateExtends = true;
  50736. // Cache
  50737. _this._orthoLeft = Number.MAX_VALUE;
  50738. _this._orthoRight = Number.MIN_VALUE;
  50739. _this._orthoTop = Number.MIN_VALUE;
  50740. _this._orthoBottom = Number.MAX_VALUE;
  50741. _this.position = direction.scale(-1.0);
  50742. _this.direction = direction;
  50743. return _this;
  50744. }
  50745. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50746. /**
  50747. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50748. */
  50749. get: function () {
  50750. return this._shadowFrustumSize;
  50751. },
  50752. /**
  50753. * Specifies a fix frustum size for the shadow generation.
  50754. */
  50755. set: function (value) {
  50756. this._shadowFrustumSize = value;
  50757. this.forceProjectionMatrixCompute();
  50758. },
  50759. enumerable: true,
  50760. configurable: true
  50761. });
  50762. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50763. /**
  50764. * Gets the shadow projection scale against the optimal computed one.
  50765. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50766. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50767. */
  50768. get: function () {
  50769. return this._shadowOrthoScale;
  50770. },
  50771. /**
  50772. * Sets the shadow projection scale against the optimal computed one.
  50773. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50774. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50775. */
  50776. set: function (value) {
  50777. this._shadowOrthoScale = value;
  50778. this.forceProjectionMatrixCompute();
  50779. },
  50780. enumerable: true,
  50781. configurable: true
  50782. });
  50783. /**
  50784. * Returns the string "DirectionalLight".
  50785. * @return The class name
  50786. */
  50787. DirectionalLight.prototype.getClassName = function () {
  50788. return "DirectionalLight";
  50789. };
  50790. /**
  50791. * Returns the integer 1.
  50792. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50793. */
  50794. DirectionalLight.prototype.getTypeID = function () {
  50795. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50796. };
  50797. /**
  50798. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50799. * Returns the DirectionalLight Shadow projection matrix.
  50800. */
  50801. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50802. if (this.shadowFrustumSize > 0) {
  50803. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50804. }
  50805. else {
  50806. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50807. }
  50808. };
  50809. /**
  50810. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50811. * Returns the DirectionalLight Shadow projection matrix.
  50812. */
  50813. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50814. var activeCamera = this.getScene().activeCamera;
  50815. if (!activeCamera) {
  50816. return;
  50817. }
  50818. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50819. };
  50820. /**
  50821. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50822. * Returns the DirectionalLight Shadow projection matrix.
  50823. */
  50824. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50825. var activeCamera = this.getScene().activeCamera;
  50826. if (!activeCamera) {
  50827. return;
  50828. }
  50829. // Check extends
  50830. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50831. var tempVector3 = BABYLON.Vector3.Zero();
  50832. this._orthoLeft = Number.MAX_VALUE;
  50833. this._orthoRight = Number.MIN_VALUE;
  50834. this._orthoTop = Number.MIN_VALUE;
  50835. this._orthoBottom = Number.MAX_VALUE;
  50836. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50837. var mesh = renderList[meshIndex];
  50838. if (!mesh) {
  50839. continue;
  50840. }
  50841. var boundingInfo = mesh.getBoundingInfo();
  50842. var boundingBox = boundingInfo.boundingBox;
  50843. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50844. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50845. if (tempVector3.x < this._orthoLeft)
  50846. this._orthoLeft = tempVector3.x;
  50847. if (tempVector3.y < this._orthoBottom)
  50848. this._orthoBottom = tempVector3.y;
  50849. if (tempVector3.x > this._orthoRight)
  50850. this._orthoRight = tempVector3.x;
  50851. if (tempVector3.y > this._orthoTop)
  50852. this._orthoTop = tempVector3.y;
  50853. }
  50854. }
  50855. }
  50856. var xOffset = this._orthoRight - this._orthoLeft;
  50857. var yOffset = this._orthoTop - this._orthoBottom;
  50858. 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);
  50859. };
  50860. DirectionalLight.prototype._buildUniformLayout = function () {
  50861. this._uniformBuffer.addUniform("vLightData", 4);
  50862. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50863. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50864. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50865. this._uniformBuffer.addUniform("depthValues", 2);
  50866. this._uniformBuffer.create();
  50867. };
  50868. /**
  50869. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50870. * @param effect The effect to update
  50871. * @param lightIndex The index of the light in the effect to update
  50872. * @returns The directional light
  50873. */
  50874. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50875. if (this.computeTransformedInformation()) {
  50876. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50877. return this;
  50878. }
  50879. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50880. return this;
  50881. };
  50882. /**
  50883. * Gets the minZ used for shadow according to both the scene and the light.
  50884. *
  50885. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50886. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50887. * @param activeCamera The camera we are returning the min for
  50888. * @returns the depth min z
  50889. */
  50890. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50891. return 1;
  50892. };
  50893. /**
  50894. * Gets the maxZ used for shadow according to both the scene and the light.
  50895. *
  50896. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50897. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50898. * @param activeCamera The camera we are returning the max for
  50899. * @returns the depth max z
  50900. */
  50901. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50902. return 1;
  50903. };
  50904. /**
  50905. * Prepares the list of defines specific to the light type.
  50906. * @param defines the list of defines
  50907. * @param lightIndex defines the index of the light for the effect
  50908. */
  50909. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50910. defines["DIRLIGHT" + lightIndex] = true;
  50911. };
  50912. __decorate([
  50913. BABYLON.serialize()
  50914. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50915. __decorate([
  50916. BABYLON.serialize()
  50917. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50918. __decorate([
  50919. BABYLON.serialize()
  50920. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50921. return DirectionalLight;
  50922. }(BABYLON.ShadowLight));
  50923. BABYLON.DirectionalLight = DirectionalLight;
  50924. })(BABYLON || (BABYLON = {}));
  50925. //# sourceMappingURL=babylon.directionalLight.js.map
  50926. var BABYLON;
  50927. (function (BABYLON) {
  50928. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  50929. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  50930. });
  50931. /**
  50932. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50933. * These values define a cone of light starting from the position, emitting toward the direction.
  50934. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50935. * and the exponent defines the speed of the decay of the light with distance (reach).
  50936. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50937. */
  50938. var SpotLight = /** @class */ (function (_super) {
  50939. __extends(SpotLight, _super);
  50940. /**
  50941. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50942. * It can cast shadows.
  50943. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50944. * @param name The light friendly name
  50945. * @param position The position of the spot light in the scene
  50946. * @param direction The direction of the light in the scene
  50947. * @param angle The cone angle of the light in Radians
  50948. * @param exponent The light decay speed with the distance from the emission spot
  50949. * @param scene The scene the lights belongs to
  50950. */
  50951. function SpotLight(name, position, direction, angle, exponent, scene) {
  50952. var _this = _super.call(this, name, scene) || this;
  50953. _this._innerAngle = 0;
  50954. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50955. _this._projectionTextureLightNear = 1e-6;
  50956. _this._projectionTextureLightFar = 1000.0;
  50957. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50958. _this._projectionTextureViewLightDirty = true;
  50959. _this._projectionTextureProjectionLightDirty = true;
  50960. _this._projectionTextureDirty = true;
  50961. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50962. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50963. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50964. _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);
  50965. _this.position = position;
  50966. _this.direction = direction;
  50967. _this.angle = angle;
  50968. _this.exponent = exponent;
  50969. return _this;
  50970. }
  50971. Object.defineProperty(SpotLight.prototype, "angle", {
  50972. /**
  50973. * Gets the cone angle of the spot light in Radians.
  50974. */
  50975. get: function () {
  50976. return this._angle;
  50977. },
  50978. /**
  50979. * Sets the cone angle of the spot light in Radians.
  50980. */
  50981. set: function (value) {
  50982. this._angle = value;
  50983. this._cosHalfAngle = Math.cos(value * 0.5);
  50984. this._projectionTextureProjectionLightDirty = true;
  50985. this.forceProjectionMatrixCompute();
  50986. this._computeAngleValues();
  50987. },
  50988. enumerable: true,
  50989. configurable: true
  50990. });
  50991. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  50992. /**
  50993. * Only used in gltf falloff mode, this defines the angle where
  50994. * the directional falloff will start before cutting at angle which could be seen
  50995. * as outer angle.
  50996. */
  50997. get: function () {
  50998. return this._innerAngle;
  50999. },
  51000. /**
  51001. * Only used in gltf falloff mode, this defines the angle where
  51002. * the directional falloff will start before cutting at angle which could be seen
  51003. * as outer angle.
  51004. */
  51005. set: function (value) {
  51006. this._innerAngle = value;
  51007. this._computeAngleValues();
  51008. },
  51009. enumerable: true,
  51010. configurable: true
  51011. });
  51012. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  51013. /**
  51014. * Allows scaling the angle of the light for shadow generation only.
  51015. */
  51016. get: function () {
  51017. return this._shadowAngleScale;
  51018. },
  51019. /**
  51020. * Allows scaling the angle of the light for shadow generation only.
  51021. */
  51022. set: function (value) {
  51023. this._shadowAngleScale = value;
  51024. this.forceProjectionMatrixCompute();
  51025. },
  51026. enumerable: true,
  51027. configurable: true
  51028. });
  51029. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  51030. /**
  51031. * Allows reading the projecton texture
  51032. */
  51033. get: function () {
  51034. return this._projectionTextureMatrix;
  51035. },
  51036. enumerable: true,
  51037. configurable: true
  51038. });
  51039. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  51040. /**
  51041. * Gets the near clip of the Spotlight for texture projection.
  51042. */
  51043. get: function () {
  51044. return this._projectionTextureLightNear;
  51045. },
  51046. /**
  51047. * Sets the near clip of the Spotlight for texture projection.
  51048. */
  51049. set: function (value) {
  51050. this._projectionTextureLightNear = value;
  51051. this._projectionTextureProjectionLightDirty = true;
  51052. },
  51053. enumerable: true,
  51054. configurable: true
  51055. });
  51056. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  51057. /**
  51058. * Gets the far clip of the Spotlight for texture projection.
  51059. */
  51060. get: function () {
  51061. return this._projectionTextureLightFar;
  51062. },
  51063. /**
  51064. * Sets the far clip of the Spotlight for texture projection.
  51065. */
  51066. set: function (value) {
  51067. this._projectionTextureLightFar = value;
  51068. this._projectionTextureProjectionLightDirty = true;
  51069. },
  51070. enumerable: true,
  51071. configurable: true
  51072. });
  51073. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  51074. /**
  51075. * Gets the Up vector of the Spotlight for texture projection.
  51076. */
  51077. get: function () {
  51078. return this._projectionTextureUpDirection;
  51079. },
  51080. /**
  51081. * Sets the Up vector of the Spotlight for texture projection.
  51082. */
  51083. set: function (value) {
  51084. this._projectionTextureUpDirection = value;
  51085. this._projectionTextureProjectionLightDirty = true;
  51086. },
  51087. enumerable: true,
  51088. configurable: true
  51089. });
  51090. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  51091. /**
  51092. * Gets the projection texture of the light.
  51093. */
  51094. get: function () {
  51095. return this._projectionTexture;
  51096. },
  51097. /**
  51098. * Sets the projection texture of the light.
  51099. */
  51100. set: function (value) {
  51101. this._projectionTexture = value;
  51102. this._projectionTextureDirty = true;
  51103. },
  51104. enumerable: true,
  51105. configurable: true
  51106. });
  51107. /**
  51108. * Returns the string "SpotLight".
  51109. * @returns the class name
  51110. */
  51111. SpotLight.prototype.getClassName = function () {
  51112. return "SpotLight";
  51113. };
  51114. /**
  51115. * Returns the integer 2.
  51116. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51117. */
  51118. SpotLight.prototype.getTypeID = function () {
  51119. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  51120. };
  51121. /**
  51122. * Overrides the direction setter to recompute the projection texture view light Matrix.
  51123. */
  51124. SpotLight.prototype._setDirection = function (value) {
  51125. _super.prototype._setDirection.call(this, value);
  51126. this._projectionTextureViewLightDirty = true;
  51127. };
  51128. /**
  51129. * Overrides the position setter to recompute the projection texture view light Matrix.
  51130. */
  51131. SpotLight.prototype._setPosition = function (value) {
  51132. _super.prototype._setPosition.call(this, value);
  51133. this._projectionTextureViewLightDirty = true;
  51134. };
  51135. /**
  51136. * 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.
  51137. * Returns the SpotLight.
  51138. */
  51139. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51140. var activeCamera = this.getScene().activeCamera;
  51141. if (!activeCamera) {
  51142. return;
  51143. }
  51144. this._shadowAngleScale = this._shadowAngleScale || 1;
  51145. var angle = this._shadowAngleScale * this._angle;
  51146. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51147. };
  51148. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  51149. this._projectionTextureViewLightDirty = false;
  51150. this._projectionTextureDirty = true;
  51151. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  51152. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  51153. };
  51154. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  51155. this._projectionTextureProjectionLightDirty = false;
  51156. this._projectionTextureDirty = true;
  51157. var light_far = this.projectionTextureLightFar;
  51158. var light_near = this.projectionTextureLightNear;
  51159. var P = light_far / (light_far - light_near);
  51160. var Q = -P * light_near;
  51161. var S = 1.0 / Math.tan(this._angle / 2.0);
  51162. var A = 1.0;
  51163. 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);
  51164. };
  51165. /**
  51166. * Main function for light texture projection matrix computing.
  51167. */
  51168. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  51169. this._projectionTextureDirty = false;
  51170. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  51171. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  51172. };
  51173. SpotLight.prototype._buildUniformLayout = function () {
  51174. this._uniformBuffer.addUniform("vLightData", 4);
  51175. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51176. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51177. this._uniformBuffer.addUniform("vLightDirection", 3);
  51178. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51179. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51180. this._uniformBuffer.addUniform("depthValues", 2);
  51181. this._uniformBuffer.create();
  51182. };
  51183. SpotLight.prototype._computeAngleValues = function () {
  51184. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  51185. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  51186. };
  51187. /**
  51188. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  51189. * @param effect The effect to update
  51190. * @param lightIndex The index of the light in the effect to update
  51191. * @returns The spot light
  51192. */
  51193. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  51194. var normalizeDirection;
  51195. if (this.computeTransformedInformation()) {
  51196. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  51197. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  51198. }
  51199. else {
  51200. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  51201. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  51202. }
  51203. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51204. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51205. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51206. if (this._projectionTextureViewLightDirty) {
  51207. this._computeProjectionTextureViewLightMatrix();
  51208. }
  51209. if (this._projectionTextureProjectionLightDirty) {
  51210. this._computeProjectionTextureProjectionLightMatrix();
  51211. }
  51212. if (this._projectionTextureDirty) {
  51213. this._computeProjectionTextureMatrix();
  51214. }
  51215. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51216. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51217. }
  51218. return this;
  51219. };
  51220. /**
  51221. * Disposes the light and the associated resources.
  51222. */
  51223. SpotLight.prototype.dispose = function () {
  51224. _super.prototype.dispose.call(this);
  51225. if (this._projectionTexture) {
  51226. this._projectionTexture.dispose();
  51227. }
  51228. };
  51229. /**
  51230. * Prepares the list of defines specific to the light type.
  51231. * @param defines the list of defines
  51232. * @param lightIndex defines the index of the light for the effect
  51233. */
  51234. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51235. defines["SPOTLIGHT" + lightIndex] = true;
  51236. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51237. };
  51238. __decorate([
  51239. BABYLON.serialize()
  51240. ], SpotLight.prototype, "angle", null);
  51241. __decorate([
  51242. BABYLON.serialize()
  51243. ], SpotLight.prototype, "innerAngle", null);
  51244. __decorate([
  51245. BABYLON.serialize()
  51246. ], SpotLight.prototype, "shadowAngleScale", null);
  51247. __decorate([
  51248. BABYLON.serialize()
  51249. ], SpotLight.prototype, "exponent", void 0);
  51250. __decorate([
  51251. BABYLON.serialize()
  51252. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51253. __decorate([
  51254. BABYLON.serialize()
  51255. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51256. __decorate([
  51257. BABYLON.serialize()
  51258. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51259. __decorate([
  51260. BABYLON.serializeAsTexture("projectedLightTexture")
  51261. ], SpotLight.prototype, "_projectionTexture", void 0);
  51262. return SpotLight;
  51263. }(BABYLON.ShadowLight));
  51264. BABYLON.SpotLight = SpotLight;
  51265. })(BABYLON || (BABYLON = {}));
  51266. //# sourceMappingURL=babylon.spotLight.js.map
  51267. var BABYLON;
  51268. (function (BABYLON) {
  51269. /**
  51270. * Class used to override all child animations of a given target
  51271. */
  51272. var AnimationPropertiesOverride = /** @class */ (function () {
  51273. function AnimationPropertiesOverride() {
  51274. /**
  51275. * Gets or sets a value indicating if animation blending must be used
  51276. */
  51277. this.enableBlending = false;
  51278. /**
  51279. * Gets or sets the blending speed to use when enableBlending is true
  51280. */
  51281. this.blendingSpeed = 0.01;
  51282. /**
  51283. * Gets or sets the default loop mode to use
  51284. */
  51285. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51286. }
  51287. return AnimationPropertiesOverride;
  51288. }());
  51289. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51290. })(BABYLON || (BABYLON = {}));
  51291. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51292. var BABYLON;
  51293. (function (BABYLON) {
  51294. /**
  51295. * Represents the range of an animation
  51296. */
  51297. var AnimationRange = /** @class */ (function () {
  51298. /**
  51299. * Initializes the range of an animation
  51300. * @param name The name of the animation range
  51301. * @param from The starting frame of the animation
  51302. * @param to The ending frame of the animation
  51303. */
  51304. function AnimationRange(
  51305. /**The name of the animation range**/
  51306. name,
  51307. /**The starting frame of the animation */
  51308. from,
  51309. /**The ending frame of the animation*/
  51310. to) {
  51311. this.name = name;
  51312. this.from = from;
  51313. this.to = to;
  51314. }
  51315. /**
  51316. * Makes a copy of the animation range
  51317. * @returns A copy of the animation range
  51318. */
  51319. AnimationRange.prototype.clone = function () {
  51320. return new AnimationRange(this.name, this.from, this.to);
  51321. };
  51322. return AnimationRange;
  51323. }());
  51324. BABYLON.AnimationRange = AnimationRange;
  51325. /**
  51326. * Composed of a frame, and an action function
  51327. */
  51328. var AnimationEvent = /** @class */ (function () {
  51329. /**
  51330. * Initializes the animation event
  51331. * @param frame The frame for which the event is triggered
  51332. * @param action The event to perform when triggered
  51333. * @param onlyOnce Specifies if the event should be triggered only once
  51334. */
  51335. function AnimationEvent(
  51336. /** The frame for which the event is triggered **/
  51337. frame,
  51338. /** The event to perform when triggered **/
  51339. action,
  51340. /** Specifies if the event should be triggered only once**/
  51341. onlyOnce) {
  51342. this.frame = frame;
  51343. this.action = action;
  51344. this.onlyOnce = onlyOnce;
  51345. /**
  51346. * Specifies if the animation event is done
  51347. */
  51348. this.isDone = false;
  51349. }
  51350. /** @hidden */
  51351. AnimationEvent.prototype._clone = function () {
  51352. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  51353. };
  51354. return AnimationEvent;
  51355. }());
  51356. BABYLON.AnimationEvent = AnimationEvent;
  51357. /**
  51358. * A cursor which tracks a point on a path
  51359. */
  51360. var PathCursor = /** @class */ (function () {
  51361. /**
  51362. * Initializes the path cursor
  51363. * @param path The path to track
  51364. */
  51365. function PathCursor(path) {
  51366. this.path = path;
  51367. /**
  51368. * Stores path cursor callbacks for when an onchange event is triggered
  51369. */
  51370. this._onchange = new Array();
  51371. /**
  51372. * The value of the path cursor
  51373. */
  51374. this.value = 0;
  51375. /**
  51376. * The animation array of the path cursor
  51377. */
  51378. this.animations = new Array();
  51379. }
  51380. /**
  51381. * Gets the cursor point on the path
  51382. * @returns A point on the path cursor at the cursor location
  51383. */
  51384. PathCursor.prototype.getPoint = function () {
  51385. var point = this.path.getPointAtLengthPosition(this.value);
  51386. return new BABYLON.Vector3(point.x, 0, point.y);
  51387. };
  51388. /**
  51389. * Moves the cursor ahead by the step amount
  51390. * @param step The amount to move the cursor forward
  51391. * @returns This path cursor
  51392. */
  51393. PathCursor.prototype.moveAhead = function (step) {
  51394. if (step === void 0) { step = 0.002; }
  51395. this.move(step);
  51396. return this;
  51397. };
  51398. /**
  51399. * Moves the cursor behind by the step amount
  51400. * @param step The amount to move the cursor back
  51401. * @returns This path cursor
  51402. */
  51403. PathCursor.prototype.moveBack = function (step) {
  51404. if (step === void 0) { step = 0.002; }
  51405. this.move(-step);
  51406. return this;
  51407. };
  51408. /**
  51409. * Moves the cursor by the step amount
  51410. * If the step amount is greater than one, an exception is thrown
  51411. * @param step The amount to move the cursor
  51412. * @returns This path cursor
  51413. */
  51414. PathCursor.prototype.move = function (step) {
  51415. if (Math.abs(step) > 1) {
  51416. throw "step size should be less than 1.";
  51417. }
  51418. this.value += step;
  51419. this.ensureLimits();
  51420. this.raiseOnChange();
  51421. return this;
  51422. };
  51423. /**
  51424. * Ensures that the value is limited between zero and one
  51425. * @returns This path cursor
  51426. */
  51427. PathCursor.prototype.ensureLimits = function () {
  51428. while (this.value > 1) {
  51429. this.value -= 1;
  51430. }
  51431. while (this.value < 0) {
  51432. this.value += 1;
  51433. }
  51434. return this;
  51435. };
  51436. /**
  51437. * Runs onchange callbacks on change (used by the animation engine)
  51438. * @returns This path cursor
  51439. */
  51440. PathCursor.prototype.raiseOnChange = function () {
  51441. var _this = this;
  51442. this._onchange.forEach(function (f) { return f(_this); });
  51443. return this;
  51444. };
  51445. /**
  51446. * Executes a function on change
  51447. * @param f A path cursor onchange callback
  51448. * @returns This path cursor
  51449. */
  51450. PathCursor.prototype.onchange = function (f) {
  51451. this._onchange.push(f);
  51452. return this;
  51453. };
  51454. return PathCursor;
  51455. }());
  51456. BABYLON.PathCursor = PathCursor;
  51457. /**
  51458. * Enum for the animation key frame interpolation type
  51459. */
  51460. var AnimationKeyInterpolation;
  51461. (function (AnimationKeyInterpolation) {
  51462. /**
  51463. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  51464. */
  51465. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  51466. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  51467. /**
  51468. * Class used to store any kind of animation
  51469. */
  51470. var Animation = /** @class */ (function () {
  51471. /**
  51472. * Initializes the animation
  51473. * @param name Name of the animation
  51474. * @param targetProperty Property to animate
  51475. * @param framePerSecond The frames per second of the animation
  51476. * @param dataType The data type of the animation
  51477. * @param loopMode The loop mode of the animation
  51478. * @param enableBlendings Specifies if blending should be enabled
  51479. */
  51480. function Animation(
  51481. /**Name of the animation */
  51482. name,
  51483. /**Property to animate */
  51484. targetProperty,
  51485. /**The frames per second of the animation */
  51486. framePerSecond,
  51487. /**The data type of the animation */
  51488. dataType,
  51489. /**The loop mode of the animation */
  51490. loopMode,
  51491. /**Specifies if blending should be enabled */
  51492. enableBlending) {
  51493. this.name = name;
  51494. this.targetProperty = targetProperty;
  51495. this.framePerSecond = framePerSecond;
  51496. this.dataType = dataType;
  51497. this.loopMode = loopMode;
  51498. this.enableBlending = enableBlending;
  51499. /**
  51500. * @hidden Internal use only
  51501. */
  51502. this._runtimeAnimations = new Array();
  51503. /**
  51504. * The set of event that will be linked to this animation
  51505. */
  51506. this._events = new Array();
  51507. /**
  51508. * Stores the blending speed of the animation
  51509. */
  51510. this.blendingSpeed = 0.01;
  51511. /**
  51512. * Stores the animation ranges for the animation
  51513. */
  51514. this._ranges = {};
  51515. this.targetPropertyPath = targetProperty.split(".");
  51516. this.dataType = dataType;
  51517. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  51518. }
  51519. /**
  51520. * @hidden Internal use
  51521. */
  51522. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  51523. var dataType = undefined;
  51524. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  51525. dataType = Animation.ANIMATIONTYPE_FLOAT;
  51526. }
  51527. else if (from instanceof BABYLON.Quaternion) {
  51528. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  51529. }
  51530. else if (from instanceof BABYLON.Vector3) {
  51531. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  51532. }
  51533. else if (from instanceof BABYLON.Vector2) {
  51534. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  51535. }
  51536. else if (from instanceof BABYLON.Color3) {
  51537. dataType = Animation.ANIMATIONTYPE_COLOR3;
  51538. }
  51539. else if (from instanceof BABYLON.Size) {
  51540. dataType = Animation.ANIMATIONTYPE_SIZE;
  51541. }
  51542. if (dataType == undefined) {
  51543. return null;
  51544. }
  51545. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  51546. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  51547. animation.setKeys(keys);
  51548. if (easingFunction !== undefined) {
  51549. animation.setEasingFunction(easingFunction);
  51550. }
  51551. return animation;
  51552. };
  51553. /**
  51554. * Sets up an animation
  51555. * @param property The property to animate
  51556. * @param animationType The animation type to apply
  51557. * @param framePerSecond The frames per second of the animation
  51558. * @param easingFunction The easing function used in the animation
  51559. * @returns The created animation
  51560. */
  51561. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  51562. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  51563. animation.setEasingFunction(easingFunction);
  51564. return animation;
  51565. };
  51566. /**
  51567. * Create and start an animation on a node
  51568. * @param name defines the name of the global animation that will be run on all nodes
  51569. * @param node defines the root node where the animation will take place
  51570. * @param targetProperty defines property to animate
  51571. * @param framePerSecond defines the number of frame per second yo use
  51572. * @param totalFrame defines the number of frames in total
  51573. * @param from defines the initial value
  51574. * @param to defines the final value
  51575. * @param loopMode defines which loop mode you want to use (off by default)
  51576. * @param easingFunction defines the easing function to use (linear by default)
  51577. * @param onAnimationEnd defines the callback to call when animation end
  51578. * @returns the animatable created for this animation
  51579. */
  51580. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51581. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51582. if (!animation) {
  51583. return null;
  51584. }
  51585. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51586. };
  51587. /**
  51588. * Create and start an animation on a node and its descendants
  51589. * @param name defines the name of the global animation that will be run on all nodes
  51590. * @param node defines the root node where the animation will take place
  51591. * @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
  51592. * @param targetProperty defines property to animate
  51593. * @param framePerSecond defines the number of frame per second to use
  51594. * @param totalFrame defines the number of frames in total
  51595. * @param from defines the initial value
  51596. * @param to defines the final value
  51597. * @param loopMode defines which loop mode you want to use (off by default)
  51598. * @param easingFunction defines the easing function to use (linear by default)
  51599. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  51600. * @returns the list of animatables created for all nodes
  51601. * @example https://www.babylonjs-playground.com/#MH0VLI
  51602. */
  51603. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51604. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51605. if (!animation) {
  51606. return null;
  51607. }
  51608. var scene = node.getScene();
  51609. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51610. };
  51611. /**
  51612. * Creates a new animation, merges it with the existing animations and starts it
  51613. * @param name Name of the animation
  51614. * @param node Node which contains the scene that begins the animations
  51615. * @param targetProperty Specifies which property to animate
  51616. * @param framePerSecond The frames per second of the animation
  51617. * @param totalFrame The total number of frames
  51618. * @param from The frame at the beginning of the animation
  51619. * @param to The frame at the end of the animation
  51620. * @param loopMode Specifies the loop mode of the animation
  51621. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  51622. * @param onAnimationEnd Callback to run once the animation is complete
  51623. * @returns Nullable animation
  51624. */
  51625. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51626. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51627. if (!animation) {
  51628. return null;
  51629. }
  51630. node.animations.push(animation);
  51631. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51632. };
  51633. /**
  51634. * Transition property of an host to the target Value
  51635. * @param property The property to transition
  51636. * @param targetValue The target Value of the property
  51637. * @param host The object where the property to animate belongs
  51638. * @param scene Scene used to run the animation
  51639. * @param frameRate Framerate (in frame/s) to use
  51640. * @param transition The transition type we want to use
  51641. * @param duration The duration of the animation, in milliseconds
  51642. * @param onAnimationEnd Callback trigger at the end of the animation
  51643. * @returns Nullable animation
  51644. */
  51645. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  51646. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  51647. if (duration <= 0) {
  51648. host[property] = targetValue;
  51649. if (onAnimationEnd) {
  51650. onAnimationEnd();
  51651. }
  51652. return null;
  51653. }
  51654. var endFrame = frameRate * (duration / 1000);
  51655. transition.setKeys([{
  51656. frame: 0,
  51657. value: host[property].clone ? host[property].clone() : host[property]
  51658. },
  51659. {
  51660. frame: endFrame,
  51661. value: targetValue
  51662. }]);
  51663. if (!host.animations) {
  51664. host.animations = [];
  51665. }
  51666. host.animations.push(transition);
  51667. var animation = scene.beginAnimation(host, 0, endFrame, false);
  51668. animation.onAnimationEnd = onAnimationEnd;
  51669. return animation;
  51670. };
  51671. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  51672. /**
  51673. * Return the array of runtime animations currently using this animation
  51674. */
  51675. get: function () {
  51676. return this._runtimeAnimations;
  51677. },
  51678. enumerable: true,
  51679. configurable: true
  51680. });
  51681. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  51682. /**
  51683. * Specifies if any of the runtime animations are currently running
  51684. */
  51685. get: function () {
  51686. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  51687. var runtimeAnimation = _a[_i];
  51688. if (!runtimeAnimation.isStopped) {
  51689. return true;
  51690. }
  51691. }
  51692. return false;
  51693. },
  51694. enumerable: true,
  51695. configurable: true
  51696. });
  51697. // Methods
  51698. /**
  51699. * Converts the animation to a string
  51700. * @param fullDetails support for multiple levels of logging within scene loading
  51701. * @returns String form of the animation
  51702. */
  51703. Animation.prototype.toString = function (fullDetails) {
  51704. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51705. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51706. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51707. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51708. if (fullDetails) {
  51709. ret += ", Ranges: {";
  51710. var first = true;
  51711. for (var name in this._ranges) {
  51712. if (first) {
  51713. ret += ", ";
  51714. first = false;
  51715. }
  51716. ret += name;
  51717. }
  51718. ret += "}";
  51719. }
  51720. return ret;
  51721. };
  51722. /**
  51723. * Add an event to this animation
  51724. * @param event Event to add
  51725. */
  51726. Animation.prototype.addEvent = function (event) {
  51727. this._events.push(event);
  51728. };
  51729. /**
  51730. * Remove all events found at the given frame
  51731. * @param frame The frame to remove events from
  51732. */
  51733. Animation.prototype.removeEvents = function (frame) {
  51734. for (var index = 0; index < this._events.length; index++) {
  51735. if (this._events[index].frame === frame) {
  51736. this._events.splice(index, 1);
  51737. index--;
  51738. }
  51739. }
  51740. };
  51741. /**
  51742. * Retrieves all the events from the animation
  51743. * @returns Events from the animation
  51744. */
  51745. Animation.prototype.getEvents = function () {
  51746. return this._events;
  51747. };
  51748. /**
  51749. * Creates an animation range
  51750. * @param name Name of the animation range
  51751. * @param from Starting frame of the animation range
  51752. * @param to Ending frame of the animation
  51753. */
  51754. Animation.prototype.createRange = function (name, from, to) {
  51755. // check name not already in use; could happen for bones after serialized
  51756. if (!this._ranges[name]) {
  51757. this._ranges[name] = new AnimationRange(name, from, to);
  51758. }
  51759. };
  51760. /**
  51761. * Deletes an animation range by name
  51762. * @param name Name of the animation range to delete
  51763. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51764. */
  51765. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51766. if (deleteFrames === void 0) { deleteFrames = true; }
  51767. var range = this._ranges[name];
  51768. if (!range) {
  51769. return;
  51770. }
  51771. if (deleteFrames) {
  51772. var from = range.from;
  51773. var to = range.to;
  51774. // this loop MUST go high to low for multiple splices to work
  51775. for (var key = this._keys.length - 1; key >= 0; key--) {
  51776. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51777. this._keys.splice(key, 1);
  51778. }
  51779. }
  51780. }
  51781. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51782. };
  51783. /**
  51784. * Gets the animation range by name, or null if not defined
  51785. * @param name Name of the animation range
  51786. * @returns Nullable animation range
  51787. */
  51788. Animation.prototype.getRange = function (name) {
  51789. return this._ranges[name];
  51790. };
  51791. /**
  51792. * Gets the key frames from the animation
  51793. * @returns The key frames of the animation
  51794. */
  51795. Animation.prototype.getKeys = function () {
  51796. return this._keys;
  51797. };
  51798. /**
  51799. * Gets the highest frame rate of the animation
  51800. * @returns Highest frame rate of the animation
  51801. */
  51802. Animation.prototype.getHighestFrame = function () {
  51803. var ret = 0;
  51804. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51805. if (ret < this._keys[key].frame) {
  51806. ret = this._keys[key].frame;
  51807. }
  51808. }
  51809. return ret;
  51810. };
  51811. /**
  51812. * Gets the easing function of the animation
  51813. * @returns Easing function of the animation
  51814. */
  51815. Animation.prototype.getEasingFunction = function () {
  51816. return this._easingFunction;
  51817. };
  51818. /**
  51819. * Sets the easing function of the animation
  51820. * @param easingFunction A custom mathematical formula for animation
  51821. */
  51822. Animation.prototype.setEasingFunction = function (easingFunction) {
  51823. this._easingFunction = easingFunction;
  51824. };
  51825. /**
  51826. * Interpolates a scalar linearly
  51827. * @param startValue Start value of the animation curve
  51828. * @param endValue End value of the animation curve
  51829. * @param gradient Scalar amount to interpolate
  51830. * @returns Interpolated scalar value
  51831. */
  51832. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51833. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51834. };
  51835. /**
  51836. * Interpolates a scalar cubically
  51837. * @param startValue Start value of the animation curve
  51838. * @param outTangent End tangent of the animation
  51839. * @param endValue End value of the animation curve
  51840. * @param inTangent Start tangent of the animation curve
  51841. * @param gradient Scalar amount to interpolate
  51842. * @returns Interpolated scalar value
  51843. */
  51844. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51845. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51846. };
  51847. /**
  51848. * Interpolates a quaternion using a spherical linear interpolation
  51849. * @param startValue Start value of the animation curve
  51850. * @param endValue End value of the animation curve
  51851. * @param gradient Scalar amount to interpolate
  51852. * @returns Interpolated quaternion value
  51853. */
  51854. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51855. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51856. };
  51857. /**
  51858. * Interpolates a quaternion cubically
  51859. * @param startValue Start value of the animation curve
  51860. * @param outTangent End tangent of the animation curve
  51861. * @param endValue End value of the animation curve
  51862. * @param inTangent Start tangent of the animation curve
  51863. * @param gradient Scalar amount to interpolate
  51864. * @returns Interpolated quaternion value
  51865. */
  51866. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51867. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51868. };
  51869. /**
  51870. * Interpolates a Vector3 linearl
  51871. * @param startValue Start value of the animation curve
  51872. * @param endValue End value of the animation curve
  51873. * @param gradient Scalar amount to interpolate
  51874. * @returns Interpolated scalar value
  51875. */
  51876. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51877. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51878. };
  51879. /**
  51880. * Interpolates a Vector3 cubically
  51881. * @param startValue Start value of the animation curve
  51882. * @param outTangent End tangent of the animation
  51883. * @param endValue End value of the animation curve
  51884. * @param inTangent Start tangent of the animation curve
  51885. * @param gradient Scalar amount to interpolate
  51886. * @returns InterpolatedVector3 value
  51887. */
  51888. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51889. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51890. };
  51891. /**
  51892. * Interpolates a Vector2 linearly
  51893. * @param startValue Start value of the animation curve
  51894. * @param endValue End value of the animation curve
  51895. * @param gradient Scalar amount to interpolate
  51896. * @returns Interpolated Vector2 value
  51897. */
  51898. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51899. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51900. };
  51901. /**
  51902. * Interpolates a Vector2 cubically
  51903. * @param startValue Start value of the animation curve
  51904. * @param outTangent End tangent of the animation
  51905. * @param endValue End value of the animation curve
  51906. * @param inTangent Start tangent of the animation curve
  51907. * @param gradient Scalar amount to interpolate
  51908. * @returns Interpolated Vector2 value
  51909. */
  51910. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51911. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51912. };
  51913. /**
  51914. * Interpolates a size linearly
  51915. * @param startValue Start value of the animation curve
  51916. * @param endValue End value of the animation curve
  51917. * @param gradient Scalar amount to interpolate
  51918. * @returns Interpolated Size value
  51919. */
  51920. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51921. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51922. };
  51923. /**
  51924. * Interpolates a Color3 linearly
  51925. * @param startValue Start value of the animation curve
  51926. * @param endValue End value of the animation curve
  51927. * @param gradient Scalar amount to interpolate
  51928. * @returns Interpolated Color3 value
  51929. */
  51930. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51931. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51932. };
  51933. /**
  51934. * @hidden Internal use only
  51935. */
  51936. Animation.prototype._getKeyValue = function (value) {
  51937. if (typeof value === "function") {
  51938. return value();
  51939. }
  51940. return value;
  51941. };
  51942. /**
  51943. * @hidden Internal use only
  51944. */
  51945. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51946. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51947. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51948. }
  51949. var keys = this.getKeys();
  51950. // Try to get a hash to find the right key
  51951. 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));
  51952. if (keys[startKeyIndex].frame >= currentFrame) {
  51953. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51954. startKeyIndex--;
  51955. }
  51956. }
  51957. for (var key = startKeyIndex; key < keys.length; key++) {
  51958. var endKey = keys[key + 1];
  51959. if (endKey.frame >= currentFrame) {
  51960. var startKey = keys[key];
  51961. var startValue = this._getKeyValue(startKey.value);
  51962. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51963. return startValue;
  51964. }
  51965. var endValue = this._getKeyValue(endKey.value);
  51966. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51967. var frameDelta = endKey.frame - startKey.frame;
  51968. // gradient : percent of currentFrame between the frame inf and the frame sup
  51969. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51970. // check for easingFunction and correction of gradient
  51971. var easingFunction = this.getEasingFunction();
  51972. if (easingFunction != null) {
  51973. gradient = easingFunction.ease(gradient);
  51974. }
  51975. switch (this.dataType) {
  51976. // Float
  51977. case Animation.ANIMATIONTYPE_FLOAT:
  51978. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51979. switch (loopMode) {
  51980. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51981. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51982. return floatValue;
  51983. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51984. return offsetValue * repeatCount + floatValue;
  51985. }
  51986. break;
  51987. // Quaternion
  51988. case Animation.ANIMATIONTYPE_QUATERNION:
  51989. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51990. switch (loopMode) {
  51991. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51992. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51993. return quatValue;
  51994. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51995. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51996. }
  51997. return quatValue;
  51998. // Vector3
  51999. case Animation.ANIMATIONTYPE_VECTOR3:
  52000. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  52001. switch (loopMode) {
  52002. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52003. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52004. return vec3Value;
  52005. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52006. return vec3Value.add(offsetValue.scale(repeatCount));
  52007. }
  52008. // Vector2
  52009. case Animation.ANIMATIONTYPE_VECTOR2:
  52010. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  52011. switch (loopMode) {
  52012. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52013. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52014. return vec2Value;
  52015. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52016. return vec2Value.add(offsetValue.scale(repeatCount));
  52017. }
  52018. // Size
  52019. case Animation.ANIMATIONTYPE_SIZE:
  52020. switch (loopMode) {
  52021. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52022. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52023. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  52024. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52025. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52026. }
  52027. // Color3
  52028. case Animation.ANIMATIONTYPE_COLOR3:
  52029. switch (loopMode) {
  52030. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52031. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52032. return this.color3InterpolateFunction(startValue, endValue, gradient);
  52033. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52034. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52035. }
  52036. // Matrix
  52037. case Animation.ANIMATIONTYPE_MATRIX:
  52038. switch (loopMode) {
  52039. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52040. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52041. if (Animation.AllowMatricesInterpolation) {
  52042. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  52043. }
  52044. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52045. return startValue;
  52046. }
  52047. default:
  52048. break;
  52049. }
  52050. break;
  52051. }
  52052. }
  52053. return this._getKeyValue(keys[keys.length - 1].value);
  52054. };
  52055. /**
  52056. * Defines the function to use to interpolate matrices
  52057. * @param startValue defines the start matrix
  52058. * @param endValue defines the end matrix
  52059. * @param gradient defines the gradient between both matrices
  52060. * @param result defines an optional target matrix where to store the interpolation
  52061. * @returns the interpolated matrix
  52062. */
  52063. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  52064. if (Animation.AllowMatrixDecomposeForInterpolation) {
  52065. if (result) {
  52066. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  52067. return result;
  52068. }
  52069. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  52070. }
  52071. if (result) {
  52072. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  52073. return result;
  52074. }
  52075. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  52076. };
  52077. /**
  52078. * Makes a copy of the animation
  52079. * @returns Cloned animation
  52080. */
  52081. Animation.prototype.clone = function () {
  52082. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  52083. clone.enableBlending = this.enableBlending;
  52084. clone.blendingSpeed = this.blendingSpeed;
  52085. if (this._keys) {
  52086. clone.setKeys(this._keys);
  52087. }
  52088. if (this._ranges) {
  52089. clone._ranges = {};
  52090. for (var name in this._ranges) {
  52091. var range = this._ranges[name];
  52092. if (!range) {
  52093. continue;
  52094. }
  52095. clone._ranges[name] = range.clone();
  52096. }
  52097. }
  52098. return clone;
  52099. };
  52100. /**
  52101. * Sets the key frames of the animation
  52102. * @param values The animation key frames to set
  52103. */
  52104. Animation.prototype.setKeys = function (values) {
  52105. this._keys = values.slice(0);
  52106. };
  52107. /**
  52108. * Serializes the animation to an object
  52109. * @returns Serialized object
  52110. */
  52111. Animation.prototype.serialize = function () {
  52112. var serializationObject = {};
  52113. serializationObject.name = this.name;
  52114. serializationObject.property = this.targetProperty;
  52115. serializationObject.framePerSecond = this.framePerSecond;
  52116. serializationObject.dataType = this.dataType;
  52117. serializationObject.loopBehavior = this.loopMode;
  52118. serializationObject.enableBlending = this.enableBlending;
  52119. serializationObject.blendingSpeed = this.blendingSpeed;
  52120. var dataType = this.dataType;
  52121. serializationObject.keys = [];
  52122. var keys = this.getKeys();
  52123. for (var index = 0; index < keys.length; index++) {
  52124. var animationKey = keys[index];
  52125. var key = {};
  52126. key.frame = animationKey.frame;
  52127. switch (dataType) {
  52128. case Animation.ANIMATIONTYPE_FLOAT:
  52129. key.values = [animationKey.value];
  52130. break;
  52131. case Animation.ANIMATIONTYPE_QUATERNION:
  52132. case Animation.ANIMATIONTYPE_MATRIX:
  52133. case Animation.ANIMATIONTYPE_VECTOR3:
  52134. case Animation.ANIMATIONTYPE_COLOR3:
  52135. key.values = animationKey.value.asArray();
  52136. break;
  52137. }
  52138. serializationObject.keys.push(key);
  52139. }
  52140. serializationObject.ranges = [];
  52141. for (var name in this._ranges) {
  52142. var source = this._ranges[name];
  52143. if (!source) {
  52144. continue;
  52145. }
  52146. var range = {};
  52147. range.name = name;
  52148. range.from = source.from;
  52149. range.to = source.to;
  52150. serializationObject.ranges.push(range);
  52151. }
  52152. return serializationObject;
  52153. };
  52154. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  52155. /**
  52156. * Get the float animation type
  52157. */
  52158. get: function () {
  52159. return Animation._ANIMATIONTYPE_FLOAT;
  52160. },
  52161. enumerable: true,
  52162. configurable: true
  52163. });
  52164. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  52165. /**
  52166. * Get the Vector3 animation type
  52167. */
  52168. get: function () {
  52169. return Animation._ANIMATIONTYPE_VECTOR3;
  52170. },
  52171. enumerable: true,
  52172. configurable: true
  52173. });
  52174. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  52175. /**
  52176. * Get the Vector2 animation type
  52177. */
  52178. get: function () {
  52179. return Animation._ANIMATIONTYPE_VECTOR2;
  52180. },
  52181. enumerable: true,
  52182. configurable: true
  52183. });
  52184. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  52185. /**
  52186. * Get the Size animation type
  52187. */
  52188. get: function () {
  52189. return Animation._ANIMATIONTYPE_SIZE;
  52190. },
  52191. enumerable: true,
  52192. configurable: true
  52193. });
  52194. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  52195. /**
  52196. * Get the Quaternion animation type
  52197. */
  52198. get: function () {
  52199. return Animation._ANIMATIONTYPE_QUATERNION;
  52200. },
  52201. enumerable: true,
  52202. configurable: true
  52203. });
  52204. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52205. /**
  52206. * Get the Matrix animation type
  52207. */
  52208. get: function () {
  52209. return Animation._ANIMATIONTYPE_MATRIX;
  52210. },
  52211. enumerable: true,
  52212. configurable: true
  52213. });
  52214. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52215. /**
  52216. * Get the Color3 animation type
  52217. */
  52218. get: function () {
  52219. return Animation._ANIMATIONTYPE_COLOR3;
  52220. },
  52221. enumerable: true,
  52222. configurable: true
  52223. });
  52224. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52225. /**
  52226. * Get the Relative Loop Mode
  52227. */
  52228. get: function () {
  52229. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52230. },
  52231. enumerable: true,
  52232. configurable: true
  52233. });
  52234. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52235. /**
  52236. * Get the Cycle Loop Mode
  52237. */
  52238. get: function () {
  52239. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52240. },
  52241. enumerable: true,
  52242. configurable: true
  52243. });
  52244. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52245. /**
  52246. * Get the Constant Loop Mode
  52247. */
  52248. get: function () {
  52249. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52250. },
  52251. enumerable: true,
  52252. configurable: true
  52253. });
  52254. /** @hidden */
  52255. Animation._UniversalLerp = function (left, right, amount) {
  52256. var constructor = left.constructor;
  52257. if (constructor.Lerp) { // Lerp supported
  52258. return constructor.Lerp(left, right, amount);
  52259. }
  52260. else if (constructor.Slerp) { // Slerp supported
  52261. return constructor.Slerp(left, right, amount);
  52262. }
  52263. else if (left.toFixed) { // Number
  52264. return left * (1.0 - amount) + amount * right;
  52265. }
  52266. else { // Blending not supported
  52267. return right;
  52268. }
  52269. };
  52270. /**
  52271. * Parses an animation object and creates an animation
  52272. * @param parsedAnimation Parsed animation object
  52273. * @returns Animation object
  52274. */
  52275. Animation.Parse = function (parsedAnimation) {
  52276. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52277. var dataType = parsedAnimation.dataType;
  52278. var keys = [];
  52279. var data;
  52280. var index;
  52281. if (parsedAnimation.enableBlending) {
  52282. animation.enableBlending = parsedAnimation.enableBlending;
  52283. }
  52284. if (parsedAnimation.blendingSpeed) {
  52285. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52286. }
  52287. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52288. var key = parsedAnimation.keys[index];
  52289. var inTangent;
  52290. var outTangent;
  52291. switch (dataType) {
  52292. case Animation.ANIMATIONTYPE_FLOAT:
  52293. data = key.values[0];
  52294. if (key.values.length >= 1) {
  52295. inTangent = key.values[1];
  52296. }
  52297. if (key.values.length >= 2) {
  52298. outTangent = key.values[2];
  52299. }
  52300. break;
  52301. case Animation.ANIMATIONTYPE_QUATERNION:
  52302. data = BABYLON.Quaternion.FromArray(key.values);
  52303. if (key.values.length >= 8) {
  52304. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52305. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52306. inTangent = _inTangent;
  52307. }
  52308. }
  52309. if (key.values.length >= 12) {
  52310. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  52311. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  52312. outTangent = _outTangent;
  52313. }
  52314. }
  52315. break;
  52316. case Animation.ANIMATIONTYPE_MATRIX:
  52317. data = BABYLON.Matrix.FromArray(key.values);
  52318. break;
  52319. case Animation.ANIMATIONTYPE_COLOR3:
  52320. data = BABYLON.Color3.FromArray(key.values);
  52321. break;
  52322. case Animation.ANIMATIONTYPE_VECTOR3:
  52323. default:
  52324. data = BABYLON.Vector3.FromArray(key.values);
  52325. break;
  52326. }
  52327. var keyData = {};
  52328. keyData.frame = key.frame;
  52329. keyData.value = data;
  52330. if (inTangent != undefined) {
  52331. keyData.inTangent = inTangent;
  52332. }
  52333. if (outTangent != undefined) {
  52334. keyData.outTangent = outTangent;
  52335. }
  52336. keys.push(keyData);
  52337. }
  52338. animation.setKeys(keys);
  52339. if (parsedAnimation.ranges) {
  52340. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  52341. data = parsedAnimation.ranges[index];
  52342. animation.createRange(data.name, data.from, data.to);
  52343. }
  52344. }
  52345. return animation;
  52346. };
  52347. /**
  52348. * Appends the serialized animations from the source animations
  52349. * @param source Source containing the animations
  52350. * @param destination Target to store the animations
  52351. */
  52352. Animation.AppendSerializedAnimations = function (source, destination) {
  52353. if (source.animations) {
  52354. destination.animations = [];
  52355. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  52356. var animation = source.animations[animationIndex];
  52357. destination.animations.push(animation.serialize());
  52358. }
  52359. }
  52360. };
  52361. /**
  52362. * Use matrix interpolation instead of using direct key value when animating matrices
  52363. */
  52364. Animation.AllowMatricesInterpolation = false;
  52365. /**
  52366. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  52367. */
  52368. Animation.AllowMatrixDecomposeForInterpolation = true;
  52369. // Statics
  52370. /**
  52371. * Float animation type
  52372. */
  52373. Animation._ANIMATIONTYPE_FLOAT = 0;
  52374. /**
  52375. * Vector3 animation type
  52376. */
  52377. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  52378. /**
  52379. * Quaternion animation type
  52380. */
  52381. Animation._ANIMATIONTYPE_QUATERNION = 2;
  52382. /**
  52383. * Matrix animation type
  52384. */
  52385. Animation._ANIMATIONTYPE_MATRIX = 3;
  52386. /**
  52387. * Color3 animation type
  52388. */
  52389. Animation._ANIMATIONTYPE_COLOR3 = 4;
  52390. /**
  52391. * Vector2 animation type
  52392. */
  52393. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  52394. /**
  52395. * Size animation type
  52396. */
  52397. Animation._ANIMATIONTYPE_SIZE = 6;
  52398. /**
  52399. * Relative Loop Mode
  52400. */
  52401. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  52402. /**
  52403. * Cycle Loop Mode
  52404. */
  52405. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  52406. /**
  52407. * Constant Loop Mode
  52408. */
  52409. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  52410. return Animation;
  52411. }());
  52412. BABYLON.Animation = Animation;
  52413. })(BABYLON || (BABYLON = {}));
  52414. //# sourceMappingURL=babylon.animation.js.map
  52415. var BABYLON;
  52416. (function (BABYLON) {
  52417. /**
  52418. * This class defines the direct association between an animation and a target
  52419. */
  52420. var TargetedAnimation = /** @class */ (function () {
  52421. function TargetedAnimation() {
  52422. }
  52423. return TargetedAnimation;
  52424. }());
  52425. BABYLON.TargetedAnimation = TargetedAnimation;
  52426. /**
  52427. * Use this class to create coordinated animations on multiple targets
  52428. */
  52429. var AnimationGroup = /** @class */ (function () {
  52430. /**
  52431. * Instantiates a new Animation Group.
  52432. * This helps managing several animations at once.
  52433. * @see http://doc.babylonjs.com/how_to/group
  52434. * @param name Defines the name of the group
  52435. * @param scene Defines the scene the group belongs to
  52436. */
  52437. function AnimationGroup(
  52438. /** The name of the animation group */
  52439. name, scene) {
  52440. if (scene === void 0) { scene = null; }
  52441. this.name = name;
  52442. this._targetedAnimations = new Array();
  52443. this._animatables = new Array();
  52444. this._from = Number.MAX_VALUE;
  52445. this._to = -Number.MAX_VALUE;
  52446. this._speedRatio = 1;
  52447. /**
  52448. * This observable will notify when one animation have ended.
  52449. */
  52450. this.onAnimationEndObservable = new BABYLON.Observable();
  52451. /**
  52452. * This observable will notify when all animations have ended.
  52453. */
  52454. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  52455. /**
  52456. * This observable will notify when all animations have paused.
  52457. */
  52458. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  52459. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52460. this._scene.animationGroups.push(this);
  52461. }
  52462. Object.defineProperty(AnimationGroup.prototype, "from", {
  52463. /**
  52464. * Gets the first frame
  52465. */
  52466. get: function () {
  52467. return this._from;
  52468. },
  52469. enumerable: true,
  52470. configurable: true
  52471. });
  52472. Object.defineProperty(AnimationGroup.prototype, "to", {
  52473. /**
  52474. * Gets the last frame
  52475. */
  52476. get: function () {
  52477. return this._to;
  52478. },
  52479. enumerable: true,
  52480. configurable: true
  52481. });
  52482. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  52483. /**
  52484. * Define if the animations are started
  52485. */
  52486. get: function () {
  52487. return this._isStarted;
  52488. },
  52489. enumerable: true,
  52490. configurable: true
  52491. });
  52492. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  52493. /**
  52494. * Gets or sets the speed ratio to use for all animations
  52495. */
  52496. get: function () {
  52497. return this._speedRatio;
  52498. },
  52499. /**
  52500. * Gets or sets the speed ratio to use for all animations
  52501. */
  52502. set: function (value) {
  52503. if (this._speedRatio === value) {
  52504. return;
  52505. }
  52506. this._speedRatio = value;
  52507. for (var index = 0; index < this._animatables.length; index++) {
  52508. var animatable = this._animatables[index];
  52509. animatable.speedRatio = this._speedRatio;
  52510. }
  52511. },
  52512. enumerable: true,
  52513. configurable: true
  52514. });
  52515. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  52516. /**
  52517. * Gets the targeted animations for this animation group
  52518. */
  52519. get: function () {
  52520. return this._targetedAnimations;
  52521. },
  52522. enumerable: true,
  52523. configurable: true
  52524. });
  52525. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  52526. /**
  52527. * returning the list of animatables controlled by this animation group.
  52528. */
  52529. get: function () {
  52530. return this._animatables;
  52531. },
  52532. enumerable: true,
  52533. configurable: true
  52534. });
  52535. /**
  52536. * Add an animation (with its target) in the group
  52537. * @param animation defines the animation we want to add
  52538. * @param target defines the target of the animation
  52539. * @returns the {BABYLON.TargetedAnimation} object
  52540. */
  52541. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  52542. var targetedAnimation = {
  52543. animation: animation,
  52544. target: target
  52545. };
  52546. var keys = animation.getKeys();
  52547. if (this._from > keys[0].frame) {
  52548. this._from = keys[0].frame;
  52549. }
  52550. if (this._to < keys[keys.length - 1].frame) {
  52551. this._to = keys[keys.length - 1].frame;
  52552. }
  52553. this._targetedAnimations.push(targetedAnimation);
  52554. return targetedAnimation;
  52555. };
  52556. /**
  52557. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  52558. * It can add constant keys at begin or end
  52559. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  52560. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  52561. * @returns the animation group
  52562. */
  52563. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  52564. if (beginFrame === void 0) { beginFrame = null; }
  52565. if (endFrame === void 0) { endFrame = null; }
  52566. if (beginFrame == null)
  52567. beginFrame = this._from;
  52568. if (endFrame == null)
  52569. endFrame = this._to;
  52570. for (var index = 0; index < this._targetedAnimations.length; index++) {
  52571. var targetedAnimation = this._targetedAnimations[index];
  52572. var keys = targetedAnimation.animation.getKeys();
  52573. var startKey = keys[0];
  52574. var endKey = keys[keys.length - 1];
  52575. if (startKey.frame > beginFrame) {
  52576. var newKey = {
  52577. frame: beginFrame,
  52578. value: startKey.value,
  52579. inTangent: startKey.inTangent,
  52580. outTangent: startKey.outTangent,
  52581. interpolation: startKey.interpolation
  52582. };
  52583. keys.splice(0, 0, newKey);
  52584. }
  52585. if (endKey.frame < endFrame) {
  52586. var newKey = {
  52587. frame: endFrame,
  52588. value: endKey.value,
  52589. inTangent: endKey.outTangent,
  52590. outTangent: endKey.outTangent,
  52591. interpolation: endKey.interpolation
  52592. };
  52593. keys.push(newKey);
  52594. }
  52595. }
  52596. this._from = beginFrame;
  52597. this._to = endFrame;
  52598. return this;
  52599. };
  52600. /**
  52601. * Start all animations on given targets
  52602. * @param loop defines if animations must loop
  52603. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  52604. * @param from defines the from key (optional)
  52605. * @param to defines the to key (optional)
  52606. * @returns the current animation group
  52607. */
  52608. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  52609. var _this = this;
  52610. if (loop === void 0) { loop = false; }
  52611. if (speedRatio === void 0) { speedRatio = 1; }
  52612. if (this._isStarted || this._targetedAnimations.length === 0) {
  52613. return this;
  52614. }
  52615. var _loop_1 = function (targetedAnimation) {
  52616. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  52617. animatable.onAnimationEnd = function () {
  52618. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  52619. _this._checkAnimationGroupEnded(animatable);
  52620. };
  52621. this_1._animatables.push(animatable);
  52622. };
  52623. var this_1 = this;
  52624. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  52625. var targetedAnimation = _a[_i];
  52626. _loop_1(targetedAnimation);
  52627. }
  52628. this._speedRatio = speedRatio;
  52629. this._isStarted = true;
  52630. return this;
  52631. };
  52632. /**
  52633. * Pause all animations
  52634. * @returns the animation group
  52635. */
  52636. AnimationGroup.prototype.pause = function () {
  52637. if (!this._isStarted) {
  52638. return this;
  52639. }
  52640. for (var index = 0; index < this._animatables.length; index++) {
  52641. var animatable = this._animatables[index];
  52642. animatable.pause();
  52643. }
  52644. this.onAnimationGroupPauseObservable.notifyObservers(this);
  52645. return this;
  52646. };
  52647. /**
  52648. * Play all animations to initial state
  52649. * This function will start() the animations if they were not started or will restart() them if they were paused
  52650. * @param loop defines if animations must loop
  52651. * @returns the animation group
  52652. */
  52653. AnimationGroup.prototype.play = function (loop) {
  52654. // only if all animatables are ready and exist
  52655. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  52656. if (loop !== undefined) {
  52657. for (var index = 0; index < this._animatables.length; index++) {
  52658. var animatable = this._animatables[index];
  52659. animatable.loopAnimation = loop;
  52660. }
  52661. }
  52662. this.restart();
  52663. }
  52664. else {
  52665. this.stop();
  52666. this.start(loop, this._speedRatio);
  52667. }
  52668. return this;
  52669. };
  52670. /**
  52671. * Reset all animations to initial state
  52672. * @returns the animation group
  52673. */
  52674. AnimationGroup.prototype.reset = function () {
  52675. if (!this._isStarted) {
  52676. return this;
  52677. }
  52678. for (var index = 0; index < this._animatables.length; index++) {
  52679. var animatable = this._animatables[index];
  52680. animatable.reset();
  52681. }
  52682. return this;
  52683. };
  52684. /**
  52685. * Restart animations from key 0
  52686. * @returns the animation group
  52687. */
  52688. AnimationGroup.prototype.restart = function () {
  52689. if (!this._isStarted) {
  52690. return this;
  52691. }
  52692. for (var index = 0; index < this._animatables.length; index++) {
  52693. var animatable = this._animatables[index];
  52694. animatable.restart();
  52695. }
  52696. return this;
  52697. };
  52698. /**
  52699. * Stop all animations
  52700. * @returns the animation group
  52701. */
  52702. AnimationGroup.prototype.stop = function () {
  52703. if (!this._isStarted) {
  52704. return this;
  52705. }
  52706. var list = this._animatables.slice();
  52707. for (var index = 0; index < list.length; index++) {
  52708. list[index].stop();
  52709. }
  52710. this._isStarted = false;
  52711. return this;
  52712. };
  52713. /**
  52714. * Set animation weight for all animatables
  52715. * @param weight defines the weight to use
  52716. * @return the animationGroup
  52717. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52718. */
  52719. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52720. for (var index = 0; index < this._animatables.length; index++) {
  52721. var animatable = this._animatables[index];
  52722. animatable.weight = weight;
  52723. }
  52724. return this;
  52725. };
  52726. /**
  52727. * Synchronize and normalize all animatables with a source animatable
  52728. * @param root defines the root animatable to synchronize with
  52729. * @return the animationGroup
  52730. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52731. */
  52732. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52733. for (var index = 0; index < this._animatables.length; index++) {
  52734. var animatable = this._animatables[index];
  52735. animatable.syncWith(root);
  52736. }
  52737. return this;
  52738. };
  52739. /**
  52740. * Goes to a specific frame in this animation group
  52741. * @param frame the frame number to go to
  52742. * @return the animationGroup
  52743. */
  52744. AnimationGroup.prototype.goToFrame = function (frame) {
  52745. if (!this._isStarted) {
  52746. return this;
  52747. }
  52748. for (var index = 0; index < this._animatables.length; index++) {
  52749. var animatable = this._animatables[index];
  52750. animatable.goToFrame(frame);
  52751. }
  52752. return this;
  52753. };
  52754. /**
  52755. * Dispose all associated resources
  52756. */
  52757. AnimationGroup.prototype.dispose = function () {
  52758. this._targetedAnimations = [];
  52759. this._animatables = [];
  52760. var index = this._scene.animationGroups.indexOf(this);
  52761. if (index > -1) {
  52762. this._scene.animationGroups.splice(index, 1);
  52763. }
  52764. };
  52765. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52766. // animatable should be taken out of the array
  52767. var idx = this._animatables.indexOf(animatable);
  52768. if (idx > -1) {
  52769. this._animatables.splice(idx, 1);
  52770. }
  52771. // all animatables were removed? animation group ended!
  52772. if (this._animatables.length === 0) {
  52773. this._isStarted = false;
  52774. this.onAnimationGroupEndObservable.notifyObservers(this);
  52775. }
  52776. };
  52777. // Statics
  52778. /**
  52779. * Returns a new AnimationGroup object parsed from the source provided.
  52780. * @param parsedAnimationGroup defines the source
  52781. * @param scene defines the scene that will receive the animationGroup
  52782. * @returns a new AnimationGroup
  52783. */
  52784. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  52785. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  52786. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  52787. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  52788. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  52789. var id = targetedAnimation.targetId;
  52790. var targetNode = scene.getNodeByID(id);
  52791. if (targetNode != null)
  52792. animationGroup.addTargetedAnimation(animation, targetNode);
  52793. }
  52794. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  52795. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  52796. return animationGroup;
  52797. };
  52798. /**
  52799. * Returns the string "AnimationGroup"
  52800. * @returns "AnimationGroup"
  52801. */
  52802. AnimationGroup.prototype.getClassName = function () {
  52803. return "AnimationGroup";
  52804. };
  52805. /**
  52806. * Creates a detailled string about the object
  52807. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  52808. * @returns a string representing the object
  52809. */
  52810. AnimationGroup.prototype.toString = function (fullDetails) {
  52811. var ret = "Name: " + this.name;
  52812. ret += ", type: " + this.getClassName();
  52813. if (fullDetails) {
  52814. ret += ", from: " + this._from;
  52815. ret += ", to: " + this._to;
  52816. ret += ", isStarted: " + this._isStarted;
  52817. ret += ", speedRatio: " + this._speedRatio;
  52818. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  52819. ret += ", animatables length: " + this._animatables;
  52820. }
  52821. return ret;
  52822. };
  52823. return AnimationGroup;
  52824. }());
  52825. BABYLON.AnimationGroup = AnimationGroup;
  52826. })(BABYLON || (BABYLON = {}));
  52827. //# sourceMappingURL=babylon.animationGroup.js.map
  52828. var BABYLON;
  52829. (function (BABYLON) {
  52830. // Static values to help the garbage collector
  52831. // Quaternion
  52832. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  52833. // Vector3
  52834. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  52835. // Vector2
  52836. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  52837. // Size
  52838. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  52839. // Color3
  52840. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  52841. /**
  52842. * Defines a runtime animation
  52843. */
  52844. var RuntimeAnimation = /** @class */ (function () {
  52845. /**
  52846. * Create a new RuntimeAnimation object
  52847. * @param target defines the target of the animation
  52848. * @param animation defines the source animation object
  52849. * @param scene defines the hosting scene
  52850. * @param host defines the initiating Animatable
  52851. */
  52852. function RuntimeAnimation(target, animation, scene, host) {
  52853. var _this = this;
  52854. this._events = new Array();
  52855. /**
  52856. * The current frame of the runtime animation
  52857. */
  52858. this._currentFrame = 0;
  52859. /**
  52860. * The original value of the runtime animation
  52861. */
  52862. this._originalValue = new Array();
  52863. /**
  52864. * The offsets cache of the runtime animation
  52865. */
  52866. this._offsetsCache = {};
  52867. /**
  52868. * The high limits cache of the runtime animation
  52869. */
  52870. this._highLimitsCache = {};
  52871. /**
  52872. * Specifies if the runtime animation has been stopped
  52873. */
  52874. this._stopped = false;
  52875. /**
  52876. * The blending factor of the runtime animation
  52877. */
  52878. this._blendingFactor = 0;
  52879. /**
  52880. * The target path of the runtime animation
  52881. */
  52882. this._targetPath = "";
  52883. /**
  52884. * The weight of the runtime animation
  52885. */
  52886. this._weight = 1.0;
  52887. /**
  52888. * The ratio offset of the runtime animation
  52889. */
  52890. this._ratioOffset = 0;
  52891. /**
  52892. * The previous delay of the runtime animation
  52893. */
  52894. this._previousDelay = 0;
  52895. /**
  52896. * The previous ratio of the runtime animation
  52897. */
  52898. this._previousRatio = 0;
  52899. this._animation = animation;
  52900. this._target = target;
  52901. this._scene = scene;
  52902. this._host = host;
  52903. animation._runtimeAnimations.push(this);
  52904. // Cloning events locally
  52905. var events = animation.getEvents();
  52906. if (events && events.length > 0) {
  52907. events.forEach(function (e) {
  52908. _this._events.push(e._clone());
  52909. });
  52910. }
  52911. }
  52912. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52913. /**
  52914. * Gets the current frame of the runtime animation
  52915. */
  52916. get: function () {
  52917. return this._currentFrame;
  52918. },
  52919. enumerable: true,
  52920. configurable: true
  52921. });
  52922. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52923. /**
  52924. * Gets the weight of the runtime animation
  52925. */
  52926. get: function () {
  52927. return this._weight;
  52928. },
  52929. enumerable: true,
  52930. configurable: true
  52931. });
  52932. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52933. /**
  52934. * Gets the current value of the runtime animation
  52935. */
  52936. get: function () {
  52937. return this._currentValue;
  52938. },
  52939. enumerable: true,
  52940. configurable: true
  52941. });
  52942. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52943. /**
  52944. * Gets the target path of the runtime animation
  52945. */
  52946. get: function () {
  52947. return this._targetPath;
  52948. },
  52949. enumerable: true,
  52950. configurable: true
  52951. });
  52952. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52953. /**
  52954. * Gets the actual target of the runtime animation
  52955. */
  52956. get: function () {
  52957. return this._activeTarget;
  52958. },
  52959. enumerable: true,
  52960. configurable: true
  52961. });
  52962. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52963. /**
  52964. * Gets the animation from the runtime animation
  52965. */
  52966. get: function () {
  52967. return this._animation;
  52968. },
  52969. enumerable: true,
  52970. configurable: true
  52971. });
  52972. /**
  52973. * Resets the runtime animation to the beginning
  52974. * @param restoreOriginal defines whether to restore the target property to the original value
  52975. */
  52976. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52977. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52978. if (restoreOriginal) {
  52979. if (this._target instanceof Array) {
  52980. var index = 0;
  52981. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52982. var target = _a[_i];
  52983. if (this._originalValue[index] !== undefined) {
  52984. this._setValue(target, this._originalValue[index], -1);
  52985. }
  52986. index++;
  52987. }
  52988. }
  52989. else {
  52990. if (this._originalValue[0] !== undefined) {
  52991. this._setValue(this._target, this._originalValue[0], -1);
  52992. }
  52993. }
  52994. }
  52995. this._offsetsCache = {};
  52996. this._highLimitsCache = {};
  52997. this._currentFrame = 0;
  52998. this._blendingFactor = 0;
  52999. this._originalValue = new Array();
  53000. // Events
  53001. for (var index = 0; index < this._events.length; index++) {
  53002. this._events[index].isDone = false;
  53003. }
  53004. };
  53005. /**
  53006. * Specifies if the runtime animation is stopped
  53007. * @returns Boolean specifying if the runtime animation is stopped
  53008. */
  53009. RuntimeAnimation.prototype.isStopped = function () {
  53010. return this._stopped;
  53011. };
  53012. /**
  53013. * Disposes of the runtime animation
  53014. */
  53015. RuntimeAnimation.prototype.dispose = function () {
  53016. var index = this._animation.runtimeAnimations.indexOf(this);
  53017. if (index > -1) {
  53018. this._animation.runtimeAnimations.splice(index, 1);
  53019. }
  53020. };
  53021. /**
  53022. * Interpolates the animation from the current frame
  53023. * @param currentFrame The frame to interpolate the animation to
  53024. * @param repeatCount The number of times that the animation should loop
  53025. * @param loopMode The type of looping mode to use
  53026. * @param offsetValue Animation offset value
  53027. * @param highLimitValue The high limit value
  53028. * @returns The interpolated value
  53029. */
  53030. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  53031. this._currentFrame = currentFrame;
  53032. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  53033. this._workValue = BABYLON.Matrix.Zero();
  53034. }
  53035. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  53036. };
  53037. /**
  53038. * Apply the interpolated value to the target
  53039. * @param currentValue defines the value computed by the animation
  53040. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  53041. */
  53042. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  53043. if (weight === void 0) { weight = 1.0; }
  53044. if (this._target instanceof Array) {
  53045. var index = 0;
  53046. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53047. var target = _a[_i];
  53048. this._setValue(target, currentValue, weight, index);
  53049. index++;
  53050. }
  53051. }
  53052. else {
  53053. this._setValue(this._target, currentValue, weight);
  53054. }
  53055. };
  53056. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  53057. if (targetIndex === void 0) { targetIndex = 0; }
  53058. // Set value
  53059. var path;
  53060. var destination;
  53061. var targetPropertyPath = this._animation.targetPropertyPath;
  53062. if (targetPropertyPath.length > 1) {
  53063. var property = target[targetPropertyPath[0]];
  53064. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  53065. property = property[targetPropertyPath[index]];
  53066. }
  53067. path = targetPropertyPath[targetPropertyPath.length - 1];
  53068. destination = property;
  53069. }
  53070. else {
  53071. path = targetPropertyPath[0];
  53072. destination = target;
  53073. }
  53074. this._targetPath = path;
  53075. this._activeTarget = destination;
  53076. this._weight = weight;
  53077. if (this._originalValue[targetIndex] === undefined) {
  53078. var originalValue = void 0;
  53079. if (destination.getRestPose && path === "_matrix") { // For bones
  53080. originalValue = destination.getRestPose();
  53081. }
  53082. else {
  53083. originalValue = destination[path];
  53084. }
  53085. if (originalValue && originalValue.clone) {
  53086. this._originalValue[targetIndex] = originalValue.clone();
  53087. }
  53088. else {
  53089. this._originalValue[targetIndex] = originalValue;
  53090. }
  53091. }
  53092. // Blending
  53093. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  53094. if (enableBlending && this._blendingFactor <= 1.0) {
  53095. if (!this._originalBlendValue) {
  53096. var originalValue = destination[path];
  53097. if (originalValue.clone) {
  53098. this._originalBlendValue = originalValue.clone();
  53099. }
  53100. else {
  53101. this._originalBlendValue = originalValue;
  53102. }
  53103. }
  53104. if (this._originalBlendValue.m) { // Matrix
  53105. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  53106. if (this._currentValue) {
  53107. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53108. }
  53109. else {
  53110. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53111. }
  53112. }
  53113. else {
  53114. if (this._currentValue) {
  53115. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53116. }
  53117. else {
  53118. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53119. }
  53120. }
  53121. }
  53122. else {
  53123. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53124. }
  53125. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  53126. this._blendingFactor += blendingSpeed;
  53127. }
  53128. else {
  53129. this._currentValue = currentValue;
  53130. }
  53131. if (weight !== -1.0) {
  53132. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  53133. }
  53134. else {
  53135. destination[path] = this._currentValue;
  53136. }
  53137. if (target.markAsDirty) {
  53138. target.markAsDirty(this._animation.targetProperty);
  53139. }
  53140. };
  53141. /**
  53142. * Gets the loop pmode of the runtime animation
  53143. * @returns Loop Mode
  53144. */
  53145. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  53146. if (this._target && this._target.animationPropertiesOverride) {
  53147. return this._target.animationPropertiesOverride.loopMode;
  53148. }
  53149. return this._animation.loopMode;
  53150. };
  53151. /**
  53152. * Move the current animation to a given frame
  53153. * @param frame defines the frame to move to
  53154. */
  53155. RuntimeAnimation.prototype.goToFrame = function (frame) {
  53156. var keys = this._animation.getKeys();
  53157. if (frame < keys[0].frame) {
  53158. frame = keys[0].frame;
  53159. }
  53160. else if (frame > keys[keys.length - 1].frame) {
  53161. frame = keys[keys.length - 1].frame;
  53162. }
  53163. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  53164. this.setValue(currentValue, -1);
  53165. };
  53166. /**
  53167. * @hidden Internal use only
  53168. */
  53169. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  53170. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  53171. this._ratioOffset = this._previousRatio - newRatio;
  53172. };
  53173. /**
  53174. * Execute the current animation
  53175. * @param delay defines the delay to add to the current frame
  53176. * @param from defines the lower bound of the animation range
  53177. * @param to defines the upper bound of the animation range
  53178. * @param loop defines if the current animation must loop
  53179. * @param speedRatio defines the current speed ratio
  53180. * @param weight defines the weight of the animation (default is -1 so no weight)
  53181. * @returns a boolean indicating if the animation is running
  53182. */
  53183. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  53184. if (weight === void 0) { weight = -1.0; }
  53185. var targetPropertyPath = this._animation.targetPropertyPath;
  53186. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  53187. this._stopped = true;
  53188. return false;
  53189. }
  53190. var returnValue = true;
  53191. var keys = this._animation.getKeys();
  53192. // Adding a start key at frame 0 if missing
  53193. if (keys[0].frame !== 0) {
  53194. var newKey = { frame: 0, value: keys[0].value };
  53195. keys.splice(0, 0, newKey);
  53196. }
  53197. // Adding a duplicate key when there is only one key at frame zero
  53198. else if (keys.length === 1) {
  53199. var newKey = { frame: 0.001, value: keys[0].value };
  53200. keys.push(newKey);
  53201. }
  53202. // Check limits
  53203. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53204. from = keys[0].frame;
  53205. }
  53206. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53207. to = keys[keys.length - 1].frame;
  53208. }
  53209. //to and from cannot be the same key
  53210. if (from === to) {
  53211. if (from > keys[0].frame) {
  53212. from--;
  53213. }
  53214. else if (to < keys[keys.length - 1].frame) {
  53215. to++;
  53216. }
  53217. }
  53218. // Compute ratio
  53219. var range = to - from;
  53220. var offsetValue;
  53221. // ratio represents the frame delta between from and to
  53222. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53223. var highLimitValue = 0;
  53224. this._previousDelay = delay;
  53225. this._previousRatio = ratio;
  53226. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53227. returnValue = false;
  53228. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53229. }
  53230. else {
  53231. // Get max value if required
  53232. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53233. var keyOffset = to.toString() + from.toString();
  53234. if (!this._offsetsCache[keyOffset]) {
  53235. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53236. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53237. switch (this._animation.dataType) {
  53238. // Float
  53239. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53240. this._offsetsCache[keyOffset] = toValue - fromValue;
  53241. break;
  53242. // Quaternion
  53243. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53244. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53245. break;
  53246. // Vector3
  53247. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53248. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53249. // Vector2
  53250. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53251. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53252. // Size
  53253. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53254. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53255. // Color3
  53256. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53257. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53258. default:
  53259. break;
  53260. }
  53261. this._highLimitsCache[keyOffset] = toValue;
  53262. }
  53263. highLimitValue = this._highLimitsCache[keyOffset];
  53264. offsetValue = this._offsetsCache[keyOffset];
  53265. }
  53266. }
  53267. if (offsetValue === undefined) {
  53268. switch (this._animation.dataType) {
  53269. // Float
  53270. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53271. offsetValue = 0;
  53272. break;
  53273. // Quaternion
  53274. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53275. offsetValue = _staticOffsetValueQuaternion;
  53276. break;
  53277. // Vector3
  53278. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53279. offsetValue = _staticOffsetValueVector3;
  53280. break;
  53281. // Vector2
  53282. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53283. offsetValue = _staticOffsetValueVector2;
  53284. break;
  53285. // Size
  53286. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53287. offsetValue = _staticOffsetValueSize;
  53288. break;
  53289. // Color3
  53290. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53291. offsetValue = _staticOffsetValueColor3;
  53292. }
  53293. }
  53294. // Compute value
  53295. var repeatCount = (ratio / range) >> 0;
  53296. var currentFrame = returnValue ? from + ratio % range : to;
  53297. // Need to normalize?
  53298. if (this._host && this._host.syncRoot) {
  53299. var syncRoot = this._host.syncRoot;
  53300. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53301. currentFrame = from + (to - from) * hostNormalizedFrame;
  53302. }
  53303. // Reset events if looping
  53304. var events = this._events;
  53305. if (range > 0 && this.currentFrame > currentFrame ||
  53306. range < 0 && this.currentFrame < currentFrame) {
  53307. // Need to reset animation events
  53308. for (var index = 0; index < events.length; index++) {
  53309. if (!events[index].onlyOnce) {
  53310. // reset event, the animation is looping
  53311. events[index].isDone = false;
  53312. }
  53313. }
  53314. }
  53315. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  53316. // Set value
  53317. this.setValue(currentValue, weight);
  53318. // Check events
  53319. for (var index = 0; index < events.length; index++) {
  53320. // Make sure current frame has passed event frame and that event frame is within the current range
  53321. // Also, handle both forward and reverse animations
  53322. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  53323. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  53324. var event = events[index];
  53325. if (!event.isDone) {
  53326. // If event should be done only once, remove it.
  53327. if (event.onlyOnce) {
  53328. events.splice(index, 1);
  53329. index--;
  53330. }
  53331. event.isDone = true;
  53332. event.action(currentFrame);
  53333. } // Don't do anything if the event has already be done.
  53334. }
  53335. }
  53336. if (!returnValue) {
  53337. this._stopped = true;
  53338. }
  53339. return returnValue;
  53340. };
  53341. return RuntimeAnimation;
  53342. }());
  53343. BABYLON.RuntimeAnimation = RuntimeAnimation;
  53344. })(BABYLON || (BABYLON = {}));
  53345. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  53346. var BABYLON;
  53347. (function (BABYLON) {
  53348. /**
  53349. * Class used to store an actual running animation
  53350. */
  53351. var Animatable = /** @class */ (function () {
  53352. /**
  53353. * Creates a new Animatable
  53354. * @param scene defines the hosting scene
  53355. * @param target defines the target object
  53356. * @param fromFrame defines the starting frame number (default is 0)
  53357. * @param toFrame defines the ending frame number (default is 100)
  53358. * @param loopAnimation defines if the animation must loop (default is false)
  53359. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  53360. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  53361. * @param animations defines a group of animation to add to the new Animatable
  53362. */
  53363. function Animatable(scene,
  53364. /** defines the target object */
  53365. target,
  53366. /** defines the starting frame number (default is 0) */
  53367. fromFrame,
  53368. /** defines the ending frame number (default is 100) */
  53369. toFrame,
  53370. /** defines if the animation must loop (default is false) */
  53371. loopAnimation, speedRatio,
  53372. /** defines a callback to call when animation ends if it is not looping */
  53373. onAnimationEnd, animations) {
  53374. if (fromFrame === void 0) { fromFrame = 0; }
  53375. if (toFrame === void 0) { toFrame = 100; }
  53376. if (loopAnimation === void 0) { loopAnimation = false; }
  53377. if (speedRatio === void 0) { speedRatio = 1.0; }
  53378. this.target = target;
  53379. this.fromFrame = fromFrame;
  53380. this.toFrame = toFrame;
  53381. this.loopAnimation = loopAnimation;
  53382. this.onAnimationEnd = onAnimationEnd;
  53383. this._localDelayOffset = null;
  53384. this._pausedDelay = null;
  53385. this._runtimeAnimations = new Array();
  53386. this._paused = false;
  53387. this._speedRatio = 1;
  53388. this._weight = -1.0;
  53389. /**
  53390. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  53391. * This will only apply for non looping animation (default is true)
  53392. */
  53393. this.disposeOnEnd = true;
  53394. /**
  53395. * Gets a boolean indicating if the animation has started
  53396. */
  53397. this.animationStarted = false;
  53398. /**
  53399. * Observer raised when the animation ends
  53400. */
  53401. this.onAnimationEndObservable = new BABYLON.Observable();
  53402. this._scene = scene;
  53403. if (animations) {
  53404. this.appendAnimations(target, animations);
  53405. }
  53406. this._speedRatio = speedRatio;
  53407. scene._activeAnimatables.push(this);
  53408. }
  53409. Object.defineProperty(Animatable.prototype, "syncRoot", {
  53410. /**
  53411. * Gets the root Animatable used to synchronize and normalize animations
  53412. */
  53413. get: function () {
  53414. return this._syncRoot;
  53415. },
  53416. enumerable: true,
  53417. configurable: true
  53418. });
  53419. Object.defineProperty(Animatable.prototype, "masterFrame", {
  53420. /**
  53421. * Gets the current frame of the first RuntimeAnimation
  53422. * Used to synchronize Animatables
  53423. */
  53424. get: function () {
  53425. if (this._runtimeAnimations.length === 0) {
  53426. return 0;
  53427. }
  53428. return this._runtimeAnimations[0].currentFrame;
  53429. },
  53430. enumerable: true,
  53431. configurable: true
  53432. });
  53433. Object.defineProperty(Animatable.prototype, "weight", {
  53434. /**
  53435. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  53436. */
  53437. get: function () {
  53438. return this._weight;
  53439. },
  53440. set: function (value) {
  53441. if (value === -1) { // -1 is ok and means no weight
  53442. this._weight = -1;
  53443. return;
  53444. }
  53445. // Else weight must be in [0, 1] range
  53446. this._weight = Math.min(Math.max(value, 0), 1.0);
  53447. },
  53448. enumerable: true,
  53449. configurable: true
  53450. });
  53451. Object.defineProperty(Animatable.prototype, "speedRatio", {
  53452. /**
  53453. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  53454. */
  53455. get: function () {
  53456. return this._speedRatio;
  53457. },
  53458. set: function (value) {
  53459. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  53460. var animation = this._runtimeAnimations[index];
  53461. animation._prepareForSpeedRatioChange(value);
  53462. }
  53463. this._speedRatio = value;
  53464. },
  53465. enumerable: true,
  53466. configurable: true
  53467. });
  53468. // Methods
  53469. /**
  53470. * Synchronize and normalize current Animatable with a source Animatable
  53471. * This is useful when using animation weights and when animations are not of the same length
  53472. * @param root defines the root Animatable to synchronize with
  53473. * @returns the current Animatable
  53474. */
  53475. Animatable.prototype.syncWith = function (root) {
  53476. this._syncRoot = root;
  53477. if (root) {
  53478. // Make sure this animatable will animate after the root
  53479. var index = this._scene._activeAnimatables.indexOf(this);
  53480. if (index > -1) {
  53481. this._scene._activeAnimatables.splice(index, 1);
  53482. this._scene._activeAnimatables.push(this);
  53483. }
  53484. }
  53485. return this;
  53486. };
  53487. /**
  53488. * Gets the list of runtime animations
  53489. * @returns an array of RuntimeAnimation
  53490. */
  53491. Animatable.prototype.getAnimations = function () {
  53492. return this._runtimeAnimations;
  53493. };
  53494. /**
  53495. * Adds more animations to the current animatable
  53496. * @param target defines the target of the animations
  53497. * @param animations defines the new animations to add
  53498. */
  53499. Animatable.prototype.appendAnimations = function (target, animations) {
  53500. for (var index = 0; index < animations.length; index++) {
  53501. var animation = animations[index];
  53502. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  53503. }
  53504. };
  53505. /**
  53506. * Gets the source animation for a specific property
  53507. * @param property defines the propertyu to look for
  53508. * @returns null or the source animation for the given property
  53509. */
  53510. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  53511. var runtimeAnimations = this._runtimeAnimations;
  53512. for (var index = 0; index < runtimeAnimations.length; index++) {
  53513. if (runtimeAnimations[index].animation.targetProperty === property) {
  53514. return runtimeAnimations[index].animation;
  53515. }
  53516. }
  53517. return null;
  53518. };
  53519. /**
  53520. * Gets the runtime animation for a specific property
  53521. * @param property defines the propertyu to look for
  53522. * @returns null or the runtime animation for the given property
  53523. */
  53524. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  53525. var runtimeAnimations = this._runtimeAnimations;
  53526. for (var index = 0; index < runtimeAnimations.length; index++) {
  53527. if (runtimeAnimations[index].animation.targetProperty === property) {
  53528. return runtimeAnimations[index];
  53529. }
  53530. }
  53531. return null;
  53532. };
  53533. /**
  53534. * Resets the animatable to its original state
  53535. */
  53536. Animatable.prototype.reset = function () {
  53537. var runtimeAnimations = this._runtimeAnimations;
  53538. for (var index = 0; index < runtimeAnimations.length; index++) {
  53539. runtimeAnimations[index].reset(true);
  53540. }
  53541. this._localDelayOffset = null;
  53542. this._pausedDelay = null;
  53543. };
  53544. /**
  53545. * Allows the animatable to blend with current running animations
  53546. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53547. * @param blendingSpeed defines the blending speed to use
  53548. */
  53549. Animatable.prototype.enableBlending = function (blendingSpeed) {
  53550. var runtimeAnimations = this._runtimeAnimations;
  53551. for (var index = 0; index < runtimeAnimations.length; index++) {
  53552. runtimeAnimations[index].animation.enableBlending = true;
  53553. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  53554. }
  53555. };
  53556. /**
  53557. * Disable animation blending
  53558. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53559. */
  53560. Animatable.prototype.disableBlending = function () {
  53561. var runtimeAnimations = this._runtimeAnimations;
  53562. for (var index = 0; index < runtimeAnimations.length; index++) {
  53563. runtimeAnimations[index].animation.enableBlending = false;
  53564. }
  53565. };
  53566. /**
  53567. * Jump directly to a given frame
  53568. * @param frame defines the frame to jump to
  53569. */
  53570. Animatable.prototype.goToFrame = function (frame) {
  53571. var runtimeAnimations = this._runtimeAnimations;
  53572. if (runtimeAnimations[0]) {
  53573. var fps = runtimeAnimations[0].animation.framePerSecond;
  53574. var currentFrame = runtimeAnimations[0].currentFrame;
  53575. var adjustTime = frame - currentFrame;
  53576. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  53577. if (this._localDelayOffset === null) {
  53578. this._localDelayOffset = 0;
  53579. }
  53580. this._localDelayOffset -= delay;
  53581. }
  53582. for (var index = 0; index < runtimeAnimations.length; index++) {
  53583. runtimeAnimations[index].goToFrame(frame);
  53584. }
  53585. };
  53586. /**
  53587. * Pause the animation
  53588. */
  53589. Animatable.prototype.pause = function () {
  53590. if (this._paused) {
  53591. return;
  53592. }
  53593. this._paused = true;
  53594. };
  53595. /**
  53596. * Restart the animation
  53597. */
  53598. Animatable.prototype.restart = function () {
  53599. this._paused = false;
  53600. };
  53601. Animatable.prototype._raiseOnAnimationEnd = function () {
  53602. if (this.onAnimationEnd) {
  53603. this.onAnimationEnd();
  53604. }
  53605. this.onAnimationEndObservable.notifyObservers(this);
  53606. };
  53607. /**
  53608. * Stop and delete the current animation
  53609. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  53610. * @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)
  53611. */
  53612. Animatable.prototype.stop = function (animationName, targetMask) {
  53613. if (animationName || targetMask) {
  53614. var idx = this._scene._activeAnimatables.indexOf(this);
  53615. if (idx > -1) {
  53616. var runtimeAnimations = this._runtimeAnimations;
  53617. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  53618. var runtimeAnimation = runtimeAnimations[index];
  53619. if (animationName && runtimeAnimation.animation.name != animationName) {
  53620. continue;
  53621. }
  53622. if (targetMask && !targetMask(runtimeAnimation.target)) {
  53623. continue;
  53624. }
  53625. runtimeAnimation.dispose();
  53626. runtimeAnimations.splice(index, 1);
  53627. }
  53628. if (runtimeAnimations.length == 0) {
  53629. this._scene._activeAnimatables.splice(idx, 1);
  53630. this._raiseOnAnimationEnd();
  53631. }
  53632. }
  53633. }
  53634. else {
  53635. var index = this._scene._activeAnimatables.indexOf(this);
  53636. if (index > -1) {
  53637. this._scene._activeAnimatables.splice(index, 1);
  53638. var runtimeAnimations = this._runtimeAnimations;
  53639. for (var index = 0; index < runtimeAnimations.length; index++) {
  53640. runtimeAnimations[index].dispose();
  53641. }
  53642. this._raiseOnAnimationEnd();
  53643. }
  53644. }
  53645. };
  53646. /**
  53647. * Wait asynchronously for the animation to end
  53648. * @returns a promise which will be fullfilled when the animation ends
  53649. */
  53650. Animatable.prototype.waitAsync = function () {
  53651. var _this = this;
  53652. return new Promise(function (resolve, reject) {
  53653. _this.onAnimationEndObservable.add(function () {
  53654. resolve(_this);
  53655. }, undefined, undefined, _this, true);
  53656. });
  53657. };
  53658. /** @hidden */
  53659. Animatable.prototype._animate = function (delay) {
  53660. if (this._paused) {
  53661. this.animationStarted = false;
  53662. if (this._pausedDelay === null) {
  53663. this._pausedDelay = delay;
  53664. }
  53665. return true;
  53666. }
  53667. if (this._localDelayOffset === null) {
  53668. this._localDelayOffset = delay;
  53669. this._pausedDelay = null;
  53670. }
  53671. else if (this._pausedDelay !== null) {
  53672. this._localDelayOffset += delay - this._pausedDelay;
  53673. this._pausedDelay = null;
  53674. }
  53675. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  53676. return true;
  53677. }
  53678. // Animating
  53679. var running = false;
  53680. var runtimeAnimations = this._runtimeAnimations;
  53681. var index;
  53682. for (index = 0; index < runtimeAnimations.length; index++) {
  53683. var animation = runtimeAnimations[index];
  53684. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  53685. running = running || isRunning;
  53686. }
  53687. this.animationStarted = running;
  53688. if (!running) {
  53689. if (this.disposeOnEnd) {
  53690. // Remove from active animatables
  53691. index = this._scene._activeAnimatables.indexOf(this);
  53692. this._scene._activeAnimatables.splice(index, 1);
  53693. // Dispose all runtime animations
  53694. for (index = 0; index < runtimeAnimations.length; index++) {
  53695. runtimeAnimations[index].dispose();
  53696. }
  53697. }
  53698. this._raiseOnAnimationEnd();
  53699. if (this.disposeOnEnd) {
  53700. this.onAnimationEnd = null;
  53701. this.onAnimationEndObservable.clear();
  53702. }
  53703. }
  53704. return running;
  53705. };
  53706. return Animatable;
  53707. }());
  53708. BABYLON.Animatable = Animatable;
  53709. })(BABYLON || (BABYLON = {}));
  53710. //# sourceMappingURL=babylon.animatable.js.map
  53711. var BABYLON;
  53712. (function (BABYLON) {
  53713. /**
  53714. * Base class used for every default easing function.
  53715. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53716. */
  53717. var EasingFunction = /** @class */ (function () {
  53718. function EasingFunction() {
  53719. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  53720. }
  53721. /**
  53722. * Sets the easing mode of the current function.
  53723. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  53724. */
  53725. EasingFunction.prototype.setEasingMode = function (easingMode) {
  53726. var n = Math.min(Math.max(easingMode, 0), 2);
  53727. this._easingMode = n;
  53728. };
  53729. /**
  53730. * Gets the current easing mode.
  53731. * @returns the easing mode
  53732. */
  53733. EasingFunction.prototype.getEasingMode = function () {
  53734. return this._easingMode;
  53735. };
  53736. /**
  53737. * @hidden
  53738. */
  53739. EasingFunction.prototype.easeInCore = function (gradient) {
  53740. throw new Error('You must implement this method');
  53741. };
  53742. /**
  53743. * Given an input gradient between 0 and 1, this returns the corrseponding value
  53744. * of the easing function.
  53745. * @param gradient Defines the value between 0 and 1 we want the easing value for
  53746. * @returns the corresponding value on the curve defined by the easing function
  53747. */
  53748. EasingFunction.prototype.ease = function (gradient) {
  53749. switch (this._easingMode) {
  53750. case EasingFunction.EASINGMODE_EASEIN:
  53751. return this.easeInCore(gradient);
  53752. case EasingFunction.EASINGMODE_EASEOUT:
  53753. return (1 - this.easeInCore(1 - gradient));
  53754. }
  53755. if (gradient >= 0.5) {
  53756. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  53757. }
  53758. return (this.easeInCore(gradient * 2) * 0.5);
  53759. };
  53760. /**
  53761. * Interpolation follows the mathematical formula associated with the easing function.
  53762. */
  53763. EasingFunction.EASINGMODE_EASEIN = 0;
  53764. /**
  53765. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  53766. */
  53767. EasingFunction.EASINGMODE_EASEOUT = 1;
  53768. /**
  53769. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  53770. */
  53771. EasingFunction.EASINGMODE_EASEINOUT = 2;
  53772. return EasingFunction;
  53773. }());
  53774. BABYLON.EasingFunction = EasingFunction;
  53775. /**
  53776. * Easing function with a circle shape (see link below).
  53777. * @see https://easings.net/#easeInCirc
  53778. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53779. */
  53780. var CircleEase = /** @class */ (function (_super) {
  53781. __extends(CircleEase, _super);
  53782. function CircleEase() {
  53783. return _super !== null && _super.apply(this, arguments) || this;
  53784. }
  53785. /** @hidden */
  53786. CircleEase.prototype.easeInCore = function (gradient) {
  53787. gradient = Math.max(0, Math.min(1, gradient));
  53788. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  53789. };
  53790. return CircleEase;
  53791. }(EasingFunction));
  53792. BABYLON.CircleEase = CircleEase;
  53793. /**
  53794. * Easing function with a ease back shape (see link below).
  53795. * @see https://easings.net/#easeInBack
  53796. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53797. */
  53798. var BackEase = /** @class */ (function (_super) {
  53799. __extends(BackEase, _super);
  53800. /**
  53801. * Instantiates a back ease easing
  53802. * @see https://easings.net/#easeInBack
  53803. * @param amplitude Defines the amplitude of the function
  53804. */
  53805. function BackEase(
  53806. /** Defines the amplitude of the function */
  53807. amplitude) {
  53808. if (amplitude === void 0) { amplitude = 1; }
  53809. var _this = _super.call(this) || this;
  53810. _this.amplitude = amplitude;
  53811. return _this;
  53812. }
  53813. /** @hidden */
  53814. BackEase.prototype.easeInCore = function (gradient) {
  53815. var num = Math.max(0, this.amplitude);
  53816. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  53817. };
  53818. return BackEase;
  53819. }(EasingFunction));
  53820. BABYLON.BackEase = BackEase;
  53821. /**
  53822. * Easing function with a bouncing shape (see link below).
  53823. * @see https://easings.net/#easeInBounce
  53824. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53825. */
  53826. var BounceEase = /** @class */ (function (_super) {
  53827. __extends(BounceEase, _super);
  53828. /**
  53829. * Instantiates a bounce easing
  53830. * @see https://easings.net/#easeInBounce
  53831. * @param bounces Defines the number of bounces
  53832. * @param bounciness Defines the amplitude of the bounce
  53833. */
  53834. function BounceEase(
  53835. /** Defines the number of bounces */
  53836. bounces,
  53837. /** Defines the amplitude of the bounce */
  53838. bounciness) {
  53839. if (bounces === void 0) { bounces = 3; }
  53840. if (bounciness === void 0) { bounciness = 2; }
  53841. var _this = _super.call(this) || this;
  53842. _this.bounces = bounces;
  53843. _this.bounciness = bounciness;
  53844. return _this;
  53845. }
  53846. /** @hidden */
  53847. BounceEase.prototype.easeInCore = function (gradient) {
  53848. var y = Math.max(0.0, this.bounces);
  53849. var bounciness = this.bounciness;
  53850. if (bounciness <= 1.0) {
  53851. bounciness = 1.001;
  53852. }
  53853. var num9 = Math.pow(bounciness, y);
  53854. var num5 = 1.0 - bounciness;
  53855. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  53856. var num15 = gradient * num4;
  53857. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  53858. var num3 = Math.floor(num65);
  53859. var num13 = num3 + 1.0;
  53860. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  53861. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  53862. var num7 = (num8 + num12) * 0.5;
  53863. var num6 = gradient - num7;
  53864. var num2 = num7 - num8;
  53865. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  53866. };
  53867. return BounceEase;
  53868. }(EasingFunction));
  53869. BABYLON.BounceEase = BounceEase;
  53870. /**
  53871. * Easing function with a power of 3 shape (see link below).
  53872. * @see https://easings.net/#easeInCubic
  53873. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53874. */
  53875. var CubicEase = /** @class */ (function (_super) {
  53876. __extends(CubicEase, _super);
  53877. function CubicEase() {
  53878. return _super !== null && _super.apply(this, arguments) || this;
  53879. }
  53880. /** @hidden */
  53881. CubicEase.prototype.easeInCore = function (gradient) {
  53882. return (gradient * gradient * gradient);
  53883. };
  53884. return CubicEase;
  53885. }(EasingFunction));
  53886. BABYLON.CubicEase = CubicEase;
  53887. /**
  53888. * Easing function with an elastic shape (see link below).
  53889. * @see https://easings.net/#easeInElastic
  53890. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53891. */
  53892. var ElasticEase = /** @class */ (function (_super) {
  53893. __extends(ElasticEase, _super);
  53894. /**
  53895. * Instantiates an elastic easing function
  53896. * @see https://easings.net/#easeInElastic
  53897. * @param oscillations Defines the number of oscillations
  53898. * @param springiness Defines the amplitude of the oscillations
  53899. */
  53900. function ElasticEase(
  53901. /** Defines the number of oscillations*/
  53902. oscillations,
  53903. /** Defines the amplitude of the oscillations*/
  53904. springiness) {
  53905. if (oscillations === void 0) { oscillations = 3; }
  53906. if (springiness === void 0) { springiness = 3; }
  53907. var _this = _super.call(this) || this;
  53908. _this.oscillations = oscillations;
  53909. _this.springiness = springiness;
  53910. return _this;
  53911. }
  53912. /** @hidden */
  53913. ElasticEase.prototype.easeInCore = function (gradient) {
  53914. var num2;
  53915. var num3 = Math.max(0.0, this.oscillations);
  53916. var num = Math.max(0.0, this.springiness);
  53917. if (num == 0) {
  53918. num2 = gradient;
  53919. }
  53920. else {
  53921. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  53922. }
  53923. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  53924. };
  53925. return ElasticEase;
  53926. }(EasingFunction));
  53927. BABYLON.ElasticEase = ElasticEase;
  53928. /**
  53929. * Easing function with an exponential shape (see link below).
  53930. * @see https://easings.net/#easeInExpo
  53931. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53932. */
  53933. var ExponentialEase = /** @class */ (function (_super) {
  53934. __extends(ExponentialEase, _super);
  53935. /**
  53936. * Instantiates an exponential easing function
  53937. * @see https://easings.net/#easeInExpo
  53938. * @param exponent Defines the exponent of the function
  53939. */
  53940. function ExponentialEase(
  53941. /** Defines the exponent of the function */
  53942. exponent) {
  53943. if (exponent === void 0) { exponent = 2; }
  53944. var _this = _super.call(this) || this;
  53945. _this.exponent = exponent;
  53946. return _this;
  53947. }
  53948. /** @hidden */
  53949. ExponentialEase.prototype.easeInCore = function (gradient) {
  53950. if (this.exponent <= 0) {
  53951. return gradient;
  53952. }
  53953. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53954. };
  53955. return ExponentialEase;
  53956. }(EasingFunction));
  53957. BABYLON.ExponentialEase = ExponentialEase;
  53958. /**
  53959. * Easing function with a power shape (see link below).
  53960. * @see https://easings.net/#easeInQuad
  53961. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53962. */
  53963. var PowerEase = /** @class */ (function (_super) {
  53964. __extends(PowerEase, _super);
  53965. /**
  53966. * Instantiates an power base easing function
  53967. * @see https://easings.net/#easeInQuad
  53968. * @param power Defines the power of the function
  53969. */
  53970. function PowerEase(
  53971. /** Defines the power of the function */
  53972. power) {
  53973. if (power === void 0) { power = 2; }
  53974. var _this = _super.call(this) || this;
  53975. _this.power = power;
  53976. return _this;
  53977. }
  53978. /** @hidden */
  53979. PowerEase.prototype.easeInCore = function (gradient) {
  53980. var y = Math.max(0.0, this.power);
  53981. return Math.pow(gradient, y);
  53982. };
  53983. return PowerEase;
  53984. }(EasingFunction));
  53985. BABYLON.PowerEase = PowerEase;
  53986. /**
  53987. * Easing function with a power of 2 shape (see link below).
  53988. * @see https://easings.net/#easeInQuad
  53989. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53990. */
  53991. var QuadraticEase = /** @class */ (function (_super) {
  53992. __extends(QuadraticEase, _super);
  53993. function QuadraticEase() {
  53994. return _super !== null && _super.apply(this, arguments) || this;
  53995. }
  53996. /** @hidden */
  53997. QuadraticEase.prototype.easeInCore = function (gradient) {
  53998. return (gradient * gradient);
  53999. };
  54000. return QuadraticEase;
  54001. }(EasingFunction));
  54002. BABYLON.QuadraticEase = QuadraticEase;
  54003. /**
  54004. * Easing function with a power of 4 shape (see link below).
  54005. * @see https://easings.net/#easeInQuart
  54006. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54007. */
  54008. var QuarticEase = /** @class */ (function (_super) {
  54009. __extends(QuarticEase, _super);
  54010. function QuarticEase() {
  54011. return _super !== null && _super.apply(this, arguments) || this;
  54012. }
  54013. /** @hidden */
  54014. QuarticEase.prototype.easeInCore = function (gradient) {
  54015. return (gradient * gradient * gradient * gradient);
  54016. };
  54017. return QuarticEase;
  54018. }(EasingFunction));
  54019. BABYLON.QuarticEase = QuarticEase;
  54020. /**
  54021. * Easing function with a power of 5 shape (see link below).
  54022. * @see https://easings.net/#easeInQuint
  54023. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54024. */
  54025. var QuinticEase = /** @class */ (function (_super) {
  54026. __extends(QuinticEase, _super);
  54027. function QuinticEase() {
  54028. return _super !== null && _super.apply(this, arguments) || this;
  54029. }
  54030. /** @hidden */
  54031. QuinticEase.prototype.easeInCore = function (gradient) {
  54032. return (gradient * gradient * gradient * gradient * gradient);
  54033. };
  54034. return QuinticEase;
  54035. }(EasingFunction));
  54036. BABYLON.QuinticEase = QuinticEase;
  54037. /**
  54038. * Easing function with a sin shape (see link below).
  54039. * @see https://easings.net/#easeInSine
  54040. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54041. */
  54042. var SineEase = /** @class */ (function (_super) {
  54043. __extends(SineEase, _super);
  54044. function SineEase() {
  54045. return _super !== null && _super.apply(this, arguments) || this;
  54046. }
  54047. /** @hidden */
  54048. SineEase.prototype.easeInCore = function (gradient) {
  54049. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  54050. };
  54051. return SineEase;
  54052. }(EasingFunction));
  54053. BABYLON.SineEase = SineEase;
  54054. /**
  54055. * Easing function with a bezier shape (see link below).
  54056. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54057. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54058. */
  54059. var BezierCurveEase = /** @class */ (function (_super) {
  54060. __extends(BezierCurveEase, _super);
  54061. /**
  54062. * Instantiates a bezier function
  54063. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54064. * @param x1 Defines the x component of the start tangent in the bezier curve
  54065. * @param y1 Defines the y component of the start tangent in the bezier curve
  54066. * @param x2 Defines the x component of the end tangent in the bezier curve
  54067. * @param y2 Defines the y component of the end tangent in the bezier curve
  54068. */
  54069. function BezierCurveEase(
  54070. /** Defines the x component of the start tangent in the bezier curve */
  54071. x1,
  54072. /** Defines the y component of the start tangent in the bezier curve */
  54073. y1,
  54074. /** Defines the x component of the end tangent in the bezier curve */
  54075. x2,
  54076. /** Defines the y component of the end tangent in the bezier curve */
  54077. y2) {
  54078. if (x1 === void 0) { x1 = 0; }
  54079. if (y1 === void 0) { y1 = 0; }
  54080. if (x2 === void 0) { x2 = 1; }
  54081. if (y2 === void 0) { y2 = 1; }
  54082. var _this = _super.call(this) || this;
  54083. _this.x1 = x1;
  54084. _this.y1 = y1;
  54085. _this.x2 = x2;
  54086. _this.y2 = y2;
  54087. return _this;
  54088. }
  54089. /** @hidden */
  54090. BezierCurveEase.prototype.easeInCore = function (gradient) {
  54091. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  54092. };
  54093. return BezierCurveEase;
  54094. }(EasingFunction));
  54095. BABYLON.BezierCurveEase = BezierCurveEase;
  54096. })(BABYLON || (BABYLON = {}));
  54097. //# sourceMappingURL=babylon.easing.js.map
  54098. var BABYLON;
  54099. (function (BABYLON) {
  54100. /**
  54101. * A Condition applied to an Action
  54102. */
  54103. var Condition = /** @class */ (function () {
  54104. /**
  54105. * Creates a new Condition
  54106. * @param actionManager the manager of the action the condition is applied to
  54107. */
  54108. function Condition(actionManager) {
  54109. this._actionManager = actionManager;
  54110. }
  54111. /**
  54112. * Check if the current condition is valid
  54113. * @returns a boolean
  54114. */
  54115. Condition.prototype.isValid = function () {
  54116. return true;
  54117. };
  54118. /**
  54119. * Internal only
  54120. * @hidden
  54121. */
  54122. Condition.prototype._getProperty = function (propertyPath) {
  54123. return this._actionManager._getProperty(propertyPath);
  54124. };
  54125. /**
  54126. * Internal only
  54127. * @hidden
  54128. */
  54129. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  54130. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54131. };
  54132. /**
  54133. * Serialize placeholder for child classes
  54134. * @returns the serialized object
  54135. */
  54136. Condition.prototype.serialize = function () {
  54137. };
  54138. /**
  54139. * Internal only
  54140. * @hidden
  54141. */
  54142. Condition.prototype._serialize = function (serializedCondition) {
  54143. return {
  54144. type: 2,
  54145. children: [],
  54146. name: serializedCondition.name,
  54147. properties: serializedCondition.properties
  54148. };
  54149. };
  54150. return Condition;
  54151. }());
  54152. BABYLON.Condition = Condition;
  54153. /**
  54154. * Defines specific conditional operators as extensions of Condition
  54155. */
  54156. var ValueCondition = /** @class */ (function (_super) {
  54157. __extends(ValueCondition, _super);
  54158. /**
  54159. * Creates a new ValueCondition
  54160. * @param actionManager manager for the action the condition applies to
  54161. * @param target for the action
  54162. * @param propertyPath path to specify the property of the target the conditional operator uses
  54163. * @param value the value compared by the conditional operator against the current value of the property
  54164. * @param operator the conditional operator, default ValueCondition.IsEqual
  54165. */
  54166. function ValueCondition(actionManager, target,
  54167. /** path to specify the property of the target the conditional operator uses */
  54168. propertyPath,
  54169. /** the value compared by the conditional operator against the current value of the property */
  54170. value,
  54171. /** the conditional operator, default ValueCondition.IsEqual */
  54172. operator) {
  54173. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  54174. var _this = _super.call(this, actionManager) || this;
  54175. _this.propertyPath = propertyPath;
  54176. _this.value = value;
  54177. _this.operator = operator;
  54178. _this._target = target;
  54179. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  54180. _this._property = _this._getProperty(_this.propertyPath);
  54181. return _this;
  54182. }
  54183. Object.defineProperty(ValueCondition, "IsEqual", {
  54184. /**
  54185. * returns the number for IsEqual
  54186. */
  54187. get: function () {
  54188. return ValueCondition._IsEqual;
  54189. },
  54190. enumerable: true,
  54191. configurable: true
  54192. });
  54193. Object.defineProperty(ValueCondition, "IsDifferent", {
  54194. /**
  54195. * Returns the number for IsDifferent
  54196. */
  54197. get: function () {
  54198. return ValueCondition._IsDifferent;
  54199. },
  54200. enumerable: true,
  54201. configurable: true
  54202. });
  54203. Object.defineProperty(ValueCondition, "IsGreater", {
  54204. /**
  54205. * Returns the number for IsGreater
  54206. */
  54207. get: function () {
  54208. return ValueCondition._IsGreater;
  54209. },
  54210. enumerable: true,
  54211. configurable: true
  54212. });
  54213. Object.defineProperty(ValueCondition, "IsLesser", {
  54214. /**
  54215. * Returns the number for IsLesser
  54216. */
  54217. get: function () {
  54218. return ValueCondition._IsLesser;
  54219. },
  54220. enumerable: true,
  54221. configurable: true
  54222. });
  54223. /**
  54224. * Compares the given value with the property value for the specified conditional operator
  54225. * @returns the result of the comparison
  54226. */
  54227. ValueCondition.prototype.isValid = function () {
  54228. switch (this.operator) {
  54229. case ValueCondition.IsGreater:
  54230. return this._effectiveTarget[this._property] > this.value;
  54231. case ValueCondition.IsLesser:
  54232. return this._effectiveTarget[this._property] < this.value;
  54233. case ValueCondition.IsEqual:
  54234. case ValueCondition.IsDifferent:
  54235. var check;
  54236. if (this.value.equals) {
  54237. check = this.value.equals(this._effectiveTarget[this._property]);
  54238. }
  54239. else {
  54240. check = this.value === this._effectiveTarget[this._property];
  54241. }
  54242. return this.operator === ValueCondition.IsEqual ? check : !check;
  54243. }
  54244. return false;
  54245. };
  54246. /**
  54247. * Serialize the ValueCondition into a JSON compatible object
  54248. * @returns serialization object
  54249. */
  54250. ValueCondition.prototype.serialize = function () {
  54251. return this._serialize({
  54252. name: "ValueCondition",
  54253. properties: [
  54254. BABYLON.Action._GetTargetProperty(this._target),
  54255. { name: "propertyPath", value: this.propertyPath },
  54256. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54257. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54258. ]
  54259. });
  54260. };
  54261. /**
  54262. * Gets the name of the conditional operator for the ValueCondition
  54263. * @param operator the conditional operator
  54264. * @returns the name
  54265. */
  54266. ValueCondition.GetOperatorName = function (operator) {
  54267. switch (operator) {
  54268. case ValueCondition._IsEqual: return "IsEqual";
  54269. case ValueCondition._IsDifferent: return "IsDifferent";
  54270. case ValueCondition._IsGreater: return "IsGreater";
  54271. case ValueCondition._IsLesser: return "IsLesser";
  54272. default: return "";
  54273. }
  54274. };
  54275. /**
  54276. * Internal only
  54277. * @hidden
  54278. */
  54279. ValueCondition._IsEqual = 0;
  54280. /**
  54281. * Internal only
  54282. * @hidden
  54283. */
  54284. ValueCondition._IsDifferent = 1;
  54285. /**
  54286. * Internal only
  54287. * @hidden
  54288. */
  54289. ValueCondition._IsGreater = 2;
  54290. /**
  54291. * Internal only
  54292. * @hidden
  54293. */
  54294. ValueCondition._IsLesser = 3;
  54295. return ValueCondition;
  54296. }(Condition));
  54297. BABYLON.ValueCondition = ValueCondition;
  54298. /**
  54299. * Defines a predicate condition as an extension of Condition
  54300. */
  54301. var PredicateCondition = /** @class */ (function (_super) {
  54302. __extends(PredicateCondition, _super);
  54303. /**
  54304. * Creates a new PredicateCondition
  54305. * @param actionManager manager for the action the condition applies to
  54306. * @param predicate defines the predicate function used to validate the condition
  54307. */
  54308. function PredicateCondition(actionManager,
  54309. /** defines the predicate function used to validate the condition */
  54310. predicate) {
  54311. var _this = _super.call(this, actionManager) || this;
  54312. _this.predicate = predicate;
  54313. return _this;
  54314. }
  54315. /**
  54316. * @returns the validity of the predicate condition
  54317. */
  54318. PredicateCondition.prototype.isValid = function () {
  54319. return this.predicate();
  54320. };
  54321. return PredicateCondition;
  54322. }(Condition));
  54323. BABYLON.PredicateCondition = PredicateCondition;
  54324. /**
  54325. * Defines a state condition as an extension of Condition
  54326. */
  54327. var StateCondition = /** @class */ (function (_super) {
  54328. __extends(StateCondition, _super);
  54329. /**
  54330. * Creates a new StateCondition
  54331. * @param actionManager manager for the action the condition applies to
  54332. * @param target of the condition
  54333. * @param value to compare with target state
  54334. */
  54335. function StateCondition(actionManager, target, value) {
  54336. var _this = _super.call(this, actionManager) || this;
  54337. _this.value = value;
  54338. _this._target = target;
  54339. return _this;
  54340. }
  54341. /**
  54342. * @returns the validity of the state
  54343. */
  54344. StateCondition.prototype.isValid = function () {
  54345. return this._target.state === this.value;
  54346. };
  54347. /**
  54348. * Serialize the StateCondition into a JSON compatible object
  54349. * @returns serialization object
  54350. */
  54351. StateCondition.prototype.serialize = function () {
  54352. return this._serialize({
  54353. name: "StateCondition",
  54354. properties: [
  54355. BABYLON.Action._GetTargetProperty(this._target),
  54356. { name: "value", value: this.value }
  54357. ]
  54358. });
  54359. };
  54360. return StateCondition;
  54361. }(Condition));
  54362. BABYLON.StateCondition = StateCondition;
  54363. })(BABYLON || (BABYLON = {}));
  54364. //# sourceMappingURL=babylon.condition.js.map
  54365. var BABYLON;
  54366. (function (BABYLON) {
  54367. /**
  54368. * The action to be carried out following a trigger
  54369. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  54370. */
  54371. var Action = /** @class */ (function () {
  54372. /**
  54373. * Creates a new Action
  54374. * @param triggerOptions the trigger, with or without parameters, for the action
  54375. * @param condition an optional determinant of action
  54376. */
  54377. function Action(
  54378. /** the trigger, with or without parameters, for the action */
  54379. triggerOptions, condition) {
  54380. this.triggerOptions = triggerOptions;
  54381. /**
  54382. * An event triggered prior to action being executed.
  54383. */
  54384. this.onBeforeExecuteObservable = new BABYLON.Observable();
  54385. if (triggerOptions.parameter) {
  54386. this.trigger = triggerOptions.trigger;
  54387. this._triggerParameter = triggerOptions.parameter;
  54388. }
  54389. else if (triggerOptions.trigger) {
  54390. this.trigger = triggerOptions.trigger;
  54391. }
  54392. else {
  54393. this.trigger = triggerOptions;
  54394. }
  54395. this._nextActiveAction = this;
  54396. this._condition = condition;
  54397. }
  54398. /**
  54399. * Internal only
  54400. * @hidden
  54401. */
  54402. Action.prototype._prepare = function () {
  54403. };
  54404. /**
  54405. * Gets the trigger parameters
  54406. * @returns the trigger parameters
  54407. */
  54408. Action.prototype.getTriggerParameter = function () {
  54409. return this._triggerParameter;
  54410. };
  54411. /**
  54412. * Internal only - executes current action event
  54413. * @hidden
  54414. */
  54415. Action.prototype._executeCurrent = function (evt) {
  54416. if (this._nextActiveAction._condition) {
  54417. var condition = this._nextActiveAction._condition;
  54418. var currentRenderId = this._actionManager.getScene().getRenderId();
  54419. // We cache the current evaluation for the current frame
  54420. if (condition._evaluationId === currentRenderId) {
  54421. if (!condition._currentResult) {
  54422. return;
  54423. }
  54424. }
  54425. else {
  54426. condition._evaluationId = currentRenderId;
  54427. if (!condition.isValid()) {
  54428. condition._currentResult = false;
  54429. return;
  54430. }
  54431. condition._currentResult = true;
  54432. }
  54433. }
  54434. this.onBeforeExecuteObservable.notifyObservers(this);
  54435. this._nextActiveAction.execute(evt);
  54436. this.skipToNextActiveAction();
  54437. };
  54438. /**
  54439. * Execute placeholder for child classes
  54440. * @param evt optional action event
  54441. */
  54442. Action.prototype.execute = function (evt) {
  54443. };
  54444. /**
  54445. * Skips to next active action
  54446. */
  54447. Action.prototype.skipToNextActiveAction = function () {
  54448. if (this._nextActiveAction._child) {
  54449. if (!this._nextActiveAction._child._actionManager) {
  54450. this._nextActiveAction._child._actionManager = this._actionManager;
  54451. }
  54452. this._nextActiveAction = this._nextActiveAction._child;
  54453. }
  54454. else {
  54455. this._nextActiveAction = this;
  54456. }
  54457. };
  54458. /**
  54459. * Adds action to chain of actions, may be a DoNothingAction
  54460. * @param action defines the next action to execute
  54461. * @returns The action passed in
  54462. * @see https://www.babylonjs-playground.com/#1T30HR#0
  54463. */
  54464. Action.prototype.then = function (action) {
  54465. this._child = action;
  54466. action._actionManager = this._actionManager;
  54467. action._prepare();
  54468. return action;
  54469. };
  54470. /**
  54471. * Internal only
  54472. * @hidden
  54473. */
  54474. Action.prototype._getProperty = function (propertyPath) {
  54475. return this._actionManager._getProperty(propertyPath);
  54476. };
  54477. /**
  54478. * Internal only
  54479. * @hidden
  54480. */
  54481. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  54482. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54483. };
  54484. /**
  54485. * Serialize placeholder for child classes
  54486. * @param parent of child
  54487. * @returns the serialized object
  54488. */
  54489. Action.prototype.serialize = function (parent) {
  54490. };
  54491. /**
  54492. * Internal only called by serialize
  54493. * @hidden
  54494. */
  54495. Action.prototype._serialize = function (serializedAction, parent) {
  54496. var serializationObject = {
  54497. type: 1,
  54498. children: [],
  54499. name: serializedAction.name,
  54500. properties: serializedAction.properties || []
  54501. };
  54502. // Serialize child
  54503. if (this._child) {
  54504. this._child.serialize(serializationObject);
  54505. }
  54506. // Check if "this" has a condition
  54507. if (this._condition) {
  54508. var serializedCondition = this._condition.serialize();
  54509. serializedCondition.children.push(serializationObject);
  54510. if (parent) {
  54511. parent.children.push(serializedCondition);
  54512. }
  54513. return serializedCondition;
  54514. }
  54515. if (parent) {
  54516. parent.children.push(serializationObject);
  54517. }
  54518. return serializationObject;
  54519. };
  54520. /**
  54521. * Internal only
  54522. * @hidden
  54523. */
  54524. Action._SerializeValueAsString = function (value) {
  54525. if (typeof value === "number") {
  54526. return value.toString();
  54527. }
  54528. if (typeof value === "boolean") {
  54529. return value ? "true" : "false";
  54530. }
  54531. if (value instanceof BABYLON.Vector2) {
  54532. return value.x + ", " + value.y;
  54533. }
  54534. if (value instanceof BABYLON.Vector3) {
  54535. return value.x + ", " + value.y + ", " + value.z;
  54536. }
  54537. if (value instanceof BABYLON.Color3) {
  54538. return value.r + ", " + value.g + ", " + value.b;
  54539. }
  54540. if (value instanceof BABYLON.Color4) {
  54541. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  54542. }
  54543. return value; // string
  54544. };
  54545. /**
  54546. * Internal only
  54547. * @hidden
  54548. */
  54549. Action._GetTargetProperty = function (target) {
  54550. return {
  54551. name: "target",
  54552. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  54553. : target instanceof BABYLON.Light ? "LightProperties"
  54554. : target instanceof BABYLON.Camera ? "CameraProperties"
  54555. : "SceneProperties",
  54556. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  54557. };
  54558. };
  54559. return Action;
  54560. }());
  54561. BABYLON.Action = Action;
  54562. })(BABYLON || (BABYLON = {}));
  54563. //# sourceMappingURL=babylon.action.js.map
  54564. var BABYLON;
  54565. (function (BABYLON) {
  54566. /**
  54567. * ActionEvent is the event being sent when an action is triggered.
  54568. */
  54569. var ActionEvent = /** @class */ (function () {
  54570. /**
  54571. * Creates a new ActionEvent
  54572. * @param source The mesh or sprite that triggered the action
  54573. * @param pointerX The X mouse cursor position at the time of the event
  54574. * @param pointerY The Y mouse cursor position at the time of the event
  54575. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  54576. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  54577. * @param additionalData additional data for the event
  54578. */
  54579. function ActionEvent(
  54580. /** The mesh or sprite that triggered the action */
  54581. source,
  54582. /** The X mouse cursor position at the time of the event */
  54583. pointerX,
  54584. /** The Y mouse cursor position at the time of the event */
  54585. pointerY,
  54586. /** The mesh that is currently pointed at (can be null) */
  54587. meshUnderPointer,
  54588. /** the original (browser) event that triggered the ActionEvent */
  54589. sourceEvent,
  54590. /** additional data for the event */
  54591. additionalData) {
  54592. this.source = source;
  54593. this.pointerX = pointerX;
  54594. this.pointerY = pointerY;
  54595. this.meshUnderPointer = meshUnderPointer;
  54596. this.sourceEvent = sourceEvent;
  54597. this.additionalData = additionalData;
  54598. }
  54599. /**
  54600. * Helper function to auto-create an ActionEvent from a source mesh.
  54601. * @param source The source mesh that triggered the event
  54602. * @param evt The original (browser) event
  54603. * @param additionalData additional data for the event
  54604. * @returns the new ActionEvent
  54605. */
  54606. ActionEvent.CreateNew = function (source, evt, additionalData) {
  54607. var scene = source.getScene();
  54608. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  54609. };
  54610. /**
  54611. * Helper function to auto-create an ActionEvent from a source sprite
  54612. * @param source The source sprite that triggered the event
  54613. * @param scene Scene associated with the sprite
  54614. * @param evt The original (browser) event
  54615. * @param additionalData additional data for the event
  54616. * @returns the new ActionEvent
  54617. */
  54618. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  54619. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  54620. };
  54621. /**
  54622. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  54623. * @param scene the scene where the event occurred
  54624. * @param evt The original (browser) event
  54625. * @returns the new ActionEvent
  54626. */
  54627. ActionEvent.CreateNewFromScene = function (scene, evt) {
  54628. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  54629. };
  54630. /**
  54631. * Helper function to auto-create an ActionEvent from a primitive
  54632. * @param prim defines the target primitive
  54633. * @param pointerPos defines the pointer position
  54634. * @param evt The original (browser) event
  54635. * @param additionalData additional data for the event
  54636. * @returns the new ActionEvent
  54637. */
  54638. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  54639. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  54640. };
  54641. return ActionEvent;
  54642. }());
  54643. BABYLON.ActionEvent = ActionEvent;
  54644. /**
  54645. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  54646. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  54647. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54648. */
  54649. var ActionManager = /** @class */ (function () {
  54650. /**
  54651. * Creates a new action manager
  54652. * @param scene defines the hosting scene
  54653. */
  54654. function ActionManager(scene) {
  54655. // Members
  54656. /** Gets the list of actions */
  54657. this.actions = new Array();
  54658. /** Gets the cursor to use when hovering items */
  54659. this.hoverCursor = '';
  54660. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54661. scene.actionManagers.push(this);
  54662. }
  54663. // Methods
  54664. /**
  54665. * Releases all associated resources
  54666. */
  54667. ActionManager.prototype.dispose = function () {
  54668. var index = this._scene.actionManagers.indexOf(this);
  54669. for (var i = 0; i < this.actions.length; i++) {
  54670. var action = this.actions[i];
  54671. ActionManager.Triggers[action.trigger]--;
  54672. if (ActionManager.Triggers[action.trigger] === 0) {
  54673. delete ActionManager.Triggers[action.trigger];
  54674. }
  54675. }
  54676. if (index > -1) {
  54677. this._scene.actionManagers.splice(index, 1);
  54678. }
  54679. };
  54680. /**
  54681. * Gets hosting scene
  54682. * @returns the hosting scene
  54683. */
  54684. ActionManager.prototype.getScene = function () {
  54685. return this._scene;
  54686. };
  54687. /**
  54688. * Does this action manager handles actions of any of the given triggers
  54689. * @param triggers defines the triggers to be tested
  54690. * @return a boolean indicating whether one (or more) of the triggers is handled
  54691. */
  54692. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  54693. for (var index = 0; index < this.actions.length; index++) {
  54694. var action = this.actions[index];
  54695. if (triggers.indexOf(action.trigger) > -1) {
  54696. return true;
  54697. }
  54698. }
  54699. return false;
  54700. };
  54701. /**
  54702. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  54703. * speed.
  54704. * @param triggerA defines the trigger to be tested
  54705. * @param triggerB defines the trigger to be tested
  54706. * @return a boolean indicating whether one (or more) of the triggers is handled
  54707. */
  54708. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  54709. for (var index = 0; index < this.actions.length; index++) {
  54710. var action = this.actions[index];
  54711. if (triggerA == action.trigger || triggerB == action.trigger) {
  54712. return true;
  54713. }
  54714. }
  54715. return false;
  54716. };
  54717. /**
  54718. * Does this action manager handles actions of a given trigger
  54719. * @param trigger defines the trigger to be tested
  54720. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  54721. * @return whether the trigger is handled
  54722. */
  54723. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  54724. for (var index = 0; index < this.actions.length; index++) {
  54725. var action = this.actions[index];
  54726. if (action.trigger === trigger) {
  54727. if (parameterPredicate) {
  54728. if (parameterPredicate(action.getTriggerParameter())) {
  54729. return true;
  54730. }
  54731. }
  54732. else {
  54733. return true;
  54734. }
  54735. }
  54736. }
  54737. return false;
  54738. };
  54739. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  54740. /**
  54741. * Does this action manager has pointer triggers
  54742. */
  54743. get: function () {
  54744. for (var index = 0; index < this.actions.length; index++) {
  54745. var action = this.actions[index];
  54746. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  54747. return true;
  54748. }
  54749. }
  54750. return false;
  54751. },
  54752. enumerable: true,
  54753. configurable: true
  54754. });
  54755. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  54756. /**
  54757. * Does this action manager has pick triggers
  54758. */
  54759. get: function () {
  54760. for (var index = 0; index < this.actions.length; index++) {
  54761. var action = this.actions[index];
  54762. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  54763. return true;
  54764. }
  54765. }
  54766. return false;
  54767. },
  54768. enumerable: true,
  54769. configurable: true
  54770. });
  54771. Object.defineProperty(ActionManager, "HasTriggers", {
  54772. /**
  54773. * Does exist one action manager with at least one trigger
  54774. **/
  54775. get: function () {
  54776. for (var t in ActionManager.Triggers) {
  54777. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54778. return true;
  54779. }
  54780. }
  54781. return false;
  54782. },
  54783. enumerable: true,
  54784. configurable: true
  54785. });
  54786. Object.defineProperty(ActionManager, "HasPickTriggers", {
  54787. /**
  54788. * Does exist one action manager with at least one pick trigger
  54789. **/
  54790. get: function () {
  54791. for (var t in ActionManager.Triggers) {
  54792. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54793. var t_int = parseInt(t);
  54794. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  54795. return true;
  54796. }
  54797. }
  54798. }
  54799. return false;
  54800. },
  54801. enumerable: true,
  54802. configurable: true
  54803. });
  54804. /**
  54805. * Does exist one action manager that handles actions of a given trigger
  54806. * @param trigger defines the trigger to be tested
  54807. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  54808. **/
  54809. ActionManager.HasSpecificTrigger = function (trigger) {
  54810. for (var t in ActionManager.Triggers) {
  54811. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54812. var t_int = parseInt(t);
  54813. if (t_int === trigger) {
  54814. return true;
  54815. }
  54816. }
  54817. }
  54818. return false;
  54819. };
  54820. /**
  54821. * Registers an action to this action manager
  54822. * @param action defines the action to be registered
  54823. * @return the action amended (prepared) after registration
  54824. */
  54825. ActionManager.prototype.registerAction = function (action) {
  54826. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  54827. if (this.getScene().actionManager !== this) {
  54828. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  54829. return null;
  54830. }
  54831. }
  54832. this.actions.push(action);
  54833. if (ActionManager.Triggers[action.trigger]) {
  54834. ActionManager.Triggers[action.trigger]++;
  54835. }
  54836. else {
  54837. ActionManager.Triggers[action.trigger] = 1;
  54838. }
  54839. action._actionManager = this;
  54840. action._prepare();
  54841. return action;
  54842. };
  54843. /**
  54844. * Unregisters an action to this action manager
  54845. * @param action defines the action to be unregistered
  54846. * @return a boolean indicating whether the action has been unregistered
  54847. */
  54848. ActionManager.prototype.unregisterAction = function (action) {
  54849. var index = this.actions.indexOf(action);
  54850. if (index !== -1) {
  54851. this.actions.splice(index, 1);
  54852. ActionManager.Triggers[action.trigger] -= 1;
  54853. if (ActionManager.Triggers[action.trigger] === 0) {
  54854. delete ActionManager.Triggers[action.trigger];
  54855. }
  54856. delete action._actionManager;
  54857. return true;
  54858. }
  54859. return false;
  54860. };
  54861. /**
  54862. * Process a specific trigger
  54863. * @param trigger defines the trigger to process
  54864. * @param evt defines the event details to be processed
  54865. */
  54866. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54867. for (var index = 0; index < this.actions.length; index++) {
  54868. var action = this.actions[index];
  54869. if (action.trigger === trigger) {
  54870. if (evt) {
  54871. if (trigger === ActionManager.OnKeyUpTrigger
  54872. || trigger === ActionManager.OnKeyDownTrigger) {
  54873. var parameter = action.getTriggerParameter();
  54874. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54875. if (!parameter.toLowerCase) {
  54876. continue;
  54877. }
  54878. var lowerCase = parameter.toLowerCase();
  54879. if (lowerCase !== evt.sourceEvent.key) {
  54880. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54881. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54882. if (actualkey !== lowerCase) {
  54883. continue;
  54884. }
  54885. }
  54886. }
  54887. }
  54888. }
  54889. action._executeCurrent(evt);
  54890. }
  54891. }
  54892. };
  54893. /** @hidden */
  54894. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54895. var properties = propertyPath.split(".");
  54896. for (var index = 0; index < properties.length - 1; index++) {
  54897. target = target[properties[index]];
  54898. }
  54899. return target;
  54900. };
  54901. /** @hidden */
  54902. ActionManager.prototype._getProperty = function (propertyPath) {
  54903. var properties = propertyPath.split(".");
  54904. return properties[properties.length - 1];
  54905. };
  54906. /**
  54907. * Serialize this manager to a JSON object
  54908. * @param name defines the property name to store this manager
  54909. * @returns a JSON representation of this manager
  54910. */
  54911. ActionManager.prototype.serialize = function (name) {
  54912. var root = {
  54913. children: new Array(),
  54914. name: name,
  54915. type: 3,
  54916. properties: new Array() // Empty for root but required
  54917. };
  54918. for (var i = 0; i < this.actions.length; i++) {
  54919. var triggerObject = {
  54920. type: 0,
  54921. children: new Array(),
  54922. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54923. properties: new Array()
  54924. };
  54925. var triggerOptions = this.actions[i].triggerOptions;
  54926. if (triggerOptions && typeof triggerOptions !== "number") {
  54927. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54928. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54929. }
  54930. else {
  54931. var parameter = {};
  54932. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54933. if (triggerOptions.parameter.mesh) {
  54934. parameter._meshId = triggerOptions.parameter.mesh.id;
  54935. }
  54936. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54937. }
  54938. }
  54939. // Serialize child action, recursively
  54940. this.actions[i].serialize(triggerObject);
  54941. // Add serialized trigger
  54942. root.children.push(triggerObject);
  54943. }
  54944. return root;
  54945. };
  54946. /**
  54947. * Creates a new ActionManager from a JSON data
  54948. * @param parsedActions defines the JSON data to read from
  54949. * @param object defines the hosting mesh
  54950. * @param scene defines the hosting scene
  54951. */
  54952. ActionManager.Parse = function (parsedActions, object, scene) {
  54953. var actionManager = new ActionManager(scene);
  54954. if (object === null)
  54955. scene.actionManager = actionManager;
  54956. else
  54957. object.actionManager = actionManager;
  54958. // instanciate a new object
  54959. var instanciate = function (name, params) {
  54960. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54961. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54962. newInstance.constructor.apply(newInstance, params);
  54963. return newInstance;
  54964. };
  54965. var parseParameter = function (name, value, target, propertyPath) {
  54966. if (propertyPath === null) {
  54967. // String, boolean or float
  54968. var floatValue = parseFloat(value);
  54969. if (value === "true" || value === "false")
  54970. return value === "true";
  54971. else
  54972. return isNaN(floatValue) ? value : floatValue;
  54973. }
  54974. var effectiveTarget = propertyPath.split(".");
  54975. var values = value.split(",");
  54976. // Get effective Target
  54977. for (var i = 0; i < effectiveTarget.length; i++) {
  54978. target = target[effectiveTarget[i]];
  54979. }
  54980. // Return appropriate value with its type
  54981. if (typeof (target) === "boolean")
  54982. return values[0] === "true";
  54983. if (typeof (target) === "string")
  54984. return values[0];
  54985. // Parameters with multiple values such as Vector3 etc.
  54986. var split = new Array();
  54987. for (var i = 0; i < values.length; i++)
  54988. split.push(parseFloat(values[i]));
  54989. if (target instanceof BABYLON.Vector3)
  54990. return BABYLON.Vector3.FromArray(split);
  54991. if (target instanceof BABYLON.Vector4)
  54992. return BABYLON.Vector4.FromArray(split);
  54993. if (target instanceof BABYLON.Color3)
  54994. return BABYLON.Color3.FromArray(split);
  54995. if (target instanceof BABYLON.Color4)
  54996. return BABYLON.Color4.FromArray(split);
  54997. return parseFloat(values[0]);
  54998. };
  54999. // traverse graph per trigger
  55000. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  55001. if (combineArray === void 0) { combineArray = null; }
  55002. if (parsedAction.detached)
  55003. return;
  55004. var parameters = new Array();
  55005. var target = null;
  55006. var propertyPath = null;
  55007. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  55008. // Parameters
  55009. if (parsedAction.type === 2)
  55010. parameters.push(actionManager);
  55011. else
  55012. parameters.push(trigger);
  55013. if (combine) {
  55014. var actions = new Array();
  55015. for (var j = 0; j < parsedAction.combine.length; j++) {
  55016. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  55017. }
  55018. parameters.push(actions);
  55019. }
  55020. else {
  55021. for (var i = 0; i < parsedAction.properties.length; i++) {
  55022. var value = parsedAction.properties[i].value;
  55023. var name = parsedAction.properties[i].name;
  55024. var targetType = parsedAction.properties[i].targetType;
  55025. if (name === "target")
  55026. if (targetType !== null && targetType === "SceneProperties")
  55027. value = target = scene;
  55028. else
  55029. value = target = scene.getNodeByName(value);
  55030. else if (name === "parent")
  55031. value = scene.getNodeByName(value);
  55032. else if (name === "sound") {
  55033. // Can not externalize to component, so only checks for the presence off the API.
  55034. if (scene.getSoundByName) {
  55035. value = scene.getSoundByName(value);
  55036. }
  55037. }
  55038. else if (name !== "propertyPath") {
  55039. if (parsedAction.type === 2 && name === "operator")
  55040. value = BABYLON.ValueCondition[value];
  55041. else
  55042. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  55043. }
  55044. else {
  55045. propertyPath = value;
  55046. }
  55047. parameters.push(value);
  55048. }
  55049. }
  55050. if (combineArray === null) {
  55051. parameters.push(condition);
  55052. }
  55053. else {
  55054. parameters.push(null);
  55055. }
  55056. // If interpolate value action
  55057. if (parsedAction.name === "InterpolateValueAction") {
  55058. var param = parameters[parameters.length - 2];
  55059. parameters[parameters.length - 1] = param;
  55060. parameters[parameters.length - 2] = condition;
  55061. }
  55062. // Action or condition(s) and not CombineAction
  55063. var newAction = instanciate(parsedAction.name, parameters);
  55064. if (newAction instanceof BABYLON.Condition && condition !== null) {
  55065. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  55066. if (action)
  55067. action.then(nothing);
  55068. else
  55069. actionManager.registerAction(nothing);
  55070. action = nothing;
  55071. }
  55072. if (combineArray === null) {
  55073. if (newAction instanceof BABYLON.Condition) {
  55074. condition = newAction;
  55075. newAction = action;
  55076. }
  55077. else {
  55078. condition = null;
  55079. if (action)
  55080. action.then(newAction);
  55081. else
  55082. actionManager.registerAction(newAction);
  55083. }
  55084. }
  55085. else {
  55086. combineArray.push(newAction);
  55087. }
  55088. for (var i = 0; i < parsedAction.children.length; i++)
  55089. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  55090. };
  55091. // triggers
  55092. for (var i = 0; i < parsedActions.children.length; i++) {
  55093. var triggerParams;
  55094. var trigger = parsedActions.children[i];
  55095. if (trigger.properties.length > 0) {
  55096. var param = trigger.properties[0].value;
  55097. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  55098. if (value._meshId) {
  55099. value.mesh = scene.getMeshByID(value._meshId);
  55100. }
  55101. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  55102. }
  55103. else
  55104. triggerParams = ActionManager[trigger.name];
  55105. for (var j = 0; j < trigger.children.length; j++) {
  55106. if (!trigger.detached)
  55107. traverse(trigger.children[j], triggerParams, null, null);
  55108. }
  55109. }
  55110. };
  55111. /**
  55112. * Get a trigger name by index
  55113. * @param trigger defines the trigger index
  55114. * @returns a trigger name
  55115. */
  55116. ActionManager.GetTriggerName = function (trigger) {
  55117. switch (trigger) {
  55118. case 0: return "NothingTrigger";
  55119. case 1: return "OnPickTrigger";
  55120. case 2: return "OnLeftPickTrigger";
  55121. case 3: return "OnRightPickTrigger";
  55122. case 4: return "OnCenterPickTrigger";
  55123. case 5: return "OnPickDownTrigger";
  55124. case 6: return "OnPickUpTrigger";
  55125. case 7: return "OnLongPressTrigger";
  55126. case 8: return "OnPointerOverTrigger";
  55127. case 9: return "OnPointerOutTrigger";
  55128. case 10: return "OnEveryFrameTrigger";
  55129. case 11: return "OnIntersectionEnterTrigger";
  55130. case 12: return "OnIntersectionExitTrigger";
  55131. case 13: return "OnKeyDownTrigger";
  55132. case 14: return "OnKeyUpTrigger";
  55133. case 15: return "OnPickOutTrigger";
  55134. default: return "";
  55135. }
  55136. };
  55137. /**
  55138. * Nothing
  55139. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55140. */
  55141. ActionManager.NothingTrigger = 0;
  55142. /**
  55143. * On pick
  55144. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55145. */
  55146. ActionManager.OnPickTrigger = 1;
  55147. /**
  55148. * On left pick
  55149. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55150. */
  55151. ActionManager.OnLeftPickTrigger = 2;
  55152. /**
  55153. * On right pick
  55154. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55155. */
  55156. ActionManager.OnRightPickTrigger = 3;
  55157. /**
  55158. * On center pick
  55159. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55160. */
  55161. ActionManager.OnCenterPickTrigger = 4;
  55162. /**
  55163. * On pick down
  55164. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55165. */
  55166. ActionManager.OnPickDownTrigger = 5;
  55167. /**
  55168. * On double pick
  55169. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55170. */
  55171. ActionManager.OnDoublePickTrigger = 6;
  55172. /**
  55173. * On pick up
  55174. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55175. */
  55176. ActionManager.OnPickUpTrigger = 7;
  55177. /**
  55178. * On pick out.
  55179. * This trigger will only be raised if you also declared a OnPickDown
  55180. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55181. */
  55182. ActionManager.OnPickOutTrigger = 16;
  55183. /**
  55184. * On long press
  55185. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55186. */
  55187. ActionManager.OnLongPressTrigger = 8;
  55188. /**
  55189. * On pointer over
  55190. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55191. */
  55192. ActionManager.OnPointerOverTrigger = 9;
  55193. /**
  55194. * On pointer out
  55195. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55196. */
  55197. ActionManager.OnPointerOutTrigger = 10;
  55198. /**
  55199. * On every frame
  55200. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55201. */
  55202. ActionManager.OnEveryFrameTrigger = 11;
  55203. /**
  55204. * On intersection enter
  55205. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55206. */
  55207. ActionManager.OnIntersectionEnterTrigger = 12;
  55208. /**
  55209. * On intersection exit
  55210. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55211. */
  55212. ActionManager.OnIntersectionExitTrigger = 13;
  55213. /**
  55214. * On key down
  55215. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55216. */
  55217. ActionManager.OnKeyDownTrigger = 14;
  55218. /**
  55219. * On key up
  55220. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55221. */
  55222. ActionManager.OnKeyUpTrigger = 15;
  55223. /** Gets the list of active triggers */
  55224. ActionManager.Triggers = {};
  55225. return ActionManager;
  55226. }());
  55227. BABYLON.ActionManager = ActionManager;
  55228. })(BABYLON || (BABYLON = {}));
  55229. //# sourceMappingURL=babylon.actionManager.js.map
  55230. var BABYLON;
  55231. (function (BABYLON) {
  55232. /**
  55233. * This defines an action responsible to change the value of a property
  55234. * by interpolating between its current value and the newly set one once triggered.
  55235. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55236. */
  55237. var InterpolateValueAction = /** @class */ (function (_super) {
  55238. __extends(InterpolateValueAction, _super);
  55239. /**
  55240. * Instantiate the action
  55241. * @param triggerOptions defines the trigger options
  55242. * @param target defines the object containing the value to interpolate
  55243. * @param propertyPath defines the path to the property in the target object
  55244. * @param value defines the target value at the end of the interpolation
  55245. * @param duration deines the time it will take for the property to interpolate to the value.
  55246. * @param condition defines the trigger related conditions
  55247. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55248. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55249. */
  55250. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55251. if (duration === void 0) { duration = 1000; }
  55252. var _this = _super.call(this, triggerOptions, condition) || this;
  55253. /**
  55254. * Defines the time it will take for the property to interpolate to the value.
  55255. */
  55256. _this.duration = 1000;
  55257. /**
  55258. * Observable triggered once the interpolation animation has been done.
  55259. */
  55260. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55261. _this.propertyPath = propertyPath;
  55262. _this.value = value;
  55263. _this.duration = duration;
  55264. _this.stopOtherAnimations = stopOtherAnimations;
  55265. _this.onInterpolationDone = onInterpolationDone;
  55266. _this._target = _this._effectiveTarget = target;
  55267. return _this;
  55268. }
  55269. /** @hidden */
  55270. InterpolateValueAction.prototype._prepare = function () {
  55271. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55272. this._property = this._getProperty(this.propertyPath);
  55273. };
  55274. /**
  55275. * Execute the action starts the value interpolation.
  55276. */
  55277. InterpolateValueAction.prototype.execute = function () {
  55278. var _this = this;
  55279. var scene = this._actionManager.getScene();
  55280. var keys = [
  55281. {
  55282. frame: 0,
  55283. value: this._effectiveTarget[this._property]
  55284. }, {
  55285. frame: 100,
  55286. value: this.value
  55287. }
  55288. ];
  55289. var dataType;
  55290. if (typeof this.value === "number") {
  55291. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  55292. }
  55293. else if (this.value instanceof BABYLON.Color3) {
  55294. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  55295. }
  55296. else if (this.value instanceof BABYLON.Vector3) {
  55297. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  55298. }
  55299. else if (this.value instanceof BABYLON.Matrix) {
  55300. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  55301. }
  55302. else if (this.value instanceof BABYLON.Quaternion) {
  55303. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  55304. }
  55305. else {
  55306. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  55307. return;
  55308. }
  55309. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  55310. animation.setKeys(keys);
  55311. if (this.stopOtherAnimations) {
  55312. scene.stopAnimation(this._effectiveTarget);
  55313. }
  55314. var wrapper = function () {
  55315. _this.onInterpolationDoneObservable.notifyObservers(_this);
  55316. if (_this.onInterpolationDone) {
  55317. _this.onInterpolationDone();
  55318. }
  55319. };
  55320. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  55321. };
  55322. /**
  55323. * Serializes the actions and its related information.
  55324. * @param parent defines the object to serialize in
  55325. * @returns the serialized object
  55326. */
  55327. InterpolateValueAction.prototype.serialize = function (parent) {
  55328. return _super.prototype._serialize.call(this, {
  55329. name: "InterpolateValueAction",
  55330. properties: [
  55331. BABYLON.Action._GetTargetProperty(this._target),
  55332. { name: "propertyPath", value: this.propertyPath },
  55333. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  55334. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  55335. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  55336. ]
  55337. }, parent);
  55338. };
  55339. return InterpolateValueAction;
  55340. }(BABYLON.Action));
  55341. BABYLON.InterpolateValueAction = InterpolateValueAction;
  55342. })(BABYLON || (BABYLON = {}));
  55343. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  55344. var BABYLON;
  55345. (function (BABYLON) {
  55346. /**
  55347. * This defines an action responsible to toggle a boolean once triggered.
  55348. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55349. */
  55350. var SwitchBooleanAction = /** @class */ (function (_super) {
  55351. __extends(SwitchBooleanAction, _super);
  55352. /**
  55353. * Instantiate the action
  55354. * @param triggerOptions defines the trigger options
  55355. * @param target defines the object containing the boolean
  55356. * @param propertyPath defines the path to the boolean property in the target object
  55357. * @param condition defines the trigger related conditions
  55358. */
  55359. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  55360. var _this = _super.call(this, triggerOptions, condition) || this;
  55361. _this.propertyPath = propertyPath;
  55362. _this._target = _this._effectiveTarget = target;
  55363. return _this;
  55364. }
  55365. /** @hidden */
  55366. SwitchBooleanAction.prototype._prepare = function () {
  55367. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55368. this._property = this._getProperty(this.propertyPath);
  55369. };
  55370. /**
  55371. * Execute the action toggle the boolean value.
  55372. */
  55373. SwitchBooleanAction.prototype.execute = function () {
  55374. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  55375. };
  55376. /**
  55377. * Serializes the actions and its related information.
  55378. * @param parent defines the object to serialize in
  55379. * @returns the serialized object
  55380. */
  55381. SwitchBooleanAction.prototype.serialize = function (parent) {
  55382. return _super.prototype._serialize.call(this, {
  55383. name: "SwitchBooleanAction",
  55384. properties: [
  55385. BABYLON.Action._GetTargetProperty(this._target),
  55386. { name: "propertyPath", value: this.propertyPath }
  55387. ]
  55388. }, parent);
  55389. };
  55390. return SwitchBooleanAction;
  55391. }(BABYLON.Action));
  55392. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  55393. /**
  55394. * This defines an action responsible to set a the state field of the target
  55395. * to a desired value once triggered.
  55396. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55397. */
  55398. var SetStateAction = /** @class */ (function (_super) {
  55399. __extends(SetStateAction, _super);
  55400. /**
  55401. * Instantiate the action
  55402. * @param triggerOptions defines the trigger options
  55403. * @param target defines the object containing the state property
  55404. * @param value defines the value to store in the state field
  55405. * @param condition defines the trigger related conditions
  55406. */
  55407. function SetStateAction(triggerOptions, target, value, condition) {
  55408. var _this = _super.call(this, triggerOptions, condition) || this;
  55409. _this.value = value;
  55410. _this._target = target;
  55411. return _this;
  55412. }
  55413. /**
  55414. * Execute the action and store the value on the target state property.
  55415. */
  55416. SetStateAction.prototype.execute = function () {
  55417. this._target.state = this.value;
  55418. };
  55419. /**
  55420. * Serializes the actions and its related information.
  55421. * @param parent defines the object to serialize in
  55422. * @returns the serialized object
  55423. */
  55424. SetStateAction.prototype.serialize = function (parent) {
  55425. return _super.prototype._serialize.call(this, {
  55426. name: "SetStateAction",
  55427. properties: [
  55428. BABYLON.Action._GetTargetProperty(this._target),
  55429. { name: "value", value: this.value }
  55430. ]
  55431. }, parent);
  55432. };
  55433. return SetStateAction;
  55434. }(BABYLON.Action));
  55435. BABYLON.SetStateAction = SetStateAction;
  55436. /**
  55437. * This defines an action responsible to set a property of the target
  55438. * to a desired value once triggered.
  55439. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55440. */
  55441. var SetValueAction = /** @class */ (function (_super) {
  55442. __extends(SetValueAction, _super);
  55443. /**
  55444. * Instantiate the action
  55445. * @param triggerOptions defines the trigger options
  55446. * @param target defines the object containing the property
  55447. * @param propertyPath defines the path of the property to set in the target
  55448. * @param value defines the value to set in the property
  55449. * @param condition defines the trigger related conditions
  55450. */
  55451. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  55452. var _this = _super.call(this, triggerOptions, condition) || this;
  55453. _this.propertyPath = propertyPath;
  55454. _this.value = value;
  55455. _this._target = _this._effectiveTarget = target;
  55456. return _this;
  55457. }
  55458. /** @hidden */
  55459. SetValueAction.prototype._prepare = function () {
  55460. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55461. this._property = this._getProperty(this.propertyPath);
  55462. };
  55463. /**
  55464. * Execute the action and set the targetted property to the desired value.
  55465. */
  55466. SetValueAction.prototype.execute = function () {
  55467. this._effectiveTarget[this._property] = this.value;
  55468. if (this._target.markAsDirty) {
  55469. this._target.markAsDirty(this._property);
  55470. }
  55471. };
  55472. /**
  55473. * Serializes the actions and its related information.
  55474. * @param parent defines the object to serialize in
  55475. * @returns the serialized object
  55476. */
  55477. SetValueAction.prototype.serialize = function (parent) {
  55478. return _super.prototype._serialize.call(this, {
  55479. name: "SetValueAction",
  55480. properties: [
  55481. BABYLON.Action._GetTargetProperty(this._target),
  55482. { name: "propertyPath", value: this.propertyPath },
  55483. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55484. ]
  55485. }, parent);
  55486. };
  55487. return SetValueAction;
  55488. }(BABYLON.Action));
  55489. BABYLON.SetValueAction = SetValueAction;
  55490. /**
  55491. * This defines an action responsible to increment the target value
  55492. * to a desired value once triggered.
  55493. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55494. */
  55495. var IncrementValueAction = /** @class */ (function (_super) {
  55496. __extends(IncrementValueAction, _super);
  55497. /**
  55498. * Instantiate the action
  55499. * @param triggerOptions defines the trigger options
  55500. * @param target defines the object containing the property
  55501. * @param propertyPath defines the path of the property to increment in the target
  55502. * @param value defines the value value we should increment the property by
  55503. * @param condition defines the trigger related conditions
  55504. */
  55505. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  55506. var _this = _super.call(this, triggerOptions, condition) || this;
  55507. _this.propertyPath = propertyPath;
  55508. _this.value = value;
  55509. _this._target = _this._effectiveTarget = target;
  55510. return _this;
  55511. }
  55512. /** @hidden */
  55513. IncrementValueAction.prototype._prepare = function () {
  55514. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55515. this._property = this._getProperty(this.propertyPath);
  55516. if (typeof this._effectiveTarget[this._property] !== "number") {
  55517. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  55518. }
  55519. };
  55520. /**
  55521. * Execute the action and increment the target of the value amount.
  55522. */
  55523. IncrementValueAction.prototype.execute = function () {
  55524. this._effectiveTarget[this._property] += this.value;
  55525. if (this._target.markAsDirty) {
  55526. this._target.markAsDirty(this._property);
  55527. }
  55528. };
  55529. /**
  55530. * Serializes the actions and its related information.
  55531. * @param parent defines the object to serialize in
  55532. * @returns the serialized object
  55533. */
  55534. IncrementValueAction.prototype.serialize = function (parent) {
  55535. return _super.prototype._serialize.call(this, {
  55536. name: "IncrementValueAction",
  55537. properties: [
  55538. BABYLON.Action._GetTargetProperty(this._target),
  55539. { name: "propertyPath", value: this.propertyPath },
  55540. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55541. ]
  55542. }, parent);
  55543. };
  55544. return IncrementValueAction;
  55545. }(BABYLON.Action));
  55546. BABYLON.IncrementValueAction = IncrementValueAction;
  55547. /**
  55548. * This defines an action responsible to start an animation once triggered.
  55549. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55550. */
  55551. var PlayAnimationAction = /** @class */ (function (_super) {
  55552. __extends(PlayAnimationAction, _super);
  55553. /**
  55554. * Instantiate the action
  55555. * @param triggerOptions defines the trigger options
  55556. * @param target defines the target animation or animation name
  55557. * @param from defines from where the animation should start (animation frame)
  55558. * @param end defines where the animation should stop (animation frame)
  55559. * @param loop defines if the animation should loop or stop after the first play
  55560. * @param condition defines the trigger related conditions
  55561. */
  55562. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  55563. var _this = _super.call(this, triggerOptions, condition) || this;
  55564. _this.from = from;
  55565. _this.to = to;
  55566. _this.loop = loop;
  55567. _this._target = target;
  55568. return _this;
  55569. }
  55570. /** @hidden */
  55571. PlayAnimationAction.prototype._prepare = function () {
  55572. };
  55573. /**
  55574. * Execute the action and play the animation.
  55575. */
  55576. PlayAnimationAction.prototype.execute = function () {
  55577. var scene = this._actionManager.getScene();
  55578. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  55579. };
  55580. /**
  55581. * Serializes the actions and its related information.
  55582. * @param parent defines the object to serialize in
  55583. * @returns the serialized object
  55584. */
  55585. PlayAnimationAction.prototype.serialize = function (parent) {
  55586. return _super.prototype._serialize.call(this, {
  55587. name: "PlayAnimationAction",
  55588. properties: [
  55589. BABYLON.Action._GetTargetProperty(this._target),
  55590. { name: "from", value: String(this.from) },
  55591. { name: "to", value: String(this.to) },
  55592. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  55593. ]
  55594. }, parent);
  55595. };
  55596. return PlayAnimationAction;
  55597. }(BABYLON.Action));
  55598. BABYLON.PlayAnimationAction = PlayAnimationAction;
  55599. /**
  55600. * This defines an action responsible to stop an animation once triggered.
  55601. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55602. */
  55603. var StopAnimationAction = /** @class */ (function (_super) {
  55604. __extends(StopAnimationAction, _super);
  55605. /**
  55606. * Instantiate the action
  55607. * @param triggerOptions defines the trigger options
  55608. * @param target defines the target animation or animation name
  55609. * @param condition defines the trigger related conditions
  55610. */
  55611. function StopAnimationAction(triggerOptions, target, condition) {
  55612. var _this = _super.call(this, triggerOptions, condition) || this;
  55613. _this._target = target;
  55614. return _this;
  55615. }
  55616. /** @hidden */
  55617. StopAnimationAction.prototype._prepare = function () {
  55618. };
  55619. /**
  55620. * Execute the action and stop the animation.
  55621. */
  55622. StopAnimationAction.prototype.execute = function () {
  55623. var scene = this._actionManager.getScene();
  55624. scene.stopAnimation(this._target);
  55625. };
  55626. /**
  55627. * Serializes the actions and its related information.
  55628. * @param parent defines the object to serialize in
  55629. * @returns the serialized object
  55630. */
  55631. StopAnimationAction.prototype.serialize = function (parent) {
  55632. return _super.prototype._serialize.call(this, {
  55633. name: "StopAnimationAction",
  55634. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  55635. }, parent);
  55636. };
  55637. return StopAnimationAction;
  55638. }(BABYLON.Action));
  55639. BABYLON.StopAnimationAction = StopAnimationAction;
  55640. /**
  55641. * This defines an action responsible that does nothing once triggered.
  55642. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55643. */
  55644. var DoNothingAction = /** @class */ (function (_super) {
  55645. __extends(DoNothingAction, _super);
  55646. /**
  55647. * Instantiate the action
  55648. * @param triggerOptions defines the trigger options
  55649. * @param condition defines the trigger related conditions
  55650. */
  55651. function DoNothingAction(triggerOptions, condition) {
  55652. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  55653. return _super.call(this, triggerOptions, condition) || this;
  55654. }
  55655. /**
  55656. * Execute the action and do nothing.
  55657. */
  55658. DoNothingAction.prototype.execute = function () {
  55659. };
  55660. /**
  55661. * Serializes the actions and its related information.
  55662. * @param parent defines the object to serialize in
  55663. * @returns the serialized object
  55664. */
  55665. DoNothingAction.prototype.serialize = function (parent) {
  55666. return _super.prototype._serialize.call(this, {
  55667. name: "DoNothingAction",
  55668. properties: []
  55669. }, parent);
  55670. };
  55671. return DoNothingAction;
  55672. }(BABYLON.Action));
  55673. BABYLON.DoNothingAction = DoNothingAction;
  55674. /**
  55675. * This defines an action responsible to trigger several actions once triggered.
  55676. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55677. */
  55678. var CombineAction = /** @class */ (function (_super) {
  55679. __extends(CombineAction, _super);
  55680. /**
  55681. * Instantiate the action
  55682. * @param triggerOptions defines the trigger options
  55683. * @param children defines the list of aggregated animations to run
  55684. * @param condition defines the trigger related conditions
  55685. */
  55686. function CombineAction(triggerOptions, children, condition) {
  55687. var _this = _super.call(this, triggerOptions, condition) || this;
  55688. _this.children = children;
  55689. return _this;
  55690. }
  55691. /** @hidden */
  55692. CombineAction.prototype._prepare = function () {
  55693. for (var index = 0; index < this.children.length; index++) {
  55694. this.children[index]._actionManager = this._actionManager;
  55695. this.children[index]._prepare();
  55696. }
  55697. };
  55698. /**
  55699. * Execute the action and executes all the aggregated actions.
  55700. */
  55701. CombineAction.prototype.execute = function (evt) {
  55702. for (var index = 0; index < this.children.length; index++) {
  55703. this.children[index].execute(evt);
  55704. }
  55705. };
  55706. /**
  55707. * Serializes the actions and its related information.
  55708. * @param parent defines the object to serialize in
  55709. * @returns the serialized object
  55710. */
  55711. CombineAction.prototype.serialize = function (parent) {
  55712. var serializationObject = _super.prototype._serialize.call(this, {
  55713. name: "CombineAction",
  55714. properties: [],
  55715. combine: []
  55716. }, parent);
  55717. for (var i = 0; i < this.children.length; i++) {
  55718. serializationObject.combine.push(this.children[i].serialize(null));
  55719. }
  55720. return serializationObject;
  55721. };
  55722. return CombineAction;
  55723. }(BABYLON.Action));
  55724. BABYLON.CombineAction = CombineAction;
  55725. /**
  55726. * This defines an action responsible to run code (external event) once triggered.
  55727. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55728. */
  55729. var ExecuteCodeAction = /** @class */ (function (_super) {
  55730. __extends(ExecuteCodeAction, _super);
  55731. /**
  55732. * Instantiate the action
  55733. * @param triggerOptions defines the trigger options
  55734. * @param func defines the callback function to run
  55735. * @param condition defines the trigger related conditions
  55736. */
  55737. function ExecuteCodeAction(triggerOptions, func, condition) {
  55738. var _this = _super.call(this, triggerOptions, condition) || this;
  55739. _this.func = func;
  55740. return _this;
  55741. }
  55742. /**
  55743. * Execute the action and run the attached code.
  55744. */
  55745. ExecuteCodeAction.prototype.execute = function (evt) {
  55746. this.func(evt);
  55747. };
  55748. return ExecuteCodeAction;
  55749. }(BABYLON.Action));
  55750. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  55751. /**
  55752. * This defines an action responsible to set the parent property of the target once triggered.
  55753. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55754. */
  55755. var SetParentAction = /** @class */ (function (_super) {
  55756. __extends(SetParentAction, _super);
  55757. /**
  55758. * Instantiate the action
  55759. * @param triggerOptions defines the trigger options
  55760. * @param target defines the target containing the parent property
  55761. * @param parent defines from where the animation should start (animation frame)
  55762. * @param condition defines the trigger related conditions
  55763. */
  55764. function SetParentAction(triggerOptions, target, parent, condition) {
  55765. var _this = _super.call(this, triggerOptions, condition) || this;
  55766. _this._target = target;
  55767. _this._parent = parent;
  55768. return _this;
  55769. }
  55770. /** @hidden */
  55771. SetParentAction.prototype._prepare = function () {
  55772. };
  55773. /**
  55774. * Execute the action and set the parent property.
  55775. */
  55776. SetParentAction.prototype.execute = function () {
  55777. if (this._target.parent === this._parent) {
  55778. return;
  55779. }
  55780. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  55781. invertParentWorldMatrix.invert();
  55782. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  55783. this._target.parent = this._parent;
  55784. };
  55785. /**
  55786. * Serializes the actions and its related information.
  55787. * @param parent defines the object to serialize in
  55788. * @returns the serialized object
  55789. */
  55790. SetParentAction.prototype.serialize = function (parent) {
  55791. return _super.prototype._serialize.call(this, {
  55792. name: "SetParentAction",
  55793. properties: [
  55794. BABYLON.Action._GetTargetProperty(this._target),
  55795. BABYLON.Action._GetTargetProperty(this._parent),
  55796. ]
  55797. }, parent);
  55798. };
  55799. return SetParentAction;
  55800. }(BABYLON.Action));
  55801. BABYLON.SetParentAction = SetParentAction;
  55802. })(BABYLON || (BABYLON = {}));
  55803. //# sourceMappingURL=babylon.directActions.js.map
  55804. var BABYLON;
  55805. (function (BABYLON) {
  55806. var SpriteManager = /** @class */ (function () {
  55807. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  55808. if (epsilon === void 0) { epsilon = 0.01; }
  55809. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55810. this.name = name;
  55811. this.sprites = new Array();
  55812. this.renderingGroupId = 0;
  55813. this.layerMask = 0x0FFFFFFF;
  55814. this.fogEnabled = true;
  55815. this.isPickable = false;
  55816. /**
  55817. * An event triggered when the manager is disposed.
  55818. */
  55819. this.onDisposeObservable = new BABYLON.Observable();
  55820. this._vertexBuffers = {};
  55821. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  55822. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  55823. }
  55824. this._capacity = capacity;
  55825. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  55826. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55827. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55828. if (cellSize.width && cellSize.height) {
  55829. this.cellWidth = cellSize.width;
  55830. this.cellHeight = cellSize.height;
  55831. }
  55832. else if (cellSize !== undefined) {
  55833. this.cellWidth = cellSize;
  55834. this.cellHeight = cellSize;
  55835. }
  55836. else {
  55837. return;
  55838. }
  55839. this._epsilon = epsilon;
  55840. this._scene = scene;
  55841. this._scene.spriteManagers.push(this);
  55842. var indices = [];
  55843. var index = 0;
  55844. for (var count = 0; count < capacity; count++) {
  55845. indices.push(index);
  55846. indices.push(index + 1);
  55847. indices.push(index + 2);
  55848. indices.push(index);
  55849. indices.push(index + 2);
  55850. indices.push(index + 3);
  55851. index += 4;
  55852. }
  55853. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  55854. // VBO
  55855. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  55856. this._vertexData = new Float32Array(capacity * 16 * 4);
  55857. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  55858. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  55859. var options = this._buffer.createVertexBuffer("options", 4, 4);
  55860. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  55861. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  55862. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55863. this._vertexBuffers["options"] = options;
  55864. this._vertexBuffers["cellInfo"] = cellInfo;
  55865. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55866. // Effects
  55867. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  55868. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  55869. }
  55870. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  55871. set: function (callback) {
  55872. if (this._onDisposeObserver) {
  55873. this.onDisposeObservable.remove(this._onDisposeObserver);
  55874. }
  55875. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55876. },
  55877. enumerable: true,
  55878. configurable: true
  55879. });
  55880. Object.defineProperty(SpriteManager.prototype, "texture", {
  55881. get: function () {
  55882. return this._spriteTexture;
  55883. },
  55884. set: function (value) {
  55885. this._spriteTexture = value;
  55886. },
  55887. enumerable: true,
  55888. configurable: true
  55889. });
  55890. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  55891. var arrayOffset = index * 16;
  55892. if (offsetX === 0)
  55893. offsetX = this._epsilon;
  55894. else if (offsetX === 1)
  55895. offsetX = 1 - this._epsilon;
  55896. if (offsetY === 0)
  55897. offsetY = this._epsilon;
  55898. else if (offsetY === 1)
  55899. offsetY = 1 - this._epsilon;
  55900. this._vertexData[arrayOffset] = sprite.position.x;
  55901. this._vertexData[arrayOffset + 1] = sprite.position.y;
  55902. this._vertexData[arrayOffset + 2] = sprite.position.z;
  55903. this._vertexData[arrayOffset + 3] = sprite.angle;
  55904. this._vertexData[arrayOffset + 4] = sprite.width;
  55905. this._vertexData[arrayOffset + 5] = sprite.height;
  55906. this._vertexData[arrayOffset + 6] = offsetX;
  55907. this._vertexData[arrayOffset + 7] = offsetY;
  55908. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  55909. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  55910. var offset = (sprite.cellIndex / rowSize) >> 0;
  55911. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  55912. this._vertexData[arrayOffset + 11] = offset;
  55913. // Color
  55914. this._vertexData[arrayOffset + 12] = sprite.color.r;
  55915. this._vertexData[arrayOffset + 13] = sprite.color.g;
  55916. this._vertexData[arrayOffset + 14] = sprite.color.b;
  55917. this._vertexData[arrayOffset + 15] = sprite.color.a;
  55918. };
  55919. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  55920. var count = Math.min(this._capacity, this.sprites.length);
  55921. var min = BABYLON.Vector3.Zero();
  55922. var max = BABYLON.Vector3.Zero();
  55923. var distance = Number.MAX_VALUE;
  55924. var currentSprite = null;
  55925. var cameraSpacePosition = BABYLON.Vector3.Zero();
  55926. var cameraView = camera.getViewMatrix();
  55927. for (var index = 0; index < count; index++) {
  55928. var sprite = this.sprites[index];
  55929. if (!sprite) {
  55930. continue;
  55931. }
  55932. if (predicate) {
  55933. if (!predicate(sprite)) {
  55934. continue;
  55935. }
  55936. }
  55937. else if (!sprite.isPickable) {
  55938. continue;
  55939. }
  55940. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  55941. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  55942. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  55943. if (ray.intersectsBoxMinMax(min, max)) {
  55944. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  55945. if (distance > currentDistance) {
  55946. distance = currentDistance;
  55947. currentSprite = sprite;
  55948. if (fastCheck) {
  55949. break;
  55950. }
  55951. }
  55952. }
  55953. }
  55954. if (currentSprite) {
  55955. var result = new BABYLON.PickingInfo();
  55956. result.hit = true;
  55957. result.pickedSprite = currentSprite;
  55958. result.distance = distance;
  55959. return result;
  55960. }
  55961. return null;
  55962. };
  55963. SpriteManager.prototype.render = function () {
  55964. // Check
  55965. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  55966. return;
  55967. var engine = this._scene.getEngine();
  55968. var baseSize = this._spriteTexture.getBaseSize();
  55969. // Sprites
  55970. var deltaTime = engine.getDeltaTime();
  55971. var max = Math.min(this._capacity, this.sprites.length);
  55972. var rowSize = baseSize.width / this.cellWidth;
  55973. var offset = 0;
  55974. for (var index = 0; index < max; index++) {
  55975. var sprite = this.sprites[index];
  55976. if (!sprite || !sprite.isVisible) {
  55977. continue;
  55978. }
  55979. sprite._animate(deltaTime);
  55980. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  55981. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  55982. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  55983. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  55984. }
  55985. this._buffer.update(this._vertexData);
  55986. // Render
  55987. var effect = this._effectBase;
  55988. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55989. effect = this._effectFog;
  55990. }
  55991. engine.enableEffect(effect);
  55992. var viewMatrix = this._scene.getViewMatrix();
  55993. effect.setTexture("diffuseSampler", this._spriteTexture);
  55994. effect.setMatrix("view", viewMatrix);
  55995. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55996. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  55997. // Fog
  55998. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55999. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  56000. effect.setColor3("vFogColor", this._scene.fogColor);
  56001. }
  56002. // VBOs
  56003. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56004. // Draw order
  56005. engine.setDepthFunctionToLessOrEqual();
  56006. effect.setBool("alphaTest", true);
  56007. engine.setColorWrite(false);
  56008. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56009. engine.setColorWrite(true);
  56010. effect.setBool("alphaTest", false);
  56011. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56012. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56013. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56014. };
  56015. SpriteManager.prototype.dispose = function () {
  56016. if (this._buffer) {
  56017. this._buffer.dispose();
  56018. this._buffer = null;
  56019. }
  56020. if (this._indexBuffer) {
  56021. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56022. this._indexBuffer = null;
  56023. }
  56024. if (this._spriteTexture) {
  56025. this._spriteTexture.dispose();
  56026. this._spriteTexture = null;
  56027. }
  56028. // Remove from scene
  56029. var index = this._scene.spriteManagers.indexOf(this);
  56030. this._scene.spriteManagers.splice(index, 1);
  56031. // Callback
  56032. this.onDisposeObservable.notifyObservers(this);
  56033. this.onDisposeObservable.clear();
  56034. };
  56035. return SpriteManager;
  56036. }());
  56037. BABYLON.SpriteManager = SpriteManager;
  56038. })(BABYLON || (BABYLON = {}));
  56039. //# sourceMappingURL=babylon.spriteManager.js.map
  56040. var BABYLON;
  56041. (function (BABYLON) {
  56042. var Sprite = /** @class */ (function () {
  56043. function Sprite(name, manager) {
  56044. this.name = name;
  56045. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56046. this.width = 1.0;
  56047. this.height = 1.0;
  56048. this.angle = 0;
  56049. this.cellIndex = 0;
  56050. this.invertU = 0;
  56051. this.invertV = 0;
  56052. this.animations = new Array();
  56053. this.isPickable = false;
  56054. this._animationStarted = false;
  56055. this._loopAnimation = false;
  56056. this._fromIndex = 0;
  56057. this._toIndex = 0;
  56058. this._delay = 0;
  56059. this._direction = 1;
  56060. this._time = 0;
  56061. /**
  56062. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  56063. */
  56064. this.isVisible = true;
  56065. this._manager = manager;
  56066. this._manager.sprites.push(this);
  56067. this.position = BABYLON.Vector3.Zero();
  56068. }
  56069. Object.defineProperty(Sprite.prototype, "size", {
  56070. get: function () {
  56071. return this.width;
  56072. },
  56073. set: function (value) {
  56074. this.width = value;
  56075. this.height = value;
  56076. },
  56077. enumerable: true,
  56078. configurable: true
  56079. });
  56080. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  56081. this._fromIndex = from;
  56082. this._toIndex = to;
  56083. this._loopAnimation = loop;
  56084. this._delay = delay;
  56085. this._animationStarted = true;
  56086. this._direction = from < to ? 1 : -1;
  56087. this.cellIndex = from;
  56088. this._time = 0;
  56089. this._onAnimationEnd = onAnimationEnd;
  56090. };
  56091. Sprite.prototype.stopAnimation = function () {
  56092. this._animationStarted = false;
  56093. };
  56094. /** @hidden */
  56095. Sprite.prototype._animate = function (deltaTime) {
  56096. if (!this._animationStarted)
  56097. return;
  56098. this._time += deltaTime;
  56099. if (this._time > this._delay) {
  56100. this._time = this._time % this._delay;
  56101. this.cellIndex += this._direction;
  56102. if (this.cellIndex > this._toIndex) {
  56103. if (this._loopAnimation) {
  56104. this.cellIndex = this._fromIndex;
  56105. }
  56106. else {
  56107. this.cellIndex = this._toIndex;
  56108. this._animationStarted = false;
  56109. if (this._onAnimationEnd) {
  56110. this._onAnimationEnd();
  56111. }
  56112. if (this.disposeWhenFinishedAnimating) {
  56113. this.dispose();
  56114. }
  56115. }
  56116. }
  56117. }
  56118. };
  56119. Sprite.prototype.dispose = function () {
  56120. for (var i = 0; i < this._manager.sprites.length; i++) {
  56121. if (this._manager.sprites[i] == this) {
  56122. this._manager.sprites.splice(i, 1);
  56123. }
  56124. }
  56125. };
  56126. return Sprite;
  56127. }());
  56128. BABYLON.Sprite = Sprite;
  56129. })(BABYLON || (BABYLON = {}));
  56130. //# sourceMappingURL=babylon.sprite.js.map
  56131. var BABYLON;
  56132. (function (BABYLON) {
  56133. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  56134. if (!BABYLON.PickingInfo) {
  56135. return null;
  56136. }
  56137. var pickingInfo = null;
  56138. if (!camera) {
  56139. if (!this.activeCamera) {
  56140. return null;
  56141. }
  56142. camera = this.activeCamera;
  56143. }
  56144. if (this.spriteManagers.length > 0) {
  56145. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  56146. var spriteManager = this.spriteManagers[spriteIndex];
  56147. if (!spriteManager.isPickable) {
  56148. continue;
  56149. }
  56150. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  56151. if (!result || !result.hit)
  56152. continue;
  56153. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  56154. continue;
  56155. pickingInfo = result;
  56156. if (fastCheck) {
  56157. break;
  56158. }
  56159. }
  56160. }
  56161. return pickingInfo || new BABYLON.PickingInfo();
  56162. };
  56163. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  56164. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  56165. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56166. };
  56167. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  56168. if (!this._tempSpritePickingRay) {
  56169. return null;
  56170. }
  56171. if (!camera) {
  56172. if (!this.activeCamera) {
  56173. return null;
  56174. }
  56175. camera = this.activeCamera;
  56176. }
  56177. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  56178. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56179. };
  56180. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  56181. if (this._pointerOverSprite === sprite) {
  56182. return;
  56183. }
  56184. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56185. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56186. }
  56187. this._pointerOverSprite = sprite;
  56188. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56189. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56190. }
  56191. };
  56192. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  56193. return this._pointerOverSprite;
  56194. };
  56195. /**
  56196. * Defines the sprite scene component responsible to manage sprites
  56197. * in a given scene.
  56198. */
  56199. var SpriteSceneComponent = /** @class */ (function () {
  56200. /**
  56201. * Creates a new instance of the component for the given scene
  56202. * @param scene Defines the scene to register the component in
  56203. */
  56204. function SpriteSceneComponent(scene) {
  56205. /**
  56206. * The component name helpfull to identify the component in the list of scene components.
  56207. */
  56208. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  56209. this.scene = scene;
  56210. this.scene.spriteManagers = new Array();
  56211. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  56212. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  56213. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  56214. this._spritePredicate = function (sprite) {
  56215. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  56216. };
  56217. }
  56218. /**
  56219. * Registers the component in a given scene
  56220. */
  56221. SpriteSceneComponent.prototype.register = function () {
  56222. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  56223. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  56224. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  56225. };
  56226. /**
  56227. * Rebuilds the elements related to this component in case of
  56228. * context lost for instance.
  56229. */
  56230. SpriteSceneComponent.prototype.rebuild = function () {
  56231. /** Nothing to do for sprites */
  56232. };
  56233. /**
  56234. * Disposes the component and the associated ressources.
  56235. */
  56236. SpriteSceneComponent.prototype.dispose = function () {
  56237. this.scene.onBeforeSpritesRenderingObservable.clear();
  56238. this.scene.onAfterSpritesRenderingObservable.clear();
  56239. var spriteManagers = this.scene.spriteManagers;
  56240. while (spriteManagers.length) {
  56241. spriteManagers[0].dispose();
  56242. }
  56243. };
  56244. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  56245. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  56246. if (result) {
  56247. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  56248. }
  56249. return result;
  56250. };
  56251. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  56252. var scene = this.scene;
  56253. if (isMeshPicked) {
  56254. scene.setPointerOverSprite(null);
  56255. }
  56256. else {
  56257. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  56258. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56259. scene.setPointerOverSprite(pickResult.pickedSprite);
  56260. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  56261. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  56262. }
  56263. else {
  56264. canvas.style.cursor = scene.hoverCursor;
  56265. }
  56266. }
  56267. else {
  56268. scene.setPointerOverSprite(null);
  56269. }
  56270. }
  56271. return pickResult;
  56272. };
  56273. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56274. var scene = this.scene;
  56275. scene._pickedDownSprite = null;
  56276. if (scene.spriteManagers.length > 0) {
  56277. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56278. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56279. if (pickResult.pickedSprite.actionManager) {
  56280. scene._pickedDownSprite = pickResult.pickedSprite;
  56281. switch (evt.button) {
  56282. case 0:
  56283. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56284. break;
  56285. case 1:
  56286. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56287. break;
  56288. case 2:
  56289. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56290. break;
  56291. }
  56292. if (pickResult.pickedSprite.actionManager) {
  56293. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56294. }
  56295. }
  56296. }
  56297. }
  56298. return pickResult;
  56299. };
  56300. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56301. var scene = this.scene;
  56302. if (scene.spriteManagers.length > 0) {
  56303. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56304. if (spritePickResult) {
  56305. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  56306. if (spritePickResult.pickedSprite.actionManager) {
  56307. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56308. if (spritePickResult.pickedSprite.actionManager) {
  56309. if (!this.scene._isPointerSwiping()) {
  56310. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56311. }
  56312. }
  56313. }
  56314. }
  56315. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  56316. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  56317. }
  56318. }
  56319. }
  56320. return pickResult;
  56321. };
  56322. return SpriteSceneComponent;
  56323. }());
  56324. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  56325. })(BABYLON || (BABYLON = {}));
  56326. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  56327. var BABYLON;
  56328. (function (BABYLON) {
  56329. /**
  56330. * @hidden
  56331. */
  56332. var IntersectionInfo = /** @class */ (function () {
  56333. function IntersectionInfo(bu, bv, distance) {
  56334. this.bu = bu;
  56335. this.bv = bv;
  56336. this.distance = distance;
  56337. this.faceId = 0;
  56338. this.subMeshId = 0;
  56339. }
  56340. return IntersectionInfo;
  56341. }());
  56342. BABYLON.IntersectionInfo = IntersectionInfo;
  56343. /**
  56344. * Information about the result of picking within a scene
  56345. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  56346. */
  56347. var PickingInfo = /** @class */ (function () {
  56348. function PickingInfo() {
  56349. /**
  56350. * If the pick collided with an object
  56351. */
  56352. this.hit = false;
  56353. /**
  56354. * Distance away where the pick collided
  56355. */
  56356. this.distance = 0;
  56357. /**
  56358. * The location of pick collision
  56359. */
  56360. this.pickedPoint = null;
  56361. /**
  56362. * The mesh corresponding the the pick collision
  56363. */
  56364. this.pickedMesh = null;
  56365. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  56366. this.bu = 0;
  56367. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  56368. this.bv = 0;
  56369. /** The id of the face on the mesh that was picked */
  56370. this.faceId = -1;
  56371. /** Id of the the submesh that was picked */
  56372. this.subMeshId = 0;
  56373. /** If a sprite was picked, this will be the sprite the pick collided with */
  56374. this.pickedSprite = null;
  56375. /**
  56376. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  56377. */
  56378. this.originMesh = null;
  56379. /**
  56380. * The ray that was used to perform the picking.
  56381. */
  56382. this.ray = null;
  56383. }
  56384. /**
  56385. * Gets the normal correspodning to the face the pick collided with
  56386. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  56387. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  56388. * @returns The normal correspodning to the face the pick collided with
  56389. */
  56390. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  56391. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  56392. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  56393. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56394. return null;
  56395. }
  56396. var indices = this.pickedMesh.getIndices();
  56397. if (!indices) {
  56398. return null;
  56399. }
  56400. var result;
  56401. if (useVerticesNormals) {
  56402. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56403. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  56404. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  56405. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  56406. normal0 = normal0.scale(this.bu);
  56407. normal1 = normal1.scale(this.bv);
  56408. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  56409. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  56410. }
  56411. else {
  56412. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56413. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  56414. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  56415. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  56416. var p1p2 = vertex1.subtract(vertex2);
  56417. var p3p2 = vertex3.subtract(vertex2);
  56418. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  56419. }
  56420. if (useWorldCoordinates) {
  56421. var wm = this.pickedMesh.getWorldMatrix();
  56422. if (this.pickedMesh.nonUniformScaling) {
  56423. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  56424. wm = BABYLON.Tmp.Matrix[0];
  56425. wm.setTranslationFromFloats(0, 0, 0);
  56426. wm.invert();
  56427. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  56428. wm = BABYLON.Tmp.Matrix[1];
  56429. }
  56430. result = BABYLON.Vector3.TransformNormal(result, wm);
  56431. }
  56432. result.normalize();
  56433. return result;
  56434. };
  56435. /**
  56436. * Gets the texture coordinates of where the pick occured
  56437. * @returns the vector containing the coordnates of the texture
  56438. */
  56439. PickingInfo.prototype.getTextureCoordinates = function () {
  56440. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56441. return null;
  56442. }
  56443. var indices = this.pickedMesh.getIndices();
  56444. if (!indices) {
  56445. return null;
  56446. }
  56447. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56448. if (!uvs) {
  56449. return null;
  56450. }
  56451. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  56452. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  56453. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  56454. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  56455. uv1 = uv1.scale(this.bu);
  56456. uv2 = uv2.scale(this.bv);
  56457. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  56458. };
  56459. return PickingInfo;
  56460. }());
  56461. BABYLON.PickingInfo = PickingInfo;
  56462. })(BABYLON || (BABYLON = {}));
  56463. //# sourceMappingURL=babylon.pickingInfo.js.map
  56464. var BABYLON;
  56465. (function (BABYLON) {
  56466. var Ray = /** @class */ (function () {
  56467. function Ray(origin, direction, length) {
  56468. if (length === void 0) { length = Number.MAX_VALUE; }
  56469. this.origin = origin;
  56470. this.direction = direction;
  56471. this.length = length;
  56472. }
  56473. // Methods
  56474. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  56475. var d = 0.0;
  56476. var maxValue = Number.MAX_VALUE;
  56477. var inv;
  56478. var min;
  56479. var max;
  56480. var temp;
  56481. if (Math.abs(this.direction.x) < 0.0000001) {
  56482. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  56483. return false;
  56484. }
  56485. }
  56486. else {
  56487. inv = 1.0 / this.direction.x;
  56488. min = (minimum.x - this.origin.x) * inv;
  56489. max = (maximum.x - this.origin.x) * inv;
  56490. if (max === -Infinity) {
  56491. max = Infinity;
  56492. }
  56493. if (min > max) {
  56494. temp = min;
  56495. min = max;
  56496. max = temp;
  56497. }
  56498. d = Math.max(min, d);
  56499. maxValue = Math.min(max, maxValue);
  56500. if (d > maxValue) {
  56501. return false;
  56502. }
  56503. }
  56504. if (Math.abs(this.direction.y) < 0.0000001) {
  56505. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  56506. return false;
  56507. }
  56508. }
  56509. else {
  56510. inv = 1.0 / this.direction.y;
  56511. min = (minimum.y - this.origin.y) * inv;
  56512. max = (maximum.y - this.origin.y) * inv;
  56513. if (max === -Infinity) {
  56514. max = Infinity;
  56515. }
  56516. if (min > max) {
  56517. temp = min;
  56518. min = max;
  56519. max = temp;
  56520. }
  56521. d = Math.max(min, d);
  56522. maxValue = Math.min(max, maxValue);
  56523. if (d > maxValue) {
  56524. return false;
  56525. }
  56526. }
  56527. if (Math.abs(this.direction.z) < 0.0000001) {
  56528. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  56529. return false;
  56530. }
  56531. }
  56532. else {
  56533. inv = 1.0 / this.direction.z;
  56534. min = (minimum.z - this.origin.z) * inv;
  56535. max = (maximum.z - this.origin.z) * inv;
  56536. if (max === -Infinity) {
  56537. max = Infinity;
  56538. }
  56539. if (min > max) {
  56540. temp = min;
  56541. min = max;
  56542. max = temp;
  56543. }
  56544. d = Math.max(min, d);
  56545. maxValue = Math.min(max, maxValue);
  56546. if (d > maxValue) {
  56547. return false;
  56548. }
  56549. }
  56550. return true;
  56551. };
  56552. Ray.prototype.intersectsBox = function (box) {
  56553. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  56554. };
  56555. Ray.prototype.intersectsSphere = function (sphere) {
  56556. var x = sphere.center.x - this.origin.x;
  56557. var y = sphere.center.y - this.origin.y;
  56558. var z = sphere.center.z - this.origin.z;
  56559. var pyth = (x * x) + (y * y) + (z * z);
  56560. var rr = sphere.radius * sphere.radius;
  56561. if (pyth <= rr) {
  56562. return true;
  56563. }
  56564. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  56565. if (dot < 0.0) {
  56566. return false;
  56567. }
  56568. var temp = pyth - (dot * dot);
  56569. return temp <= rr;
  56570. };
  56571. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  56572. if (!this._edge1) {
  56573. this._edge1 = BABYLON.Vector3.Zero();
  56574. this._edge2 = BABYLON.Vector3.Zero();
  56575. this._pvec = BABYLON.Vector3.Zero();
  56576. this._tvec = BABYLON.Vector3.Zero();
  56577. this._qvec = BABYLON.Vector3.Zero();
  56578. }
  56579. vertex1.subtractToRef(vertex0, this._edge1);
  56580. vertex2.subtractToRef(vertex0, this._edge2);
  56581. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  56582. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  56583. if (det === 0) {
  56584. return null;
  56585. }
  56586. var invdet = 1 / det;
  56587. this.origin.subtractToRef(vertex0, this._tvec);
  56588. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  56589. if (bu < 0 || bu > 1.0) {
  56590. return null;
  56591. }
  56592. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  56593. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  56594. if (bv < 0 || bu + bv > 1.0) {
  56595. return null;
  56596. }
  56597. //check if the distance is longer than the predefined length.
  56598. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  56599. if (distance > this.length) {
  56600. return null;
  56601. }
  56602. return new BABYLON.IntersectionInfo(bu, bv, distance);
  56603. };
  56604. Ray.prototype.intersectsPlane = function (plane) {
  56605. var distance;
  56606. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  56607. if (Math.abs(result1) < 9.99999997475243E-07) {
  56608. return null;
  56609. }
  56610. else {
  56611. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  56612. distance = (-plane.d - result2) / result1;
  56613. if (distance < 0.0) {
  56614. if (distance < -9.99999997475243E-07) {
  56615. return null;
  56616. }
  56617. else {
  56618. return 0;
  56619. }
  56620. }
  56621. return distance;
  56622. }
  56623. };
  56624. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  56625. var tm = BABYLON.Tmp.Matrix[0];
  56626. mesh.getWorldMatrix().invertToRef(tm);
  56627. if (this._tmpRay) {
  56628. Ray.TransformToRef(this, tm, this._tmpRay);
  56629. }
  56630. else {
  56631. this._tmpRay = Ray.Transform(this, tm);
  56632. }
  56633. return mesh.intersects(this._tmpRay, fastCheck);
  56634. };
  56635. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  56636. if (results) {
  56637. results.length = 0;
  56638. }
  56639. else {
  56640. results = [];
  56641. }
  56642. for (var i = 0; i < meshes.length; i++) {
  56643. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  56644. if (pickInfo.hit) {
  56645. results.push(pickInfo);
  56646. }
  56647. }
  56648. results.sort(this._comparePickingInfo);
  56649. return results;
  56650. };
  56651. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  56652. if (pickingInfoA.distance < pickingInfoB.distance) {
  56653. return -1;
  56654. }
  56655. else if (pickingInfoA.distance > pickingInfoB.distance) {
  56656. return 1;
  56657. }
  56658. else {
  56659. return 0;
  56660. }
  56661. };
  56662. /**
  56663. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  56664. * @param sega the first point of the segment to test the intersection against
  56665. * @param segb the second point of the segment to test the intersection against
  56666. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  56667. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  56668. */
  56669. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  56670. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  56671. var u = segb.subtract(sega);
  56672. var v = rsegb.subtract(this.origin);
  56673. var w = sega.subtract(this.origin);
  56674. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  56675. var b = BABYLON.Vector3.Dot(u, v);
  56676. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  56677. var d = BABYLON.Vector3.Dot(u, w);
  56678. var e = BABYLON.Vector3.Dot(v, w);
  56679. var D = a * c - b * b; // always >= 0
  56680. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  56681. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  56682. // compute the line parameters of the two closest points
  56683. if (D < Ray.smallnum) { // the lines are almost parallel
  56684. sN = 0.0; // force using point P0 on segment S1
  56685. sD = 1.0; // to prevent possible division by 0.0 later
  56686. tN = e;
  56687. tD = c;
  56688. }
  56689. else { // get the closest points on the infinite lines
  56690. sN = (b * e - c * d);
  56691. tN = (a * e - b * d);
  56692. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  56693. sN = 0.0;
  56694. tN = e;
  56695. tD = c;
  56696. }
  56697. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  56698. sN = sD;
  56699. tN = e + b;
  56700. tD = c;
  56701. }
  56702. }
  56703. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  56704. tN = 0.0;
  56705. // recompute sc for this edge
  56706. if (-d < 0.0) {
  56707. sN = 0.0;
  56708. }
  56709. else if (-d > a)
  56710. sN = sD;
  56711. else {
  56712. sN = -d;
  56713. sD = a;
  56714. }
  56715. }
  56716. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  56717. tN = tD;
  56718. // recompute sc for this edge
  56719. if ((-d + b) < 0.0) {
  56720. sN = 0;
  56721. }
  56722. else if ((-d + b) > a) {
  56723. sN = sD;
  56724. }
  56725. else {
  56726. sN = (-d + b);
  56727. sD = a;
  56728. }
  56729. }
  56730. // finally do the division to get sc and tc
  56731. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  56732. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  56733. // get the difference of the two closest points
  56734. var qtc = v.multiplyByFloats(tc, tc, tc);
  56735. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  56736. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  56737. if (isIntersected) {
  56738. return qtc.length();
  56739. }
  56740. return -1;
  56741. };
  56742. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56743. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  56744. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  56745. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  56746. this.direction.normalize();
  56747. return this;
  56748. };
  56749. // Statics
  56750. Ray.Zero = function () {
  56751. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  56752. };
  56753. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56754. var result = Ray.Zero();
  56755. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  56756. };
  56757. /**
  56758. * 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
  56759. * transformed to the given world matrix.
  56760. * @param origin The origin point
  56761. * @param end The end point
  56762. * @param world a matrix to transform the ray to. Default is the identity matrix.
  56763. */
  56764. Ray.CreateNewFromTo = function (origin, end, world) {
  56765. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  56766. var direction = end.subtract(origin);
  56767. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  56768. direction.normalize();
  56769. return Ray.Transform(new Ray(origin, direction, length), world);
  56770. };
  56771. Ray.Transform = function (ray, matrix) {
  56772. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  56773. Ray.TransformToRef(ray, matrix, result);
  56774. return result;
  56775. };
  56776. Ray.TransformToRef = function (ray, matrix, result) {
  56777. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  56778. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  56779. result.length = ray.length;
  56780. var dir = result.direction;
  56781. var len = dir.length();
  56782. if (!(len === 0 || len === 1)) {
  56783. var num = 1.0 / len;
  56784. dir.x *= num;
  56785. dir.y *= num;
  56786. dir.z *= num;
  56787. result.length *= len;
  56788. }
  56789. };
  56790. Ray.smallnum = 0.00000001;
  56791. Ray.rayl = 10e8;
  56792. return Ray;
  56793. }());
  56794. BABYLON.Ray = Ray;
  56795. })(BABYLON || (BABYLON = {}));
  56796. //# sourceMappingURL=babylon.ray.js.map
  56797. var BABYLON;
  56798. (function (BABYLON) {
  56799. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  56800. if (boxMin.x > sphereCenter.x + sphereRadius)
  56801. return false;
  56802. if (sphereCenter.x - sphereRadius > boxMax.x)
  56803. return false;
  56804. if (boxMin.y > sphereCenter.y + sphereRadius)
  56805. return false;
  56806. if (sphereCenter.y - sphereRadius > boxMax.y)
  56807. return false;
  56808. if (boxMin.z > sphereCenter.z + sphereRadius)
  56809. return false;
  56810. if (sphereCenter.z - sphereRadius > boxMax.z)
  56811. return false;
  56812. return true;
  56813. };
  56814. var getLowestRoot = (function () {
  56815. var result = { root: 0, found: false };
  56816. return function (a, b, c, maxR) {
  56817. result.root = 0;
  56818. result.found = false;
  56819. var determinant = b * b - 4.0 * a * c;
  56820. if (determinant < 0)
  56821. return result;
  56822. var sqrtD = Math.sqrt(determinant);
  56823. var r1 = (-b - sqrtD) / (2.0 * a);
  56824. var r2 = (-b + sqrtD) / (2.0 * a);
  56825. if (r1 > r2) {
  56826. var temp = r2;
  56827. r2 = r1;
  56828. r1 = temp;
  56829. }
  56830. if (r1 > 0 && r1 < maxR) {
  56831. result.root = r1;
  56832. result.found = true;
  56833. return result;
  56834. }
  56835. if (r2 > 0 && r2 < maxR) {
  56836. result.root = r2;
  56837. result.found = true;
  56838. return result;
  56839. }
  56840. return result;
  56841. };
  56842. })();
  56843. /** @hidden */
  56844. var Collider = /** @class */ (function () {
  56845. function Collider() {
  56846. this._collisionPoint = BABYLON.Vector3.Zero();
  56847. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  56848. this._tempVector = BABYLON.Vector3.Zero();
  56849. this._tempVector2 = BABYLON.Vector3.Zero();
  56850. this._tempVector3 = BABYLON.Vector3.Zero();
  56851. this._tempVector4 = BABYLON.Vector3.Zero();
  56852. this._edge = BABYLON.Vector3.Zero();
  56853. this._baseToVertex = BABYLON.Vector3.Zero();
  56854. this._destinationPoint = BABYLON.Vector3.Zero();
  56855. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  56856. this._displacementVector = BABYLON.Vector3.Zero();
  56857. /** @hidden */
  56858. this._radius = BABYLON.Vector3.One();
  56859. /** @hidden */
  56860. this._retry = 0;
  56861. /** @hidden */
  56862. this._basePointWorld = BABYLON.Vector3.Zero();
  56863. this._velocityWorld = BABYLON.Vector3.Zero();
  56864. this._normalizedVelocity = BABYLON.Vector3.Zero();
  56865. this._collisionMask = -1;
  56866. }
  56867. Object.defineProperty(Collider.prototype, "collisionMask", {
  56868. get: function () {
  56869. return this._collisionMask;
  56870. },
  56871. set: function (mask) {
  56872. this._collisionMask = !isNaN(mask) ? mask : -1;
  56873. },
  56874. enumerable: true,
  56875. configurable: true
  56876. });
  56877. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  56878. /**
  56879. * Gets the plane normal used to compute the sliding response (in local space)
  56880. */
  56881. get: function () {
  56882. return this._slidePlaneNormal;
  56883. },
  56884. enumerable: true,
  56885. configurable: true
  56886. });
  56887. // Methods
  56888. /** @hidden */
  56889. Collider.prototype._initialize = function (source, dir, e) {
  56890. this._velocity = dir;
  56891. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  56892. this._basePoint = source;
  56893. source.multiplyToRef(this._radius, this._basePointWorld);
  56894. dir.multiplyToRef(this._radius, this._velocityWorld);
  56895. this._velocityWorldLength = this._velocityWorld.length();
  56896. this._epsilon = e;
  56897. this.collisionFound = false;
  56898. };
  56899. /** @hidden */
  56900. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  56901. pa.subtractToRef(point, this._tempVector);
  56902. pb.subtractToRef(point, this._tempVector2);
  56903. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  56904. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56905. if (d < 0)
  56906. return false;
  56907. pc.subtractToRef(point, this._tempVector3);
  56908. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  56909. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56910. if (d < 0)
  56911. return false;
  56912. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  56913. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56914. return d >= 0;
  56915. };
  56916. /** @hidden */
  56917. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  56918. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  56919. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  56920. if (distance > this._velocityWorldLength + max + sphereRadius) {
  56921. return false;
  56922. }
  56923. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  56924. return false;
  56925. return true;
  56926. };
  56927. /** @hidden */
  56928. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  56929. var t0;
  56930. var embeddedInPlane = false;
  56931. //defensive programming, actually not needed.
  56932. if (!trianglePlaneArray) {
  56933. trianglePlaneArray = [];
  56934. }
  56935. if (!trianglePlaneArray[faceIndex]) {
  56936. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  56937. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  56938. }
  56939. var trianglePlane = trianglePlaneArray[faceIndex];
  56940. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  56941. return;
  56942. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  56943. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  56944. if (normalDotVelocity == 0) {
  56945. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  56946. return;
  56947. embeddedInPlane = true;
  56948. t0 = 0;
  56949. }
  56950. else {
  56951. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56952. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56953. if (t0 > t1) {
  56954. var temp = t1;
  56955. t1 = t0;
  56956. t0 = temp;
  56957. }
  56958. if (t0 > 1.0 || t1 < 0.0)
  56959. return;
  56960. if (t0 < 0)
  56961. t0 = 0;
  56962. if (t0 > 1.0)
  56963. t0 = 1.0;
  56964. }
  56965. this._collisionPoint.copyFromFloats(0, 0, 0);
  56966. var found = false;
  56967. var t = 1.0;
  56968. if (!embeddedInPlane) {
  56969. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  56970. this._velocity.scaleToRef(t0, this._tempVector);
  56971. this._planeIntersectionPoint.addInPlace(this._tempVector);
  56972. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  56973. found = true;
  56974. t = t0;
  56975. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  56976. }
  56977. }
  56978. if (!found) {
  56979. var velocitySquaredLength = this._velocity.lengthSquared();
  56980. var a = velocitySquaredLength;
  56981. this._basePoint.subtractToRef(p1, this._tempVector);
  56982. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56983. var c = this._tempVector.lengthSquared() - 1.0;
  56984. var lowestRoot = getLowestRoot(a, b, c, t);
  56985. if (lowestRoot.found) {
  56986. t = lowestRoot.root;
  56987. found = true;
  56988. this._collisionPoint.copyFrom(p1);
  56989. }
  56990. this._basePoint.subtractToRef(p2, this._tempVector);
  56991. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56992. c = this._tempVector.lengthSquared() - 1.0;
  56993. lowestRoot = getLowestRoot(a, b, c, t);
  56994. if (lowestRoot.found) {
  56995. t = lowestRoot.root;
  56996. found = true;
  56997. this._collisionPoint.copyFrom(p2);
  56998. }
  56999. this._basePoint.subtractToRef(p3, this._tempVector);
  57000. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57001. c = this._tempVector.lengthSquared() - 1.0;
  57002. lowestRoot = getLowestRoot(a, b, c, t);
  57003. if (lowestRoot.found) {
  57004. t = lowestRoot.root;
  57005. found = true;
  57006. this._collisionPoint.copyFrom(p3);
  57007. }
  57008. p2.subtractToRef(p1, this._edge);
  57009. p1.subtractToRef(this._basePoint, this._baseToVertex);
  57010. var edgeSquaredLength = this._edge.lengthSquared();
  57011. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57012. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57013. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57014. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57015. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57016. lowestRoot = getLowestRoot(a, b, c, t);
  57017. if (lowestRoot.found) {
  57018. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57019. if (f >= 0.0 && f <= 1.0) {
  57020. t = lowestRoot.root;
  57021. found = true;
  57022. this._edge.scaleInPlace(f);
  57023. p1.addToRef(this._edge, this._collisionPoint);
  57024. }
  57025. }
  57026. p3.subtractToRef(p2, this._edge);
  57027. p2.subtractToRef(this._basePoint, this._baseToVertex);
  57028. edgeSquaredLength = this._edge.lengthSquared();
  57029. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57030. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57031. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57032. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57033. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57034. lowestRoot = getLowestRoot(a, b, c, t);
  57035. if (lowestRoot.found) {
  57036. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57037. if (f >= 0.0 && f <= 1.0) {
  57038. t = lowestRoot.root;
  57039. found = true;
  57040. this._edge.scaleInPlace(f);
  57041. p2.addToRef(this._edge, this._collisionPoint);
  57042. }
  57043. }
  57044. p1.subtractToRef(p3, this._edge);
  57045. p3.subtractToRef(this._basePoint, this._baseToVertex);
  57046. edgeSquaredLength = this._edge.lengthSquared();
  57047. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57048. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57049. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57050. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57051. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57052. lowestRoot = getLowestRoot(a, b, c, t);
  57053. if (lowestRoot.found) {
  57054. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57055. if (f >= 0.0 && f <= 1.0) {
  57056. t = lowestRoot.root;
  57057. found = true;
  57058. this._edge.scaleInPlace(f);
  57059. p3.addToRef(this._edge, this._collisionPoint);
  57060. }
  57061. }
  57062. }
  57063. if (found) {
  57064. var distToCollision = t * this._velocity.length();
  57065. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  57066. if (!this.intersectionPoint) {
  57067. this.intersectionPoint = this._collisionPoint.clone();
  57068. }
  57069. else {
  57070. this.intersectionPoint.copyFrom(this._collisionPoint);
  57071. }
  57072. this._nearestDistance = distToCollision;
  57073. this.collisionFound = true;
  57074. }
  57075. }
  57076. };
  57077. /** @hidden */
  57078. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  57079. for (var i = indexStart; i < indexEnd; i += 3) {
  57080. var p1 = pts[indices[i] - decal];
  57081. var p2 = pts[indices[i + 1] - decal];
  57082. var p3 = pts[indices[i + 2] - decal];
  57083. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  57084. }
  57085. };
  57086. /** @hidden */
  57087. Collider.prototype._getResponse = function (pos, vel) {
  57088. pos.addToRef(vel, this._destinationPoint);
  57089. vel.scaleInPlace((this._nearestDistance / vel.length()));
  57090. this._basePoint.addToRef(vel, pos);
  57091. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  57092. this._slidePlaneNormal.normalize();
  57093. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  57094. pos.addInPlace(this._displacementVector);
  57095. this.intersectionPoint.addInPlace(this._displacementVector);
  57096. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  57097. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  57098. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  57099. };
  57100. return Collider;
  57101. }());
  57102. BABYLON.Collider = Collider;
  57103. })(BABYLON || (BABYLON = {}));
  57104. //# sourceMappingURL=babylon.collider.js.map
  57105. var BABYLON;
  57106. (function (BABYLON) {
  57107. //WebWorker code will be inserted to this variable.
  57108. /** @hidden */
  57109. BABYLON.CollisionWorker = "";
  57110. /** Defines supported task for worker process */
  57111. var WorkerTaskType;
  57112. (function (WorkerTaskType) {
  57113. /** Initialization */
  57114. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  57115. /** Update of geometry */
  57116. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  57117. /** Evaluate collision */
  57118. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  57119. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  57120. /** Defines kind of replies returned by worker */
  57121. var WorkerReplyType;
  57122. (function (WorkerReplyType) {
  57123. /** Success */
  57124. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  57125. /** Unkown error */
  57126. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  57127. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  57128. /** @hidden */
  57129. var CollisionCoordinatorWorker = /** @class */ (function () {
  57130. function CollisionCoordinatorWorker() {
  57131. var _this = this;
  57132. this._scaledPosition = BABYLON.Vector3.Zero();
  57133. this._scaledVelocity = BABYLON.Vector3.Zero();
  57134. this.onMeshUpdated = function (transformNode) {
  57135. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  57136. };
  57137. this.onGeometryUpdated = function (geometry) {
  57138. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  57139. };
  57140. this._afterRender = function () {
  57141. if (!_this._init)
  57142. return;
  57143. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  57144. return;
  57145. }
  57146. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  57147. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  57148. if (_this._runningUpdated > 4) {
  57149. return;
  57150. }
  57151. ++_this._runningUpdated;
  57152. var payload = {
  57153. updatedMeshes: _this._addUpdateMeshesList,
  57154. updatedGeometries: _this._addUpdateGeometriesList,
  57155. removedGeometries: _this._toRemoveGeometryArray,
  57156. removedMeshes: _this._toRemoveMeshesArray
  57157. };
  57158. var message = {
  57159. payload: payload,
  57160. taskType: WorkerTaskType.UPDATE
  57161. };
  57162. var serializable = [];
  57163. for (var id in payload.updatedGeometries) {
  57164. if (payload.updatedGeometries.hasOwnProperty(id)) {
  57165. //prepare transferables
  57166. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  57167. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  57168. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  57169. }
  57170. }
  57171. _this._worker.postMessage(message, serializable);
  57172. _this._addUpdateMeshesList = {};
  57173. _this._addUpdateGeometriesList = {};
  57174. _this._toRemoveGeometryArray = [];
  57175. _this._toRemoveMeshesArray = [];
  57176. };
  57177. this._onMessageFromWorker = function (e) {
  57178. var returnData = e.data;
  57179. if (returnData.error != WorkerReplyType.SUCCESS) {
  57180. //TODO what errors can be returned from the worker?
  57181. BABYLON.Tools.Warn("error returned from worker!");
  57182. return;
  57183. }
  57184. switch (returnData.taskType) {
  57185. case WorkerTaskType.INIT:
  57186. _this._init = true;
  57187. //Update the worked with ALL of the scene's current state
  57188. _this._scene.meshes.forEach(function (mesh) {
  57189. _this.onMeshAdded(mesh);
  57190. });
  57191. _this._scene.getGeometries().forEach(function (geometry) {
  57192. _this.onGeometryAdded(geometry);
  57193. });
  57194. break;
  57195. case WorkerTaskType.UPDATE:
  57196. _this._runningUpdated--;
  57197. break;
  57198. case WorkerTaskType.COLLIDE:
  57199. var returnPayload = returnData.payload;
  57200. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  57201. return;
  57202. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  57203. if (callback) {
  57204. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  57205. if (mesh) {
  57206. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  57207. }
  57208. }
  57209. //cleanup
  57210. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  57211. break;
  57212. }
  57213. };
  57214. this._collisionsCallbackArray = [];
  57215. this._init = false;
  57216. this._runningUpdated = 0;
  57217. this._addUpdateMeshesList = {};
  57218. this._addUpdateGeometriesList = {};
  57219. this._toRemoveGeometryArray = [];
  57220. this._toRemoveMeshesArray = [];
  57221. }
  57222. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57223. if (!this._init)
  57224. return;
  57225. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  57226. return;
  57227. position.divideToRef(collider._radius, this._scaledPosition);
  57228. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57229. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  57230. var payload = {
  57231. collider: {
  57232. position: this._scaledPosition.asArray(),
  57233. velocity: this._scaledVelocity.asArray(),
  57234. radius: collider._radius.asArray()
  57235. },
  57236. collisionId: collisionIndex,
  57237. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  57238. maximumRetry: maximumRetry
  57239. };
  57240. var message = {
  57241. payload: payload,
  57242. taskType: WorkerTaskType.COLLIDE
  57243. };
  57244. this._worker.postMessage(message);
  57245. };
  57246. CollisionCoordinatorWorker.prototype.init = function (scene) {
  57247. this._scene = scene;
  57248. this._scene.registerAfterRender(this._afterRender);
  57249. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  57250. this._worker = new Worker(workerUrl);
  57251. this._worker.onmessage = this._onMessageFromWorker;
  57252. var message = {
  57253. payload: {},
  57254. taskType: WorkerTaskType.INIT
  57255. };
  57256. this._worker.postMessage(message);
  57257. };
  57258. CollisionCoordinatorWorker.prototype.destroy = function () {
  57259. this._scene.unregisterAfterRender(this._afterRender);
  57260. this._worker.terminate();
  57261. };
  57262. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  57263. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  57264. this.onMeshUpdated(mesh);
  57265. };
  57266. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  57267. this._toRemoveMeshesArray.push(mesh.uniqueId);
  57268. };
  57269. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  57270. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  57271. geometry.onGeometryUpdated = this.onGeometryUpdated;
  57272. this.onGeometryUpdated(geometry);
  57273. };
  57274. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  57275. this._toRemoveGeometryArray.push(geometry.id);
  57276. };
  57277. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  57278. var submeshes = [];
  57279. if (mesh.subMeshes) {
  57280. submeshes = mesh.subMeshes.map(function (sm, idx) {
  57281. var boundingInfo = sm.getBoundingInfo();
  57282. return {
  57283. position: idx,
  57284. verticesStart: sm.verticesStart,
  57285. verticesCount: sm.verticesCount,
  57286. indexStart: sm.indexStart,
  57287. indexCount: sm.indexCount,
  57288. hasMaterial: !!sm.getMaterial(),
  57289. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57290. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57291. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57292. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  57293. };
  57294. });
  57295. }
  57296. var geometryId = null;
  57297. if (mesh instanceof BABYLON.Mesh) {
  57298. var geometry = mesh.geometry;
  57299. geometryId = geometry ? geometry.id : null;
  57300. }
  57301. else if (mesh instanceof BABYLON.InstancedMesh) {
  57302. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  57303. geometryId = geometry ? geometry.id : null;
  57304. }
  57305. var boundingInfo = mesh.getBoundingInfo();
  57306. return {
  57307. uniqueId: mesh.uniqueId,
  57308. id: mesh.id,
  57309. name: mesh.name,
  57310. geometryId: geometryId,
  57311. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57312. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57313. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57314. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  57315. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  57316. subMeshes: submeshes,
  57317. checkCollisions: mesh.checkCollisions
  57318. };
  57319. };
  57320. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  57321. return {
  57322. id: geometry.id,
  57323. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  57324. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  57325. indices: new Uint32Array(geometry.getIndices() || []),
  57326. };
  57327. };
  57328. return CollisionCoordinatorWorker;
  57329. }());
  57330. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  57331. /** @hidden */
  57332. var CollisionCoordinatorLegacy = /** @class */ (function () {
  57333. function CollisionCoordinatorLegacy() {
  57334. this._scaledPosition = BABYLON.Vector3.Zero();
  57335. this._scaledVelocity = BABYLON.Vector3.Zero();
  57336. this._finalPosition = BABYLON.Vector3.Zero();
  57337. }
  57338. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57339. position.divideToRef(collider._radius, this._scaledPosition);
  57340. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57341. collider.collidedMesh = null;
  57342. collider._retry = 0;
  57343. collider._initialVelocity = this._scaledVelocity;
  57344. collider._initialPosition = this._scaledPosition;
  57345. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  57346. this._finalPosition.multiplyInPlace(collider._radius);
  57347. //run the callback
  57348. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  57349. };
  57350. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  57351. this._scene = scene;
  57352. };
  57353. CollisionCoordinatorLegacy.prototype.destroy = function () {
  57354. //Legacy need no destruction method.
  57355. };
  57356. //No update in legacy mode
  57357. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  57358. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  57359. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  57360. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  57361. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  57362. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  57363. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  57364. if (excludedMesh === void 0) { excludedMesh = null; }
  57365. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  57366. if (collider._retry >= maximumRetry) {
  57367. finalPosition.copyFrom(position);
  57368. return;
  57369. }
  57370. // Check if this is a mesh else camera or -1
  57371. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  57372. collider._initialize(position, velocity, closeDistance);
  57373. // Check all meshes
  57374. for (var index = 0; index < this._scene.meshes.length; index++) {
  57375. var mesh = this._scene.meshes[index];
  57376. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  57377. mesh._checkCollision(collider);
  57378. }
  57379. }
  57380. if (!collider.collisionFound) {
  57381. position.addToRef(velocity, finalPosition);
  57382. return;
  57383. }
  57384. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  57385. collider._getResponse(position, velocity);
  57386. }
  57387. if (velocity.length() <= closeDistance) {
  57388. finalPosition.copyFrom(position);
  57389. return;
  57390. }
  57391. collider._retry++;
  57392. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  57393. };
  57394. return CollisionCoordinatorLegacy;
  57395. }());
  57396. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  57397. })(BABYLON || (BABYLON = {}));
  57398. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  57399. var BABYLON;
  57400. (function (BABYLON) {
  57401. /**
  57402. * A particle represents one of the element emitted by a particle system.
  57403. * This is mainly define by its coordinates, direction, velocity and age.
  57404. */
  57405. var Particle = /** @class */ (function () {
  57406. /**
  57407. * Creates a new instance Particle
  57408. * @param particleSystem the particle system the particle belongs to
  57409. */
  57410. function Particle(
  57411. /**
  57412. * The particle system the particle belongs to.
  57413. */
  57414. particleSystem) {
  57415. this.particleSystem = particleSystem;
  57416. /**
  57417. * The world position of the particle in the scene.
  57418. */
  57419. this.position = BABYLON.Vector3.Zero();
  57420. /**
  57421. * The world direction of the particle in the scene.
  57422. */
  57423. this.direction = BABYLON.Vector3.Zero();
  57424. /**
  57425. * The color of the particle.
  57426. */
  57427. this.color = new BABYLON.Color4(0, 0, 0, 0);
  57428. /**
  57429. * The color change of the particle per step.
  57430. */
  57431. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  57432. /**
  57433. * Defines how long will the life of the particle be.
  57434. */
  57435. this.lifeTime = 1.0;
  57436. /**
  57437. * The current age of the particle.
  57438. */
  57439. this.age = 0;
  57440. /**
  57441. * The current size of the particle.
  57442. */
  57443. this.size = 0;
  57444. /**
  57445. * The current scale of the particle.
  57446. */
  57447. this.scale = new BABYLON.Vector2(1, 1);
  57448. /**
  57449. * The current angle of the particle.
  57450. */
  57451. this.angle = 0;
  57452. /**
  57453. * Defines how fast is the angle changing.
  57454. */
  57455. this.angularSpeed = 0;
  57456. /**
  57457. * Defines the cell index used by the particle to be rendered from a sprite.
  57458. */
  57459. this.cellIndex = 0;
  57460. /** @hidden */
  57461. this._attachedSubEmitters = null;
  57462. /** @hidden */
  57463. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  57464. /** @hidden */
  57465. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  57466. /** @hidden */
  57467. this._currentSize1 = 0;
  57468. /** @hidden */
  57469. this._currentSize2 = 0;
  57470. /** @hidden */
  57471. this._currentAngularSpeed1 = 0;
  57472. /** @hidden */
  57473. this._currentAngularSpeed2 = 0;
  57474. /** @hidden */
  57475. this._currentVelocity1 = 0;
  57476. /** @hidden */
  57477. this._currentVelocity2 = 0;
  57478. /** @hidden */
  57479. this._currentLimitVelocity1 = 0;
  57480. /** @hidden */
  57481. this._currentLimitVelocity2 = 0;
  57482. /** @hidden */
  57483. this._currentDrag1 = 0;
  57484. /** @hidden */
  57485. this._currentDrag2 = 0;
  57486. this.id = Particle._Count++;
  57487. if (!this.particleSystem.isAnimationSheetEnabled) {
  57488. return;
  57489. }
  57490. this.updateCellInfoFromSystem();
  57491. }
  57492. Particle.prototype.updateCellInfoFromSystem = function () {
  57493. this.cellIndex = this.particleSystem.startSpriteCellID;
  57494. };
  57495. /**
  57496. * Defines how the sprite cell index is updated for the particle
  57497. */
  57498. Particle.prototype.updateCellIndex = function () {
  57499. var offsetAge = this.age;
  57500. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  57501. if (this.particleSystem.spriteRandomStartCell) {
  57502. if (this._randomCellOffset === undefined) {
  57503. this._randomCellOffset = Math.random() * this.lifeTime;
  57504. }
  57505. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  57506. changeSpeed = 1;
  57507. offsetAge = this._randomCellOffset;
  57508. }
  57509. else {
  57510. offsetAge += this._randomCellOffset;
  57511. }
  57512. }
  57513. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  57514. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  57515. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  57516. };
  57517. /** @hidden */
  57518. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  57519. if (subEmitter.particleSystem.emitter.position) {
  57520. var emitterMesh = subEmitter.particleSystem.emitter;
  57521. emitterMesh.position.copyFrom(this.position);
  57522. if (subEmitter.inheritDirection) {
  57523. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  57524. // Look at using Y as forward
  57525. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  57526. }
  57527. }
  57528. else {
  57529. var emitterPosition = subEmitter.particleSystem.emitter;
  57530. emitterPosition.copyFrom(this.position);
  57531. }
  57532. // Set inheritedVelocityOffset to be used when new particles are created
  57533. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  57534. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  57535. };
  57536. /** @hidden */
  57537. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  57538. var _this = this;
  57539. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  57540. this._attachedSubEmitters.forEach(function (subEmitter) {
  57541. _this._inheritParticleInfoToSubEmitter(subEmitter);
  57542. });
  57543. }
  57544. };
  57545. /** @hidden */
  57546. Particle.prototype._reset = function () {
  57547. this.age = 0;
  57548. this._currentColorGradient = null;
  57549. this._currentSizeGradient = null;
  57550. this._currentAngularSpeedGradient = null;
  57551. this._currentVelocityGradient = null;
  57552. this._currentLimitVelocityGradient = null;
  57553. this._currentDragGradient = null;
  57554. this.cellIndex = this.particleSystem.startSpriteCellID;
  57555. this._randomCellOffset = undefined;
  57556. };
  57557. /**
  57558. * Copy the properties of particle to another one.
  57559. * @param other the particle to copy the information to.
  57560. */
  57561. Particle.prototype.copyTo = function (other) {
  57562. other.position.copyFrom(this.position);
  57563. if (this._initialDirection) {
  57564. if (other._initialDirection) {
  57565. other._initialDirection.copyFrom(this._initialDirection);
  57566. }
  57567. else {
  57568. other._initialDirection = this._initialDirection.clone();
  57569. }
  57570. }
  57571. else {
  57572. other._initialDirection = null;
  57573. }
  57574. other.direction.copyFrom(this.direction);
  57575. other.color.copyFrom(this.color);
  57576. other.colorStep.copyFrom(this.colorStep);
  57577. other.lifeTime = this.lifeTime;
  57578. other.age = this.age;
  57579. other._randomCellOffset = this._randomCellOffset;
  57580. other.size = this.size;
  57581. other.scale.copyFrom(this.scale);
  57582. other.angle = this.angle;
  57583. other.angularSpeed = this.angularSpeed;
  57584. other.particleSystem = this.particleSystem;
  57585. other.cellIndex = this.cellIndex;
  57586. other.id = this.id;
  57587. other._attachedSubEmitters = this._attachedSubEmitters;
  57588. if (this._currentColorGradient) {
  57589. other._currentColorGradient = this._currentColorGradient;
  57590. other._currentColor1.copyFrom(this._currentColor1);
  57591. other._currentColor2.copyFrom(this._currentColor2);
  57592. }
  57593. if (this._currentSizeGradient) {
  57594. other._currentSizeGradient = this._currentSizeGradient;
  57595. other._currentSize1 = this._currentSize1;
  57596. other._currentSize2 = this._currentSize2;
  57597. }
  57598. if (this._currentAngularSpeedGradient) {
  57599. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  57600. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  57601. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  57602. }
  57603. if (this._currentVelocityGradient) {
  57604. other._currentVelocityGradient = this._currentVelocityGradient;
  57605. other._currentVelocity1 = this._currentVelocity1;
  57606. other._currentVelocity2 = this._currentVelocity2;
  57607. }
  57608. if (this._currentLimitVelocityGradient) {
  57609. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  57610. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  57611. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  57612. }
  57613. if (this._currentDragGradient) {
  57614. other._currentDragGradient = this._currentDragGradient;
  57615. other._currentDrag1 = this._currentDrag1;
  57616. other._currentDrag2 = this._currentDrag2;
  57617. }
  57618. if (this.particleSystem.isAnimationSheetEnabled) {
  57619. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  57620. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  57621. }
  57622. if (this.particleSystem.useRampGradients) {
  57623. other.remapData.copyFrom(this.remapData);
  57624. }
  57625. if (this._randomNoiseCoordinates1) {
  57626. if (other._randomNoiseCoordinates1) {
  57627. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  57628. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  57629. }
  57630. else {
  57631. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  57632. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  57633. }
  57634. }
  57635. };
  57636. Particle._Count = 0;
  57637. return Particle;
  57638. }());
  57639. BABYLON.Particle = Particle;
  57640. })(BABYLON || (BABYLON = {}));
  57641. //# sourceMappingURL=babylon.particle.js.map
  57642. var BABYLON;
  57643. (function (BABYLON) {
  57644. /**
  57645. * This represents the base class for particle system in Babylon.
  57646. * 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.
  57647. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57648. * @example https://doc.babylonjs.com/babylon101/particles
  57649. */
  57650. var BaseParticleSystem = /** @class */ (function () {
  57651. /**
  57652. * Instantiates a particle system.
  57653. * 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.
  57654. * @param name The name of the particle system
  57655. */
  57656. function BaseParticleSystem(name) {
  57657. /**
  57658. * List of animations used by the particle system.
  57659. */
  57660. this.animations = [];
  57661. /**
  57662. * The rendering group used by the Particle system to chose when to render.
  57663. */
  57664. this.renderingGroupId = 0;
  57665. /**
  57666. * The emitter represents the Mesh or position we are attaching the particle system to.
  57667. */
  57668. this.emitter = null;
  57669. /**
  57670. * The maximum number of particles to emit per frame
  57671. */
  57672. this.emitRate = 10;
  57673. /**
  57674. * If you want to launch only a few particles at once, that can be done, as well.
  57675. */
  57676. this.manualEmitCount = -1;
  57677. /**
  57678. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57679. */
  57680. this.updateSpeed = 0.01;
  57681. /**
  57682. * The amount of time the particle system is running (depends of the overall update speed).
  57683. */
  57684. this.targetStopDuration = 0;
  57685. /**
  57686. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  57687. */
  57688. this.disposeOnStop = false;
  57689. /**
  57690. * Minimum power of emitting particles.
  57691. */
  57692. this.minEmitPower = 1;
  57693. /**
  57694. * Maximum power of emitting particles.
  57695. */
  57696. this.maxEmitPower = 1;
  57697. /**
  57698. * Minimum life time of emitting particles.
  57699. */
  57700. this.minLifeTime = 1;
  57701. /**
  57702. * Maximum life time of emitting particles.
  57703. */
  57704. this.maxLifeTime = 1;
  57705. /**
  57706. * Minimum Size of emitting particles.
  57707. */
  57708. this.minSize = 1;
  57709. /**
  57710. * Maximum Size of emitting particles.
  57711. */
  57712. this.maxSize = 1;
  57713. /**
  57714. * Minimum scale of emitting particles on X axis.
  57715. */
  57716. this.minScaleX = 1;
  57717. /**
  57718. * Maximum scale of emitting particles on X axis.
  57719. */
  57720. this.maxScaleX = 1;
  57721. /**
  57722. * Minimum scale of emitting particles on Y axis.
  57723. */
  57724. this.minScaleY = 1;
  57725. /**
  57726. * Maximum scale of emitting particles on Y axis.
  57727. */
  57728. this.maxScaleY = 1;
  57729. /**
  57730. * Gets or sets the minimal initial rotation in radians.
  57731. */
  57732. this.minInitialRotation = 0;
  57733. /**
  57734. * Gets or sets the maximal initial rotation in radians.
  57735. */
  57736. this.maxInitialRotation = 0;
  57737. /**
  57738. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57739. */
  57740. this.minAngularSpeed = 0;
  57741. /**
  57742. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57743. */
  57744. this.maxAngularSpeed = 0;
  57745. /**
  57746. * The layer mask we are rendering the particles through.
  57747. */
  57748. this.layerMask = 0x0FFFFFFF;
  57749. /**
  57750. * This can help using your own shader to render the particle system.
  57751. * The according effect will be created
  57752. */
  57753. this.customShader = null;
  57754. /**
  57755. * By default particle system starts as soon as they are created. This prevents the
  57756. * automatic start to happen and let you decide when to start emitting particles.
  57757. */
  57758. this.preventAutoStart = false;
  57759. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  57760. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  57761. /**
  57762. * Callback triggered when the particle animation is ending.
  57763. */
  57764. this.onAnimationEnd = null;
  57765. /**
  57766. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57767. */
  57768. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57769. /**
  57770. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57771. * to override the particles.
  57772. */
  57773. this.forceDepthWrite = false;
  57774. /** 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 */
  57775. this.preWarmCycles = 0;
  57776. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57777. this.preWarmStepOffset = 1;
  57778. /**
  57779. * 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)
  57780. */
  57781. this.spriteCellChangeSpeed = 1;
  57782. /**
  57783. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57784. */
  57785. this.startSpriteCellID = 0;
  57786. /**
  57787. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57788. */
  57789. this.endSpriteCellID = 0;
  57790. /**
  57791. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57792. */
  57793. this.spriteCellWidth = 0;
  57794. /**
  57795. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57796. */
  57797. this.spriteCellHeight = 0;
  57798. /**
  57799. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  57800. */
  57801. this.spriteRandomStartCell = false;
  57802. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57803. this.translationPivot = new BABYLON.Vector2(0, 0);
  57804. /**
  57805. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  57806. */
  57807. this.beginAnimationOnStart = false;
  57808. /**
  57809. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  57810. */
  57811. this.beginAnimationFrom = 0;
  57812. /**
  57813. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  57814. */
  57815. this.beginAnimationTo = 60;
  57816. /**
  57817. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  57818. */
  57819. this.beginAnimationLoop = false;
  57820. /**
  57821. * You can use gravity if you want to give an orientation to your particles.
  57822. */
  57823. this.gravity = BABYLON.Vector3.Zero();
  57824. this._colorGradients = null;
  57825. this._sizeGradients = null;
  57826. this._lifeTimeGradients = null;
  57827. this._angularSpeedGradients = null;
  57828. this._velocityGradients = null;
  57829. this._limitVelocityGradients = null;
  57830. this._dragGradients = null;
  57831. this._emitRateGradients = null;
  57832. this._startSizeGradients = null;
  57833. this._rampGradients = null;
  57834. this._colorRemapGradients = null;
  57835. this._alphaRemapGradients = null;
  57836. /**
  57837. * Defines the delay in milliseconds before starting the system (0 by default)
  57838. */
  57839. this.startDelay = 0;
  57840. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  57841. this.limitVelocityDamping = 0.4;
  57842. /**
  57843. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57844. */
  57845. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57846. /**
  57847. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57848. */
  57849. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57850. /**
  57851. * Color the particle will have at the end of its lifetime
  57852. */
  57853. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  57854. /**
  57855. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  57856. */
  57857. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57858. /** @hidden */
  57859. this._isSubEmitter = false;
  57860. /**
  57861. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57862. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  57863. */
  57864. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  57865. this._isBillboardBased = true;
  57866. /**
  57867. * Local cache of defines for image processing.
  57868. */
  57869. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  57870. this.id = name;
  57871. this.name = name;
  57872. }
  57873. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  57874. /**
  57875. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  57876. */
  57877. get: function () {
  57878. return this._isAnimationSheetEnabled;
  57879. },
  57880. set: function (value) {
  57881. if (this._isAnimationSheetEnabled == value) {
  57882. return;
  57883. }
  57884. this._isAnimationSheetEnabled = value;
  57885. this._reset();
  57886. },
  57887. enumerable: true,
  57888. configurable: true
  57889. });
  57890. /**
  57891. * Get hosting scene
  57892. * @returns the scene
  57893. */
  57894. BaseParticleSystem.prototype.getScene = function () {
  57895. return this._scene;
  57896. };
  57897. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  57898. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  57899. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  57900. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  57901. };
  57902. /**
  57903. * Gets the current list of drag gradients.
  57904. * You must use addDragGradient and removeDragGradient to udpate this list
  57905. * @returns the list of drag gradients
  57906. */
  57907. BaseParticleSystem.prototype.getDragGradients = function () {
  57908. return this._dragGradients;
  57909. };
  57910. /**
  57911. * Gets the current list of limit velocity gradients.
  57912. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  57913. * @returns the list of limit velocity gradients
  57914. */
  57915. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  57916. return this._limitVelocityGradients;
  57917. };
  57918. /**
  57919. * Gets the current list of color gradients.
  57920. * You must use addColorGradient and removeColorGradient to udpate this list
  57921. * @returns the list of color gradients
  57922. */
  57923. BaseParticleSystem.prototype.getColorGradients = function () {
  57924. return this._colorGradients;
  57925. };
  57926. /**
  57927. * Gets the current list of size gradients.
  57928. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57929. * @returns the list of size gradients
  57930. */
  57931. BaseParticleSystem.prototype.getSizeGradients = function () {
  57932. return this._sizeGradients;
  57933. };
  57934. /**
  57935. * Gets the current list of color remap gradients.
  57936. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  57937. * @returns the list of color remap gradients
  57938. */
  57939. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  57940. return this._colorRemapGradients;
  57941. };
  57942. /**
  57943. * Gets the current list of alpha remap gradients.
  57944. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  57945. * @returns the list of alpha remap gradients
  57946. */
  57947. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  57948. return this._alphaRemapGradients;
  57949. };
  57950. /**
  57951. * Gets the current list of life time gradients.
  57952. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  57953. * @returns the list of life time gradients
  57954. */
  57955. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  57956. return this._lifeTimeGradients;
  57957. };
  57958. /**
  57959. * Gets the current list of angular speed gradients.
  57960. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57961. * @returns the list of angular speed gradients
  57962. */
  57963. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  57964. return this._angularSpeedGradients;
  57965. };
  57966. /**
  57967. * Gets the current list of velocity gradients.
  57968. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57969. * @returns the list of velocity gradients
  57970. */
  57971. BaseParticleSystem.prototype.getVelocityGradients = function () {
  57972. return this._velocityGradients;
  57973. };
  57974. /**
  57975. * Gets the current list of start size gradients.
  57976. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  57977. * @returns the list of start size gradients
  57978. */
  57979. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  57980. return this._startSizeGradients;
  57981. };
  57982. /**
  57983. * Gets the current list of emit rate gradients.
  57984. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  57985. * @returns the list of emit rate gradients
  57986. */
  57987. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  57988. return this._emitRateGradients;
  57989. };
  57990. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  57991. /**
  57992. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57993. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57994. */
  57995. get: function () {
  57996. if (this.particleEmitterType.direction1) {
  57997. return this.particleEmitterType.direction1;
  57998. }
  57999. return BABYLON.Vector3.Zero();
  58000. },
  58001. set: function (value) {
  58002. if (this.particleEmitterType.direction1) {
  58003. this.particleEmitterType.direction1 = value;
  58004. }
  58005. },
  58006. enumerable: true,
  58007. configurable: true
  58008. });
  58009. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  58010. /**
  58011. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58012. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58013. */
  58014. get: function () {
  58015. if (this.particleEmitterType.direction2) {
  58016. return this.particleEmitterType.direction2;
  58017. }
  58018. return BABYLON.Vector3.Zero();
  58019. },
  58020. set: function (value) {
  58021. if (this.particleEmitterType.direction2) {
  58022. this.particleEmitterType.direction2 = value;
  58023. }
  58024. },
  58025. enumerable: true,
  58026. configurable: true
  58027. });
  58028. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  58029. /**
  58030. * 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.
  58031. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58032. */
  58033. get: function () {
  58034. if (this.particleEmitterType.minEmitBox) {
  58035. return this.particleEmitterType.minEmitBox;
  58036. }
  58037. return BABYLON.Vector3.Zero();
  58038. },
  58039. set: function (value) {
  58040. if (this.particleEmitterType.minEmitBox) {
  58041. this.particleEmitterType.minEmitBox = value;
  58042. }
  58043. },
  58044. enumerable: true,
  58045. configurable: true
  58046. });
  58047. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  58048. /**
  58049. * 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.
  58050. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58051. */
  58052. get: function () {
  58053. if (this.particleEmitterType.maxEmitBox) {
  58054. return this.particleEmitterType.maxEmitBox;
  58055. }
  58056. return BABYLON.Vector3.Zero();
  58057. },
  58058. set: function (value) {
  58059. if (this.particleEmitterType.maxEmitBox) {
  58060. this.particleEmitterType.maxEmitBox = value;
  58061. }
  58062. },
  58063. enumerable: true,
  58064. configurable: true
  58065. });
  58066. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  58067. /**
  58068. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  58069. */
  58070. get: function () {
  58071. return this._isBillboardBased;
  58072. },
  58073. set: function (value) {
  58074. if (this._isBillboardBased === value) {
  58075. return;
  58076. }
  58077. this._isBillboardBased = value;
  58078. this._reset();
  58079. },
  58080. enumerable: true,
  58081. configurable: true
  58082. });
  58083. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  58084. /**
  58085. * Gets the image processing configuration used either in this material.
  58086. */
  58087. get: function () {
  58088. return this._imageProcessingConfiguration;
  58089. },
  58090. /**
  58091. * Sets the Default image processing configuration used either in the this material.
  58092. *
  58093. * If sets to null, the scene one is in use.
  58094. */
  58095. set: function (value) {
  58096. this._attachImageProcessingConfiguration(value);
  58097. },
  58098. enumerable: true,
  58099. configurable: true
  58100. });
  58101. /**
  58102. * Attaches a new image processing configuration to the Standard Material.
  58103. * @param configuration
  58104. */
  58105. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  58106. if (configuration === this._imageProcessingConfiguration) {
  58107. return;
  58108. }
  58109. // Pick the scene configuration if needed.
  58110. if (!configuration) {
  58111. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  58112. }
  58113. else {
  58114. this._imageProcessingConfiguration = configuration;
  58115. }
  58116. };
  58117. /** @hidden */
  58118. BaseParticleSystem.prototype._reset = function () {
  58119. };
  58120. /** @hidden */
  58121. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  58122. if (!gradients) {
  58123. return this;
  58124. }
  58125. var index = 0;
  58126. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  58127. var valueGradient = gradients_1[_i];
  58128. if (valueGradient.gradient === gradient) {
  58129. gradients.splice(index, 1);
  58130. break;
  58131. }
  58132. index++;
  58133. }
  58134. if (texture) {
  58135. texture.dispose();
  58136. }
  58137. return this;
  58138. };
  58139. /**
  58140. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  58141. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58142. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58143. * @returns the emitter
  58144. */
  58145. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  58146. var particleEmitter = new BABYLON.PointParticleEmitter();
  58147. particleEmitter.direction1 = direction1;
  58148. particleEmitter.direction2 = direction2;
  58149. this.particleEmitterType = particleEmitter;
  58150. return particleEmitter;
  58151. };
  58152. /**
  58153. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  58154. * @param radius The radius of the hemisphere to emit from
  58155. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58156. * @returns the emitter
  58157. */
  58158. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  58159. if (radius === void 0) { radius = 1; }
  58160. if (radiusRange === void 0) { radiusRange = 1; }
  58161. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  58162. this.particleEmitterType = particleEmitter;
  58163. return particleEmitter;
  58164. };
  58165. /**
  58166. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  58167. * @param radius The radius of the sphere to emit from
  58168. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58169. * @returns the emitter
  58170. */
  58171. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  58172. if (radius === void 0) { radius = 1; }
  58173. if (radiusRange === void 0) { radiusRange = 1; }
  58174. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  58175. this.particleEmitterType = particleEmitter;
  58176. return particleEmitter;
  58177. };
  58178. /**
  58179. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  58180. * @param radius The radius of the sphere to emit from
  58181. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  58182. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  58183. * @returns the emitter
  58184. */
  58185. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  58186. if (radius === void 0) { radius = 1; }
  58187. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58188. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58189. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  58190. this.particleEmitterType = particleEmitter;
  58191. return particleEmitter;
  58192. };
  58193. /**
  58194. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  58195. * @param radius The radius of the emission cylinder
  58196. * @param height The height of the emission cylinder
  58197. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  58198. * @param directionRandomizer How much to randomize the particle direction [0-1]
  58199. * @returns the emitter
  58200. */
  58201. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  58202. if (radius === void 0) { radius = 1; }
  58203. if (height === void 0) { height = 1; }
  58204. if (radiusRange === void 0) { radiusRange = 1; }
  58205. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58206. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  58207. this.particleEmitterType = particleEmitter;
  58208. return particleEmitter;
  58209. };
  58210. /**
  58211. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  58212. * @param radius The radius of the cylinder to emit from
  58213. * @param height The height of the emission cylinder
  58214. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58215. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  58216. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  58217. * @returns the emitter
  58218. */
  58219. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  58220. if (radius === void 0) { radius = 1; }
  58221. if (height === void 0) { height = 1; }
  58222. if (radiusRange === void 0) { radiusRange = 1; }
  58223. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58224. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58225. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  58226. this.particleEmitterType = particleEmitter;
  58227. return particleEmitter;
  58228. };
  58229. /**
  58230. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  58231. * @param radius The radius of the cone to emit from
  58232. * @param angle The base angle of the cone
  58233. * @returns the emitter
  58234. */
  58235. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  58236. if (radius === void 0) { radius = 1; }
  58237. if (angle === void 0) { angle = Math.PI / 4; }
  58238. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  58239. this.particleEmitterType = particleEmitter;
  58240. return particleEmitter;
  58241. };
  58242. /**
  58243. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  58244. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58245. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58246. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58247. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58248. * @returns the emitter
  58249. */
  58250. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  58251. var particleEmitter = new BABYLON.BoxParticleEmitter();
  58252. this.particleEmitterType = particleEmitter;
  58253. this.direction1 = direction1;
  58254. this.direction2 = direction2;
  58255. this.minEmitBox = minEmitBox;
  58256. this.maxEmitBox = maxEmitBox;
  58257. return particleEmitter;
  58258. };
  58259. /**
  58260. * Source color is added to the destination color without alpha affecting the result
  58261. */
  58262. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  58263. /**
  58264. * Blend current color and particle color using particle’s alpha
  58265. */
  58266. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  58267. /**
  58268. * Add current color and particle color multiplied by particle’s alpha
  58269. */
  58270. BaseParticleSystem.BLENDMODE_ADD = 2;
  58271. /**
  58272. * Multiply current color with particle color
  58273. */
  58274. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  58275. /**
  58276. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  58277. */
  58278. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  58279. return BaseParticleSystem;
  58280. }());
  58281. BABYLON.BaseParticleSystem = BaseParticleSystem;
  58282. })(BABYLON || (BABYLON = {}));
  58283. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  58284. var BABYLON;
  58285. (function (BABYLON) {
  58286. /**
  58287. * This represents a particle system in Babylon.
  58288. * 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.
  58289. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58290. * @example https://doc.babylonjs.com/babylon101/particles
  58291. */
  58292. var ParticleSystem = /** @class */ (function (_super) {
  58293. __extends(ParticleSystem, _super);
  58294. /**
  58295. * Instantiates a particle system.
  58296. * 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.
  58297. * @param name The name of the particle system
  58298. * @param capacity The max number of particles alive at the same time
  58299. * @param scene The scene the particle system belongs to
  58300. * @param customEffect a custom effect used to change the way particles are rendered by default
  58301. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  58302. * @param epsilon Offset used to render the particles
  58303. */
  58304. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  58305. if (customEffect === void 0) { customEffect = null; }
  58306. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58307. if (epsilon === void 0) { epsilon = 0.01; }
  58308. var _this = _super.call(this, name) || this;
  58309. /**
  58310. * @hidden
  58311. */
  58312. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  58313. /**
  58314. * An event triggered when the system is disposed
  58315. */
  58316. _this.onDisposeObservable = new BABYLON.Observable();
  58317. _this._particles = new Array();
  58318. _this._stockParticles = new Array();
  58319. _this._newPartsExcess = 0;
  58320. _this._vertexBuffers = {};
  58321. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  58322. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  58323. _this._scaledDirection = BABYLON.Vector3.Zero();
  58324. _this._scaledGravity = BABYLON.Vector3.Zero();
  58325. _this._currentRenderId = -1;
  58326. _this._useInstancing = false;
  58327. _this._started = false;
  58328. _this._stopped = false;
  58329. _this._actualFrame = 0;
  58330. /** @hidden */
  58331. _this._currentEmitRate1 = 0;
  58332. /** @hidden */
  58333. _this._currentEmitRate2 = 0;
  58334. /** @hidden */
  58335. _this._currentStartSize1 = 0;
  58336. /** @hidden */
  58337. _this._currentStartSize2 = 0;
  58338. _this._rawTextureWidth = 256;
  58339. _this._useRampGradients = false;
  58340. /**
  58341. * @hidden
  58342. * If the particle systems emitter should be disposed when the particle system is disposed
  58343. */
  58344. _this._disposeEmitterOnDispose = false;
  58345. // start of sub system methods
  58346. /**
  58347. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  58348. * Its lifetime will start back at 0.
  58349. */
  58350. _this.recycleParticle = function (particle) {
  58351. // move particle from activeParticle list to stock particles
  58352. var lastParticle = _this._particles.pop();
  58353. if (lastParticle !== particle) {
  58354. lastParticle.copyTo(particle);
  58355. }
  58356. _this._stockParticles.push(lastParticle);
  58357. };
  58358. _this._createParticle = function () {
  58359. var particle;
  58360. if (_this._stockParticles.length !== 0) {
  58361. particle = _this._stockParticles.pop();
  58362. particle._reset();
  58363. }
  58364. else {
  58365. particle = new BABYLON.Particle(_this);
  58366. }
  58367. // Attach emitters
  58368. if (_this._subEmitters && _this._subEmitters.length > 0) {
  58369. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  58370. particle._attachedSubEmitters = [];
  58371. subEmitters.forEach(function (subEmitter) {
  58372. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  58373. var newEmitter = subEmitter.clone();
  58374. particle._attachedSubEmitters.push(newEmitter);
  58375. newEmitter.particleSystem.start();
  58376. }
  58377. });
  58378. }
  58379. return particle;
  58380. };
  58381. _this._emitFromParticle = function (particle) {
  58382. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  58383. return;
  58384. }
  58385. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  58386. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  58387. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  58388. var subSystem = subEmitter.clone();
  58389. particle._inheritParticleInfoToSubEmitter(subSystem);
  58390. subSystem.particleSystem._rootParticleSystem = _this;
  58391. _this.activeSubSystems.push(subSystem.particleSystem);
  58392. subSystem.particleSystem.start();
  58393. }
  58394. });
  58395. };
  58396. _this._capacity = capacity;
  58397. _this._epsilon = epsilon;
  58398. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  58399. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58400. // Setup the default processing configuration to the scene.
  58401. _this._attachImageProcessingConfiguration(null);
  58402. _this._customEffect = customEffect;
  58403. _this._scene.particleSystems.push(_this);
  58404. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  58405. _this._createIndexBuffer();
  58406. _this._createVertexBuffers();
  58407. // Default emitter type
  58408. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  58409. // Update
  58410. _this.updateFunction = function (particles) {
  58411. var noiseTextureSize = null;
  58412. var noiseTextureData = null;
  58413. if (_this.noiseTexture) { // We need to get texture data back to CPU
  58414. noiseTextureSize = _this.noiseTexture.getSize();
  58415. noiseTextureData = (_this.noiseTexture.getContent());
  58416. }
  58417. var _loop_1 = function () {
  58418. particle = particles[index];
  58419. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  58420. var previousAge = particle.age;
  58421. particle.age += scaledUpdateSpeed;
  58422. // Evaluate step to death
  58423. if (particle.age > particle.lifeTime) {
  58424. var diff = particle.age - previousAge;
  58425. var oldDiff = particle.lifeTime - previousAge;
  58426. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  58427. particle.age = particle.lifeTime;
  58428. }
  58429. var ratio = particle.age / particle.lifeTime;
  58430. // Color
  58431. if (_this._colorGradients && _this._colorGradients.length > 0) {
  58432. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  58433. if (currentGradient !== particle._currentColorGradient) {
  58434. particle._currentColor1.copyFrom(particle._currentColor2);
  58435. nextGradient.getColorToRef(particle._currentColor2);
  58436. particle._currentColorGradient = currentGradient;
  58437. }
  58438. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  58439. });
  58440. }
  58441. else {
  58442. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  58443. particle.color.addInPlace(_this._scaledColorStep);
  58444. if (particle.color.a < 0) {
  58445. particle.color.a = 0;
  58446. }
  58447. }
  58448. // Angular speed
  58449. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  58450. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  58451. if (currentGradient !== particle._currentAngularSpeedGradient) {
  58452. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  58453. particle._currentAngularSpeed2 = nextGradient.getFactor();
  58454. particle._currentAngularSpeedGradient = currentGradient;
  58455. }
  58456. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  58457. });
  58458. }
  58459. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  58460. // Direction
  58461. var directionScale = scaledUpdateSpeed;
  58462. /// Velocity
  58463. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  58464. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  58465. if (currentGradient !== particle._currentVelocityGradient) {
  58466. particle._currentVelocity1 = particle._currentVelocity2;
  58467. particle._currentVelocity2 = nextGradient.getFactor();
  58468. particle._currentVelocityGradient = currentGradient;
  58469. }
  58470. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  58471. });
  58472. }
  58473. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  58474. /// Limit velocity
  58475. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  58476. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  58477. if (currentGradient !== particle._currentLimitVelocityGradient) {
  58478. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  58479. particle._currentLimitVelocity2 = nextGradient.getFactor();
  58480. particle._currentLimitVelocityGradient = currentGradient;
  58481. }
  58482. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  58483. var currentVelocity = particle.direction.length();
  58484. if (currentVelocity > limitVelocity) {
  58485. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  58486. }
  58487. });
  58488. }
  58489. /// Drag
  58490. if (_this._dragGradients && _this._dragGradients.length > 0) {
  58491. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  58492. if (currentGradient !== particle._currentDragGradient) {
  58493. particle._currentDrag1 = particle._currentDrag2;
  58494. particle._currentDrag2 = nextGradient.getFactor();
  58495. particle._currentDragGradient = currentGradient;
  58496. }
  58497. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  58498. _this._scaledDirection.scaleInPlace(1.0 - drag);
  58499. });
  58500. }
  58501. particle.position.addInPlace(_this._scaledDirection);
  58502. // Noise
  58503. if (noiseTextureData && noiseTextureSize) {
  58504. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58505. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58506. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58507. var force = BABYLON.Tmp.Vector3[0];
  58508. var scaledForce = BABYLON.Tmp.Vector3[1];
  58509. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  58510. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  58511. particle.direction.addInPlace(scaledForce);
  58512. }
  58513. // Gravity
  58514. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  58515. particle.direction.addInPlace(_this._scaledGravity);
  58516. // Size
  58517. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  58518. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  58519. if (currentGradient !== particle._currentSizeGradient) {
  58520. particle._currentSize1 = particle._currentSize2;
  58521. particle._currentSize2 = nextGradient.getFactor();
  58522. particle._currentSizeGradient = currentGradient;
  58523. }
  58524. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  58525. });
  58526. }
  58527. // Remap data
  58528. if (_this._useRampGradients) {
  58529. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  58530. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  58531. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58532. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  58533. particle.remapData.x = min;
  58534. particle.remapData.y = max - min;
  58535. });
  58536. }
  58537. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  58538. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  58539. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58540. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  58541. particle.remapData.z = min;
  58542. particle.remapData.w = max - min;
  58543. });
  58544. }
  58545. }
  58546. if (_this._isAnimationSheetEnabled) {
  58547. particle.updateCellIndex();
  58548. }
  58549. // Update the position of the attached sub-emitters to match their attached particle
  58550. particle._inheritParticleInfoToSubEmitters();
  58551. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  58552. _this._emitFromParticle(particle);
  58553. if (particle._attachedSubEmitters) {
  58554. particle._attachedSubEmitters.forEach(function (subEmitter) {
  58555. subEmitter.particleSystem.disposeOnStop = true;
  58556. subEmitter.particleSystem.stop();
  58557. });
  58558. particle._attachedSubEmitters = null;
  58559. }
  58560. _this.recycleParticle(particle);
  58561. index--;
  58562. return "continue";
  58563. }
  58564. };
  58565. var particle;
  58566. for (var index = 0; index < particles.length; index++) {
  58567. _loop_1();
  58568. }
  58569. };
  58570. return _this;
  58571. }
  58572. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  58573. /**
  58574. * Sets a callback that will be triggered when the system is disposed
  58575. */
  58576. set: function (callback) {
  58577. if (this._onDisposeObserver) {
  58578. this.onDisposeObservable.remove(this._onDisposeObserver);
  58579. }
  58580. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  58581. },
  58582. enumerable: true,
  58583. configurable: true
  58584. });
  58585. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  58586. /** Gets or sets a boolean indicating that ramp gradients must be used
  58587. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  58588. */
  58589. get: function () {
  58590. return this._useRampGradients;
  58591. },
  58592. set: function (value) {
  58593. if (this._useRampGradients === value) {
  58594. return;
  58595. }
  58596. this._useRampGradients = value;
  58597. this._resetEffect();
  58598. },
  58599. enumerable: true,
  58600. configurable: true
  58601. });
  58602. Object.defineProperty(ParticleSystem.prototype, "particles", {
  58603. //end of Sub-emitter
  58604. /**
  58605. * Gets the current list of active particles
  58606. */
  58607. get: function () {
  58608. return this._particles;
  58609. },
  58610. enumerable: true,
  58611. configurable: true
  58612. });
  58613. /**
  58614. * Returns the string "ParticleSystem"
  58615. * @returns a string containing the class name
  58616. */
  58617. ParticleSystem.prototype.getClassName = function () {
  58618. return "ParticleSystem";
  58619. };
  58620. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  58621. var newGradient = new BABYLON.FactorGradient();
  58622. newGradient.gradient = gradient;
  58623. newGradient.factor1 = factor;
  58624. newGradient.factor2 = factor2;
  58625. factorGradients.push(newGradient);
  58626. factorGradients.sort(function (a, b) {
  58627. if (a.gradient < b.gradient) {
  58628. return -1;
  58629. }
  58630. else if (a.gradient > b.gradient) {
  58631. return 1;
  58632. }
  58633. return 0;
  58634. });
  58635. };
  58636. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  58637. if (!factorGradients) {
  58638. return;
  58639. }
  58640. var index = 0;
  58641. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  58642. var factorGradient = factorGradients_1[_i];
  58643. if (factorGradient.gradient === gradient) {
  58644. factorGradients.splice(index, 1);
  58645. break;
  58646. }
  58647. index++;
  58648. }
  58649. };
  58650. /**
  58651. * Adds a new life time gradient
  58652. * @param gradient defines the gradient to use (between 0 and 1)
  58653. * @param factor defines the life time factor to affect to the specified gradient
  58654. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58655. * @returns the current particle system
  58656. */
  58657. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  58658. if (!this._lifeTimeGradients) {
  58659. this._lifeTimeGradients = [];
  58660. }
  58661. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  58662. return this;
  58663. };
  58664. /**
  58665. * Remove a specific life time gradient
  58666. * @param gradient defines the gradient to remove
  58667. * @returns the current particle system
  58668. */
  58669. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  58670. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  58671. return this;
  58672. };
  58673. /**
  58674. * Adds a new size gradient
  58675. * @param gradient defines the gradient to use (between 0 and 1)
  58676. * @param factor defines the size factor to affect to the specified gradient
  58677. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58678. * @returns the current particle system
  58679. */
  58680. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  58681. if (!this._sizeGradients) {
  58682. this._sizeGradients = [];
  58683. }
  58684. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  58685. return this;
  58686. };
  58687. /**
  58688. * Remove a specific size gradient
  58689. * @param gradient defines the gradient to remove
  58690. * @returns the current particle system
  58691. */
  58692. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  58693. this._removeFactorGradient(this._sizeGradients, gradient);
  58694. return this;
  58695. };
  58696. /**
  58697. * Adds a new color remap gradient
  58698. * @param gradient defines the gradient to use (between 0 and 1)
  58699. * @param min defines the color remap minimal range
  58700. * @param max defines the color remap maximal range
  58701. * @returns the current particle system
  58702. */
  58703. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  58704. if (!this._colorRemapGradients) {
  58705. this._colorRemapGradients = [];
  58706. }
  58707. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  58708. return this;
  58709. };
  58710. /**
  58711. * Remove a specific color remap gradient
  58712. * @param gradient defines the gradient to remove
  58713. * @returns the current particle system
  58714. */
  58715. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  58716. this._removeFactorGradient(this._colorRemapGradients, gradient);
  58717. return this;
  58718. };
  58719. /**
  58720. * Adds a new alpha remap gradient
  58721. * @param gradient defines the gradient to use (between 0 and 1)
  58722. * @param min defines the alpha remap minimal range
  58723. * @param max defines the alpha remap maximal range
  58724. * @returns the current particle system
  58725. */
  58726. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  58727. if (!this._alphaRemapGradients) {
  58728. this._alphaRemapGradients = [];
  58729. }
  58730. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  58731. return this;
  58732. };
  58733. /**
  58734. * Remove a specific alpha remap gradient
  58735. * @param gradient defines the gradient to remove
  58736. * @returns the current particle system
  58737. */
  58738. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  58739. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  58740. return this;
  58741. };
  58742. /**
  58743. * Adds a new angular speed gradient
  58744. * @param gradient defines the gradient to use (between 0 and 1)
  58745. * @param factor defines the angular speed to affect to the specified gradient
  58746. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58747. * @returns the current particle system
  58748. */
  58749. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  58750. if (!this._angularSpeedGradients) {
  58751. this._angularSpeedGradients = [];
  58752. }
  58753. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  58754. return this;
  58755. };
  58756. /**
  58757. * Remove a specific angular speed gradient
  58758. * @param gradient defines the gradient to remove
  58759. * @returns the current particle system
  58760. */
  58761. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  58762. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  58763. return this;
  58764. };
  58765. /**
  58766. * Adds a new velocity gradient
  58767. * @param gradient defines the gradient to use (between 0 and 1)
  58768. * @param factor defines the velocity to affect to the specified gradient
  58769. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58770. * @returns the current particle system
  58771. */
  58772. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  58773. if (!this._velocityGradients) {
  58774. this._velocityGradients = [];
  58775. }
  58776. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  58777. return this;
  58778. };
  58779. /**
  58780. * Remove a specific velocity gradient
  58781. * @param gradient defines the gradient to remove
  58782. * @returns the current particle system
  58783. */
  58784. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  58785. this._removeFactorGradient(this._velocityGradients, gradient);
  58786. return this;
  58787. };
  58788. /**
  58789. * Adds a new limit velocity gradient
  58790. * @param gradient defines the gradient to use (between 0 and 1)
  58791. * @param factor defines the limit velocity value to affect to the specified gradient
  58792. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58793. * @returns the current particle system
  58794. */
  58795. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  58796. if (!this._limitVelocityGradients) {
  58797. this._limitVelocityGradients = [];
  58798. }
  58799. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  58800. return this;
  58801. };
  58802. /**
  58803. * Remove a specific limit velocity gradient
  58804. * @param gradient defines the gradient to remove
  58805. * @returns the current particle system
  58806. */
  58807. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  58808. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  58809. return this;
  58810. };
  58811. /**
  58812. * Adds a new drag gradient
  58813. * @param gradient defines the gradient to use (between 0 and 1)
  58814. * @param factor defines the drag value to affect to the specified gradient
  58815. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58816. * @returns the current particle system
  58817. */
  58818. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  58819. if (!this._dragGradients) {
  58820. this._dragGradients = [];
  58821. }
  58822. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  58823. return this;
  58824. };
  58825. /**
  58826. * Remove a specific drag gradient
  58827. * @param gradient defines the gradient to remove
  58828. * @returns the current particle system
  58829. */
  58830. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  58831. this._removeFactorGradient(this._dragGradients, gradient);
  58832. return this;
  58833. };
  58834. /**
  58835. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  58836. * @param gradient defines the gradient to use (between 0 and 1)
  58837. * @param factor defines the emit rate value to affect to the specified gradient
  58838. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58839. * @returns the current particle system
  58840. */
  58841. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  58842. if (!this._emitRateGradients) {
  58843. this._emitRateGradients = [];
  58844. }
  58845. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  58846. if (!this._currentEmitRateGradient) {
  58847. this._currentEmitRateGradient = this._emitRateGradients[0];
  58848. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  58849. this._currentEmitRate2 = this._currentEmitRate1;
  58850. }
  58851. if (this._emitRateGradients.length === 2) {
  58852. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  58853. }
  58854. return this;
  58855. };
  58856. /**
  58857. * Remove a specific emit rate gradient
  58858. * @param gradient defines the gradient to remove
  58859. * @returns the current particle system
  58860. */
  58861. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  58862. this._removeFactorGradient(this._emitRateGradients, gradient);
  58863. return this;
  58864. };
  58865. /**
  58866. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  58867. * @param gradient defines the gradient to use (between 0 and 1)
  58868. * @param factor defines the start size value to affect to the specified gradient
  58869. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58870. * @returns the current particle system
  58871. */
  58872. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  58873. if (!this._startSizeGradients) {
  58874. this._startSizeGradients = [];
  58875. }
  58876. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  58877. if (!this._currentStartSizeGradient) {
  58878. this._currentStartSizeGradient = this._startSizeGradients[0];
  58879. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  58880. this._currentStartSize2 = this._currentStartSize1;
  58881. }
  58882. if (this._startSizeGradients.length === 2) {
  58883. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  58884. }
  58885. return this;
  58886. };
  58887. /**
  58888. * Remove a specific start size gradient
  58889. * @param gradient defines the gradient to remove
  58890. * @returns the current particle system
  58891. */
  58892. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  58893. this._removeFactorGradient(this._emitRateGradients, gradient);
  58894. return this;
  58895. };
  58896. ParticleSystem.prototype._createRampGradientTexture = function () {
  58897. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  58898. return;
  58899. }
  58900. var data = new Uint8Array(this._rawTextureWidth * 4);
  58901. var tmpColor = BABYLON.Tmp.Color3[0];
  58902. for (var x = 0; x < this._rawTextureWidth; x++) {
  58903. var ratio = x / this._rawTextureWidth;
  58904. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  58905. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  58906. data[x * 4] = tmpColor.r * 255;
  58907. data[x * 4 + 1] = tmpColor.g * 255;
  58908. data[x * 4 + 2] = tmpColor.b * 255;
  58909. data[x * 4 + 3] = 255;
  58910. });
  58911. }
  58912. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58913. };
  58914. /**
  58915. * Gets the current list of ramp gradients.
  58916. * You must use addRampGradient and removeRampGradient to udpate this list
  58917. * @returns the list of ramp gradients
  58918. */
  58919. ParticleSystem.prototype.getRampGradients = function () {
  58920. return this._rampGradients;
  58921. };
  58922. /**
  58923. * Adds a new ramp gradient used to remap particle colors
  58924. * @param gradient defines the gradient to use (between 0 and 1)
  58925. * @param color defines the color to affect to the specified gradient
  58926. * @returns the current particle system
  58927. */
  58928. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  58929. if (!this._rampGradients) {
  58930. this._rampGradients = [];
  58931. }
  58932. var rampGradient = new BABYLON.Color3Gradient();
  58933. rampGradient.gradient = gradient;
  58934. rampGradient.color = color;
  58935. this._rampGradients.push(rampGradient);
  58936. this._rampGradients.sort(function (a, b) {
  58937. if (a.gradient < b.gradient) {
  58938. return -1;
  58939. }
  58940. else if (a.gradient > b.gradient) {
  58941. return 1;
  58942. }
  58943. return 0;
  58944. });
  58945. if (this._rampGradientsTexture) {
  58946. this._rampGradientsTexture.dispose();
  58947. this._rampGradientsTexture = null;
  58948. }
  58949. this._createRampGradientTexture();
  58950. return this;
  58951. };
  58952. /**
  58953. * Remove a specific ramp gradient
  58954. * @param gradient defines the gradient to remove
  58955. * @returns the current particle system
  58956. */
  58957. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  58958. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  58959. this._rampGradientsTexture = null;
  58960. if (this._rampGradients && this._rampGradients.length > 0) {
  58961. this._createRampGradientTexture();
  58962. }
  58963. return this;
  58964. };
  58965. /**
  58966. * Adds a new color gradient
  58967. * @param gradient defines the gradient to use (between 0 and 1)
  58968. * @param color1 defines the color to affect to the specified gradient
  58969. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  58970. * @returns this particle system
  58971. */
  58972. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  58973. if (!this._colorGradients) {
  58974. this._colorGradients = [];
  58975. }
  58976. var colorGradient = new BABYLON.ColorGradient();
  58977. colorGradient.gradient = gradient;
  58978. colorGradient.color1 = color1;
  58979. colorGradient.color2 = color2;
  58980. this._colorGradients.push(colorGradient);
  58981. this._colorGradients.sort(function (a, b) {
  58982. if (a.gradient < b.gradient) {
  58983. return -1;
  58984. }
  58985. else if (a.gradient > b.gradient) {
  58986. return 1;
  58987. }
  58988. return 0;
  58989. });
  58990. return this;
  58991. };
  58992. /**
  58993. * Remove a specific color gradient
  58994. * @param gradient defines the gradient to remove
  58995. * @returns this particle system
  58996. */
  58997. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  58998. if (!this._colorGradients) {
  58999. return this;
  59000. }
  59001. var index = 0;
  59002. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  59003. var colorGradient = _a[_i];
  59004. if (colorGradient.gradient === gradient) {
  59005. this._colorGradients.splice(index, 1);
  59006. break;
  59007. }
  59008. index++;
  59009. }
  59010. return this;
  59011. };
  59012. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  59013. u = Math.abs(u) * 0.5 + 0.5;
  59014. v = Math.abs(v) * 0.5 + 0.5;
  59015. var wrappedU = ((u * width) % width) | 0;
  59016. var wrappedV = ((v * height) % height) | 0;
  59017. var position = (wrappedU + wrappedV * width) * 4;
  59018. return pixels[position] / 255;
  59019. };
  59020. ParticleSystem.prototype._reset = function () {
  59021. this._resetEffect();
  59022. };
  59023. ParticleSystem.prototype._resetEffect = function () {
  59024. if (this._vertexBuffer) {
  59025. this._vertexBuffer.dispose();
  59026. this._vertexBuffer = null;
  59027. }
  59028. if (this._spriteBuffer) {
  59029. this._spriteBuffer.dispose();
  59030. this._spriteBuffer = null;
  59031. }
  59032. this._createVertexBuffers();
  59033. };
  59034. ParticleSystem.prototype._createVertexBuffers = function () {
  59035. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  59036. if (this._isAnimationSheetEnabled) {
  59037. this._vertexBufferSize += 1;
  59038. }
  59039. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59040. this._vertexBufferSize += 3;
  59041. }
  59042. if (this._useRampGradients) {
  59043. this._vertexBufferSize += 4;
  59044. }
  59045. var engine = this._scene.getEngine();
  59046. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  59047. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  59048. var dataOffset = 0;
  59049. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59050. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  59051. dataOffset += 3;
  59052. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59053. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  59054. dataOffset += 4;
  59055. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59056. this._vertexBuffers["angle"] = options;
  59057. dataOffset += 1;
  59058. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59059. this._vertexBuffers["size"] = size;
  59060. dataOffset += 2;
  59061. if (this._isAnimationSheetEnabled) {
  59062. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59063. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  59064. dataOffset += 1;
  59065. }
  59066. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59067. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59068. this._vertexBuffers["direction"] = directionBuffer;
  59069. dataOffset += 3;
  59070. }
  59071. if (this._useRampGradients) {
  59072. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59073. this._vertexBuffers["remapData"] = rampDataBuffer;
  59074. dataOffset += 4;
  59075. }
  59076. var offsets;
  59077. if (this._useInstancing) {
  59078. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  59079. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  59080. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  59081. }
  59082. else {
  59083. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59084. dataOffset += 2;
  59085. }
  59086. this._vertexBuffers["offset"] = offsets;
  59087. };
  59088. ParticleSystem.prototype._createIndexBuffer = function () {
  59089. if (this._useInstancing) {
  59090. return;
  59091. }
  59092. var indices = [];
  59093. var index = 0;
  59094. for (var count = 0; count < this._capacity; count++) {
  59095. indices.push(index);
  59096. indices.push(index + 1);
  59097. indices.push(index + 2);
  59098. indices.push(index);
  59099. indices.push(index + 2);
  59100. indices.push(index + 3);
  59101. index += 4;
  59102. }
  59103. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  59104. };
  59105. /**
  59106. * Gets the maximum number of particles active at the same time.
  59107. * @returns The max number of active particles.
  59108. */
  59109. ParticleSystem.prototype.getCapacity = function () {
  59110. return this._capacity;
  59111. };
  59112. /**
  59113. * Gets whether there are still active particles in the system.
  59114. * @returns True if it is alive, otherwise false.
  59115. */
  59116. ParticleSystem.prototype.isAlive = function () {
  59117. return this._alive;
  59118. };
  59119. /**
  59120. * Gets if the system has been started. (Note: this will still be true after stop is called)
  59121. * @returns True if it has been started, otherwise false.
  59122. */
  59123. ParticleSystem.prototype.isStarted = function () {
  59124. return this._started;
  59125. };
  59126. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  59127. var _this = this;
  59128. this._subEmitters = new Array();
  59129. if (this.subEmitters) {
  59130. this.subEmitters.forEach(function (subEmitter) {
  59131. if (subEmitter instanceof ParticleSystem) {
  59132. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  59133. }
  59134. else if (subEmitter instanceof BABYLON.SubEmitter) {
  59135. _this._subEmitters.push([subEmitter]);
  59136. }
  59137. else if (subEmitter instanceof Array) {
  59138. _this._subEmitters.push(subEmitter);
  59139. }
  59140. });
  59141. }
  59142. };
  59143. /**
  59144. * Starts the particle system and begins to emit
  59145. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  59146. */
  59147. ParticleSystem.prototype.start = function (delay) {
  59148. var _this = this;
  59149. if (delay === void 0) { delay = this.startDelay; }
  59150. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  59151. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  59152. }
  59153. if (delay) {
  59154. setTimeout(function () {
  59155. _this.start(0);
  59156. }, delay);
  59157. return;
  59158. }
  59159. // Convert the subEmitters field to the constant type field _subEmitters
  59160. this._prepareSubEmitterInternalArray();
  59161. this._started = true;
  59162. this._stopped = false;
  59163. this._actualFrame = 0;
  59164. if (this._subEmitters && this._subEmitters.length != 0) {
  59165. this.activeSubSystems = new Array();
  59166. }
  59167. if (this.preWarmCycles) {
  59168. if (this.emitter instanceof BABYLON.AbstractMesh) {
  59169. this.emitter.computeWorldMatrix(true);
  59170. }
  59171. var noiseTextureAsProcedural_1 = this.noiseTexture;
  59172. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  59173. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  59174. setTimeout(function () {
  59175. for (var index = 0; index < _this.preWarmCycles; index++) {
  59176. _this.animate(true);
  59177. noiseTextureAsProcedural_1.render();
  59178. }
  59179. });
  59180. });
  59181. }
  59182. else {
  59183. for (var index = 0; index < this.preWarmCycles; index++) {
  59184. this.animate(true);
  59185. }
  59186. }
  59187. }
  59188. // Animations
  59189. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  59190. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  59191. }
  59192. };
  59193. /**
  59194. * Stops the particle system.
  59195. * @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.
  59196. */
  59197. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  59198. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  59199. this._stopped = true;
  59200. if (stopSubEmitters) {
  59201. this._stopSubEmitters();
  59202. }
  59203. };
  59204. // animation sheet
  59205. /**
  59206. * Remove all active particles
  59207. */
  59208. ParticleSystem.prototype.reset = function () {
  59209. this._stockParticles = [];
  59210. this._particles = [];
  59211. };
  59212. /**
  59213. * @hidden (for internal use only)
  59214. */
  59215. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  59216. var offset = index * this._vertexBufferSize;
  59217. this._vertexData[offset++] = particle.position.x;
  59218. this._vertexData[offset++] = particle.position.y;
  59219. this._vertexData[offset++] = particle.position.z;
  59220. this._vertexData[offset++] = particle.color.r;
  59221. this._vertexData[offset++] = particle.color.g;
  59222. this._vertexData[offset++] = particle.color.b;
  59223. this._vertexData[offset++] = particle.color.a;
  59224. this._vertexData[offset++] = particle.angle;
  59225. this._vertexData[offset++] = particle.scale.x * particle.size;
  59226. this._vertexData[offset++] = particle.scale.y * particle.size;
  59227. if (this._isAnimationSheetEnabled) {
  59228. this._vertexData[offset++] = particle.cellIndex;
  59229. }
  59230. if (!this._isBillboardBased) {
  59231. if (particle._initialDirection) {
  59232. this._vertexData[offset++] = particle._initialDirection.x;
  59233. this._vertexData[offset++] = particle._initialDirection.y;
  59234. this._vertexData[offset++] = particle._initialDirection.z;
  59235. }
  59236. else {
  59237. this._vertexData[offset++] = particle.direction.x;
  59238. this._vertexData[offset++] = particle.direction.y;
  59239. this._vertexData[offset++] = particle.direction.z;
  59240. }
  59241. }
  59242. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59243. this._vertexData[offset++] = particle.direction.x;
  59244. this._vertexData[offset++] = particle.direction.y;
  59245. this._vertexData[offset++] = particle.direction.z;
  59246. }
  59247. if (this._useRampGradients) {
  59248. this._vertexData[offset++] = particle.remapData.x;
  59249. this._vertexData[offset++] = particle.remapData.y;
  59250. this._vertexData[offset++] = particle.remapData.z;
  59251. this._vertexData[offset++] = particle.remapData.w;
  59252. }
  59253. if (!this._useInstancing) {
  59254. if (this._isAnimationSheetEnabled) {
  59255. if (offsetX === 0)
  59256. offsetX = this._epsilon;
  59257. else if (offsetX === 1)
  59258. offsetX = 1 - this._epsilon;
  59259. if (offsetY === 0)
  59260. offsetY = this._epsilon;
  59261. else if (offsetY === 1)
  59262. offsetY = 1 - this._epsilon;
  59263. }
  59264. this._vertexData[offset++] = offsetX;
  59265. this._vertexData[offset++] = offsetY;
  59266. }
  59267. };
  59268. ParticleSystem.prototype._stopSubEmitters = function () {
  59269. if (!this.activeSubSystems) {
  59270. return;
  59271. }
  59272. this.activeSubSystems.forEach(function (subSystem) {
  59273. subSystem.stop(true);
  59274. });
  59275. this.activeSubSystems = new Array();
  59276. };
  59277. ParticleSystem.prototype._removeFromRoot = function () {
  59278. if (!this._rootParticleSystem) {
  59279. return;
  59280. }
  59281. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  59282. if (index !== -1) {
  59283. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  59284. }
  59285. this._rootParticleSystem = null;
  59286. };
  59287. // End of sub system methods
  59288. ParticleSystem.prototype._update = function (newParticles) {
  59289. var _this = this;
  59290. // Update current
  59291. this._alive = this._particles.length > 0;
  59292. if (this.emitter.position) {
  59293. var emitterMesh = this.emitter;
  59294. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  59295. }
  59296. else {
  59297. var emitterPosition = this.emitter;
  59298. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  59299. }
  59300. this.updateFunction(this._particles);
  59301. // Add new ones
  59302. var particle;
  59303. var _loop_2 = function () {
  59304. if (this_1._particles.length === this_1._capacity) {
  59305. return "break";
  59306. }
  59307. particle = this_1._createParticle();
  59308. this_1._particles.push(particle);
  59309. // Emitter
  59310. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  59311. if (this_1.startPositionFunction) {
  59312. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59313. }
  59314. else {
  59315. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59316. }
  59317. if (this_1.startDirectionFunction) {
  59318. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59319. }
  59320. else {
  59321. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59322. }
  59323. if (emitPower === 0) {
  59324. if (!particle._initialDirection) {
  59325. particle._initialDirection = particle.direction.clone();
  59326. }
  59327. else {
  59328. particle._initialDirection.copyFrom(particle.direction);
  59329. }
  59330. }
  59331. else {
  59332. particle._initialDirection = null;
  59333. }
  59334. particle.direction.scaleInPlace(emitPower);
  59335. // Life time
  59336. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  59337. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  59338. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  59339. var factorGradient1 = currentGradient;
  59340. var factorGradient2 = nextGradient;
  59341. var lifeTime1 = factorGradient1.getFactor();
  59342. var lifeTime2 = factorGradient2.getFactor();
  59343. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  59344. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  59345. });
  59346. }
  59347. else {
  59348. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  59349. }
  59350. // Size
  59351. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  59352. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  59353. }
  59354. else {
  59355. particle._currentSizeGradient = this_1._sizeGradients[0];
  59356. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  59357. particle.size = particle._currentSize1;
  59358. if (this_1._sizeGradients.length > 1) {
  59359. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  59360. }
  59361. else {
  59362. particle._currentSize2 = particle._currentSize1;
  59363. }
  59364. }
  59365. // Size and scale
  59366. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  59367. // Adjust scale by start size
  59368. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  59369. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  59370. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  59371. if (currentGradient !== _this._currentStartSizeGradient) {
  59372. _this._currentStartSize1 = _this._currentStartSize2;
  59373. _this._currentStartSize2 = nextGradient.getFactor();
  59374. _this._currentStartSizeGradient = currentGradient;
  59375. }
  59376. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  59377. particle.scale.scaleInPlace(value);
  59378. });
  59379. }
  59380. // Angle
  59381. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  59382. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  59383. }
  59384. else {
  59385. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  59386. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  59387. particle._currentAngularSpeed1 = particle.angularSpeed;
  59388. if (this_1._angularSpeedGradients.length > 1) {
  59389. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  59390. }
  59391. else {
  59392. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  59393. }
  59394. }
  59395. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  59396. // Velocity
  59397. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  59398. particle._currentVelocityGradient = this_1._velocityGradients[0];
  59399. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  59400. if (this_1._velocityGradients.length > 1) {
  59401. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  59402. }
  59403. else {
  59404. particle._currentVelocity2 = particle._currentVelocity1;
  59405. }
  59406. }
  59407. // Limit velocity
  59408. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  59409. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  59410. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  59411. if (this_1._limitVelocityGradients.length > 1) {
  59412. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  59413. }
  59414. else {
  59415. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  59416. }
  59417. }
  59418. // Drag
  59419. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  59420. particle._currentDragGradient = this_1._dragGradients[0];
  59421. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  59422. if (this_1._dragGradients.length > 1) {
  59423. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  59424. }
  59425. else {
  59426. particle._currentDrag2 = particle._currentDrag1;
  59427. }
  59428. }
  59429. // Color
  59430. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  59431. step = BABYLON.Scalar.RandomRange(0, 1.0);
  59432. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  59433. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  59434. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  59435. }
  59436. else {
  59437. particle._currentColorGradient = this_1._colorGradients[0];
  59438. particle._currentColorGradient.getColorToRef(particle.color);
  59439. particle._currentColor1.copyFrom(particle.color);
  59440. if (this_1._colorGradients.length > 1) {
  59441. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  59442. }
  59443. else {
  59444. particle._currentColor2.copyFrom(particle.color);
  59445. }
  59446. }
  59447. // Sheet
  59448. if (this_1._isAnimationSheetEnabled) {
  59449. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  59450. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  59451. }
  59452. // Inherited Velocity
  59453. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  59454. // Ramp
  59455. if (this_1._useRampGradients) {
  59456. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  59457. }
  59458. // Noise texture coordinates
  59459. if (this_1.noiseTexture) {
  59460. if (particle._randomNoiseCoordinates1) {
  59461. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  59462. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  59463. }
  59464. else {
  59465. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  59466. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  59467. }
  59468. }
  59469. // Update the position of the attached sub-emitters to match their attached particle
  59470. particle._inheritParticleInfoToSubEmitters();
  59471. };
  59472. var this_1 = this, step;
  59473. for (var index = 0; index < newParticles; index++) {
  59474. var state_1 = _loop_2();
  59475. if (state_1 === "break")
  59476. break;
  59477. }
  59478. };
  59479. /** @hidden */
  59480. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  59481. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59482. if (isBillboardBased === void 0) { isBillboardBased = false; }
  59483. if (useRampGradients === void 0) { useRampGradients = false; }
  59484. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  59485. if (isAnimationSheetEnabled) {
  59486. attributeNamesOrOptions.push("cellIndex");
  59487. }
  59488. if (!isBillboardBased) {
  59489. attributeNamesOrOptions.push("direction");
  59490. }
  59491. if (useRampGradients) {
  59492. attributeNamesOrOptions.push("remapData");
  59493. }
  59494. return attributeNamesOrOptions;
  59495. };
  59496. /** @hidden */
  59497. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  59498. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59499. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  59500. if (isAnimationSheetEnabled) {
  59501. effectCreationOption.push("particlesInfos");
  59502. }
  59503. return effectCreationOption;
  59504. };
  59505. /** @hidden */
  59506. ParticleSystem.prototype._getEffect = function (blendMode) {
  59507. if (this._customEffect) {
  59508. return this._customEffect;
  59509. }
  59510. ;
  59511. var defines = [];
  59512. if (this._scene.clipPlane) {
  59513. defines.push("#define CLIPPLANE");
  59514. }
  59515. if (this._scene.clipPlane2) {
  59516. defines.push("#define CLIPPLANE2");
  59517. }
  59518. if (this._scene.clipPlane3) {
  59519. defines.push("#define CLIPPLANE3");
  59520. }
  59521. if (this._scene.clipPlane4) {
  59522. defines.push("#define CLIPPLANE4");
  59523. }
  59524. if (this._isAnimationSheetEnabled) {
  59525. defines.push("#define ANIMATESHEET");
  59526. }
  59527. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  59528. defines.push("#define BLENDMULTIPLYMODE");
  59529. }
  59530. if (this._useRampGradients) {
  59531. defines.push("#define RAMPGRADIENT");
  59532. }
  59533. if (this._isBillboardBased) {
  59534. defines.push("#define BILLBOARD");
  59535. switch (this.billboardMode) {
  59536. case ParticleSystem.BILLBOARDMODE_Y:
  59537. defines.push("#define BILLBOARDY");
  59538. break;
  59539. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  59540. defines.push("#define BILLBOARDSTRETCHED");
  59541. break;
  59542. case ParticleSystem.BILLBOARDMODE_ALL:
  59543. default:
  59544. break;
  59545. }
  59546. }
  59547. if (this._imageProcessingConfiguration) {
  59548. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  59549. defines.push(this._imageProcessingConfigurationDefines.toString());
  59550. }
  59551. // Effect
  59552. var join = defines.join("\n");
  59553. if (this._cachedDefines !== join) {
  59554. this._cachedDefines = join;
  59555. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  59556. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  59557. var samplers = ["diffuseSampler", "rampSampler"];
  59558. if (BABYLON.ImageProcessingConfiguration) {
  59559. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  59560. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  59561. }
  59562. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  59563. }
  59564. return this._effect;
  59565. };
  59566. /**
  59567. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  59568. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  59569. */
  59570. ParticleSystem.prototype.animate = function (preWarmOnly) {
  59571. var _this = this;
  59572. if (preWarmOnly === void 0) { preWarmOnly = false; }
  59573. if (!this._started)
  59574. return;
  59575. if (!preWarmOnly) {
  59576. // Check
  59577. if (!this.isReady())
  59578. return;
  59579. if (this._currentRenderId === this._scene.getRenderId()) {
  59580. return;
  59581. }
  59582. this._currentRenderId = this._scene.getRenderId();
  59583. }
  59584. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  59585. // Determine the number of particles we need to create
  59586. var newParticles;
  59587. if (this.manualEmitCount > -1) {
  59588. newParticles = this.manualEmitCount;
  59589. this._newPartsExcess = 0;
  59590. this.manualEmitCount = 0;
  59591. }
  59592. else {
  59593. var rate_1 = this.emitRate;
  59594. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  59595. var ratio = this._actualFrame / this.targetStopDuration;
  59596. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  59597. if (currentGradient !== _this._currentEmitRateGradient) {
  59598. _this._currentEmitRate1 = _this._currentEmitRate2;
  59599. _this._currentEmitRate2 = nextGradient.getFactor();
  59600. _this._currentEmitRateGradient = currentGradient;
  59601. }
  59602. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  59603. });
  59604. }
  59605. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  59606. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  59607. }
  59608. if (this._newPartsExcess > 1.0) {
  59609. newParticles += this._newPartsExcess >> 0;
  59610. this._newPartsExcess -= this._newPartsExcess >> 0;
  59611. }
  59612. this._alive = false;
  59613. if (!this._stopped) {
  59614. this._actualFrame += this._scaledUpdateSpeed;
  59615. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  59616. this.stop();
  59617. }
  59618. else {
  59619. newParticles = 0;
  59620. }
  59621. this._update(newParticles);
  59622. // Stopped?
  59623. if (this._stopped) {
  59624. if (!this._alive) {
  59625. this._started = false;
  59626. if (this.onAnimationEnd) {
  59627. this.onAnimationEnd();
  59628. }
  59629. if (this.disposeOnStop) {
  59630. this._scene._toBeDisposed.push(this);
  59631. }
  59632. }
  59633. }
  59634. if (!preWarmOnly) {
  59635. // Update VBO
  59636. var offset = 0;
  59637. for (var index = 0; index < this._particles.length; index++) {
  59638. var particle = this._particles[index];
  59639. this._appendParticleVertices(offset, particle);
  59640. offset += this._useInstancing ? 1 : 4;
  59641. }
  59642. if (this._vertexBuffer) {
  59643. this._vertexBuffer.update(this._vertexData);
  59644. }
  59645. }
  59646. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  59647. this.stop();
  59648. }
  59649. };
  59650. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  59651. this._appendParticleVertex(offset++, particle, 0, 0);
  59652. if (!this._useInstancing) {
  59653. this._appendParticleVertex(offset++, particle, 1, 0);
  59654. this._appendParticleVertex(offset++, particle, 1, 1);
  59655. this._appendParticleVertex(offset++, particle, 0, 1);
  59656. }
  59657. };
  59658. /**
  59659. * Rebuilds the particle system.
  59660. */
  59661. ParticleSystem.prototype.rebuild = function () {
  59662. this._createIndexBuffer();
  59663. if (this._vertexBuffer) {
  59664. this._vertexBuffer._rebuild();
  59665. }
  59666. };
  59667. /**
  59668. * Is this system ready to be used/rendered
  59669. * @return true if the system is ready
  59670. */
  59671. ParticleSystem.prototype.isReady = function () {
  59672. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59673. return false;
  59674. }
  59675. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59676. if (!this._getEffect(this.blendMode).isReady()) {
  59677. return false;
  59678. }
  59679. }
  59680. else {
  59681. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  59682. return false;
  59683. }
  59684. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  59685. return false;
  59686. }
  59687. }
  59688. return true;
  59689. };
  59690. ParticleSystem.prototype._render = function (blendMode) {
  59691. var effect = this._getEffect(blendMode);
  59692. var engine = this._scene.getEngine();
  59693. // Render
  59694. engine.enableEffect(effect);
  59695. var viewMatrix = this._scene.getViewMatrix();
  59696. effect.setTexture("diffuseSampler", this.particleTexture);
  59697. effect.setMatrix("view", viewMatrix);
  59698. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  59699. if (this._isAnimationSheetEnabled && this.particleTexture) {
  59700. var baseSize = this.particleTexture.getBaseSize();
  59701. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  59702. }
  59703. effect.setVector2("translationPivot", this.translationPivot);
  59704. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  59705. if (this._isBillboardBased) {
  59706. var camera = this._scene.activeCamera;
  59707. effect.setVector3("eyePosition", camera.globalPosition);
  59708. }
  59709. if (this._rampGradientsTexture) {
  59710. effect.setTexture("rampSampler", this._rampGradientsTexture);
  59711. }
  59712. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  59713. var invView = viewMatrix.clone();
  59714. invView.invert();
  59715. effect.setMatrix("invView", invView);
  59716. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  59717. }
  59718. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  59719. // image processing
  59720. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  59721. this._imageProcessingConfiguration.bind(effect);
  59722. }
  59723. // Draw order
  59724. switch (blendMode) {
  59725. case ParticleSystem.BLENDMODE_ADD:
  59726. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  59727. break;
  59728. case ParticleSystem.BLENDMODE_ONEONE:
  59729. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  59730. break;
  59731. case ParticleSystem.BLENDMODE_STANDARD:
  59732. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59733. break;
  59734. case ParticleSystem.BLENDMODE_MULTIPLY:
  59735. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  59736. break;
  59737. }
  59738. if (this._useInstancing) {
  59739. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  59740. }
  59741. else {
  59742. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  59743. }
  59744. return this._particles.length;
  59745. };
  59746. /**
  59747. * Renders the particle system in its current state.
  59748. * @returns the current number of particles
  59749. */
  59750. ParticleSystem.prototype.render = function () {
  59751. // Check
  59752. if (!this.isReady() || !this._particles.length) {
  59753. return 0;
  59754. }
  59755. var engine = this._scene.getEngine();
  59756. engine.setState(false);
  59757. if (this.forceDepthWrite) {
  59758. engine.setDepthWrite(true);
  59759. }
  59760. var outparticles = 0;
  59761. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59762. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  59763. }
  59764. outparticles = this._render(this.blendMode);
  59765. engine.unbindInstanceAttributes();
  59766. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59767. return outparticles;
  59768. };
  59769. /**
  59770. * Disposes the particle system and free the associated resources
  59771. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  59772. */
  59773. ParticleSystem.prototype.dispose = function (disposeTexture) {
  59774. if (disposeTexture === void 0) { disposeTexture = true; }
  59775. if (this._vertexBuffer) {
  59776. this._vertexBuffer.dispose();
  59777. this._vertexBuffer = null;
  59778. }
  59779. if (this._spriteBuffer) {
  59780. this._spriteBuffer.dispose();
  59781. this._spriteBuffer = null;
  59782. }
  59783. if (this._indexBuffer) {
  59784. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59785. this._indexBuffer = null;
  59786. }
  59787. if (disposeTexture && this.particleTexture) {
  59788. this.particleTexture.dispose();
  59789. this.particleTexture = null;
  59790. }
  59791. if (disposeTexture && this.noiseTexture) {
  59792. this.noiseTexture.dispose();
  59793. this.noiseTexture = null;
  59794. }
  59795. if (this._rampGradientsTexture) {
  59796. this._rampGradientsTexture.dispose();
  59797. this._rampGradientsTexture = null;
  59798. }
  59799. this._removeFromRoot();
  59800. if (this._subEmitters && this._subEmitters.length) {
  59801. for (var index = 0; index < this._subEmitters.length; index++) {
  59802. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  59803. var subEmitter = _a[_i];
  59804. subEmitter.dispose();
  59805. }
  59806. }
  59807. this._subEmitters = [];
  59808. this.subEmitters = [];
  59809. }
  59810. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  59811. this.emitter.dispose(true);
  59812. }
  59813. // Remove from scene
  59814. var index = this._scene.particleSystems.indexOf(this);
  59815. if (index > -1) {
  59816. this._scene.particleSystems.splice(index, 1);
  59817. }
  59818. this._scene._activeParticleSystems.dispose();
  59819. // Callback
  59820. this.onDisposeObservable.notifyObservers(this);
  59821. this.onDisposeObservable.clear();
  59822. this.reset();
  59823. };
  59824. // Clone
  59825. /**
  59826. * Clones the particle system.
  59827. * @param name The name of the cloned object
  59828. * @param newEmitter The new emitter to use
  59829. * @returns the cloned particle system
  59830. */
  59831. ParticleSystem.prototype.clone = function (name, newEmitter) {
  59832. var custom = null;
  59833. var program = null;
  59834. if (this.customShader != null) {
  59835. program = this.customShader;
  59836. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59837. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59838. }
  59839. else if (this._customEffect) {
  59840. custom = this._customEffect;
  59841. }
  59842. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  59843. result.customShader = program;
  59844. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  59845. if (newEmitter === undefined) {
  59846. newEmitter = this.emitter;
  59847. }
  59848. result.noiseTexture = this.noiseTexture;
  59849. result.emitter = newEmitter;
  59850. if (this.particleTexture) {
  59851. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  59852. }
  59853. // Clone gradients
  59854. if (this._colorGradients) {
  59855. this._colorGradients.forEach(function (v) {
  59856. result.addColorGradient(v.gradient, v.color1, v.color2);
  59857. });
  59858. }
  59859. if (this._dragGradients) {
  59860. this._dragGradients.forEach(function (v) {
  59861. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  59862. });
  59863. }
  59864. if (this._angularSpeedGradients) {
  59865. this._angularSpeedGradients.forEach(function (v) {
  59866. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  59867. });
  59868. }
  59869. if (this._emitRateGradients) {
  59870. this._emitRateGradients.forEach(function (v) {
  59871. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  59872. });
  59873. }
  59874. if (this._lifeTimeGradients) {
  59875. this._lifeTimeGradients.forEach(function (v) {
  59876. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  59877. });
  59878. }
  59879. if (this._limitVelocityGradients) {
  59880. this._limitVelocityGradients.forEach(function (v) {
  59881. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  59882. });
  59883. }
  59884. if (this._sizeGradients) {
  59885. this._sizeGradients.forEach(function (v) {
  59886. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  59887. });
  59888. }
  59889. if (this._startSizeGradients) {
  59890. this._startSizeGradients.forEach(function (v) {
  59891. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  59892. });
  59893. }
  59894. if (this._velocityGradients) {
  59895. this._velocityGradients.forEach(function (v) {
  59896. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  59897. });
  59898. }
  59899. if (this._rampGradients) {
  59900. this._rampGradients.forEach(function (v) {
  59901. result.addRampGradient(v.gradient, v.color);
  59902. });
  59903. }
  59904. if (this._colorRemapGradients) {
  59905. this._colorRemapGradients.forEach(function (v) {
  59906. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  59907. });
  59908. }
  59909. if (this._alphaRemapGradients) {
  59910. this._alphaRemapGradients.forEach(function (v) {
  59911. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  59912. });
  59913. }
  59914. if (!this.preventAutoStart) {
  59915. result.start();
  59916. }
  59917. return result;
  59918. };
  59919. /**
  59920. * Serializes the particle system to a JSON object.
  59921. * @returns the JSON object
  59922. */
  59923. ParticleSystem.prototype.serialize = function () {
  59924. var serializationObject = {};
  59925. ParticleSystem._Serialize(serializationObject, this);
  59926. serializationObject.textureMask = this.textureMask.asArray();
  59927. serializationObject.customShader = this.customShader;
  59928. serializationObject.preventAutoStart = this.preventAutoStart;
  59929. // SubEmitters
  59930. if (this.subEmitters) {
  59931. serializationObject.subEmitters = [];
  59932. if (!this._subEmitters) {
  59933. this._prepareSubEmitterInternalArray();
  59934. }
  59935. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  59936. var subs = _a[_i];
  59937. var cell = [];
  59938. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  59939. var sub = subs_1[_b];
  59940. cell.push(sub.serialize());
  59941. }
  59942. serializationObject.subEmitters.push(cell);
  59943. }
  59944. }
  59945. return serializationObject;
  59946. };
  59947. /** @hidden */
  59948. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  59949. serializationObject.name = particleSystem.name;
  59950. serializationObject.id = particleSystem.id;
  59951. serializationObject.capacity = particleSystem.getCapacity();
  59952. // Emitter
  59953. if (particleSystem.emitter.position) {
  59954. var emitterMesh = particleSystem.emitter;
  59955. serializationObject.emitterId = emitterMesh.id;
  59956. }
  59957. else {
  59958. var emitterPosition = particleSystem.emitter;
  59959. serializationObject.emitter = emitterPosition.asArray();
  59960. }
  59961. // Emitter
  59962. if (particleSystem.particleEmitterType) {
  59963. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  59964. }
  59965. if (particleSystem.particleTexture) {
  59966. serializationObject.textureName = particleSystem.particleTexture.name;
  59967. serializationObject.invertY = particleSystem.particleTexture._invertY;
  59968. }
  59969. // Animations
  59970. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  59971. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  59972. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  59973. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  59974. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  59975. // Particle system
  59976. serializationObject.startDelay = particleSystem.startDelay;
  59977. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  59978. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  59979. serializationObject.billboardMode = particleSystem.billboardMode;
  59980. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  59981. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  59982. serializationObject.minSize = particleSystem.minSize;
  59983. serializationObject.maxSize = particleSystem.maxSize;
  59984. serializationObject.minScaleX = particleSystem.minScaleX;
  59985. serializationObject.maxScaleX = particleSystem.maxScaleX;
  59986. serializationObject.minScaleY = particleSystem.minScaleY;
  59987. serializationObject.maxScaleY = particleSystem.maxScaleY;
  59988. serializationObject.minEmitPower = particleSystem.minEmitPower;
  59989. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  59990. serializationObject.minLifeTime = particleSystem.minLifeTime;
  59991. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  59992. serializationObject.emitRate = particleSystem.emitRate;
  59993. serializationObject.gravity = particleSystem.gravity.asArray();
  59994. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  59995. serializationObject.color1 = particleSystem.color1.asArray();
  59996. serializationObject.color2 = particleSystem.color2.asArray();
  59997. serializationObject.colorDead = particleSystem.colorDead.asArray();
  59998. serializationObject.updateSpeed = particleSystem.updateSpeed;
  59999. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  60000. serializationObject.blendMode = particleSystem.blendMode;
  60001. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  60002. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  60003. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  60004. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  60005. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  60006. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  60007. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  60008. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  60009. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  60010. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  60011. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  60012. var colorGradients = particleSystem.getColorGradients();
  60013. if (colorGradients) {
  60014. serializationObject.colorGradients = [];
  60015. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  60016. var colorGradient = colorGradients_1[_i];
  60017. var serializedGradient = {
  60018. gradient: colorGradient.gradient,
  60019. color1: colorGradient.color1.asArray()
  60020. };
  60021. if (colorGradient.color2) {
  60022. serializedGradient.color2 = colorGradient.color2.asArray();
  60023. }
  60024. serializationObject.colorGradients.push(serializedGradient);
  60025. }
  60026. }
  60027. var rampGradients = particleSystem.getRampGradients();
  60028. if (rampGradients) {
  60029. serializationObject.rampGradients = [];
  60030. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  60031. var rampGradient = rampGradients_1[_a];
  60032. var serializedGradient = {
  60033. gradient: rampGradient.gradient,
  60034. color: rampGradient.color.asArray()
  60035. };
  60036. serializationObject.rampGradients.push(serializedGradient);
  60037. }
  60038. serializationObject.useRampGradients = particleSystem.useRampGradients;
  60039. }
  60040. var colorRemapGradients = particleSystem.getColorRemapGradients();
  60041. if (colorRemapGradients) {
  60042. serializationObject.colorRemapGradients = [];
  60043. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  60044. var colorRemapGradient = colorRemapGradients_1[_b];
  60045. var serializedGradient = {
  60046. gradient: colorRemapGradient.gradient,
  60047. factor1: colorRemapGradient.factor1
  60048. };
  60049. if (colorRemapGradient.factor2 !== undefined) {
  60050. serializedGradient.factor2 = colorRemapGradient.factor2;
  60051. }
  60052. serializationObject.colorRemapGradients.push(serializedGradient);
  60053. }
  60054. }
  60055. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  60056. if (alphaRemapGradients) {
  60057. serializationObject.alphaRemapGradients = [];
  60058. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  60059. var alphaRemapGradient = alphaRemapGradients_1[_c];
  60060. var serializedGradient = {
  60061. gradient: alphaRemapGradient.gradient,
  60062. factor1: alphaRemapGradient.factor1
  60063. };
  60064. if (alphaRemapGradient.factor2 !== undefined) {
  60065. serializedGradient.factor2 = alphaRemapGradient.factor2;
  60066. }
  60067. serializationObject.alphaRemapGradients.push(serializedGradient);
  60068. }
  60069. }
  60070. var sizeGradients = particleSystem.getSizeGradients();
  60071. if (sizeGradients) {
  60072. serializationObject.sizeGradients = [];
  60073. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  60074. var sizeGradient = sizeGradients_1[_d];
  60075. var serializedGradient = {
  60076. gradient: sizeGradient.gradient,
  60077. factor1: sizeGradient.factor1
  60078. };
  60079. if (sizeGradient.factor2 !== undefined) {
  60080. serializedGradient.factor2 = sizeGradient.factor2;
  60081. }
  60082. serializationObject.sizeGradients.push(serializedGradient);
  60083. }
  60084. }
  60085. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  60086. if (angularSpeedGradients) {
  60087. serializationObject.angularSpeedGradients = [];
  60088. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  60089. var angularSpeedGradient = angularSpeedGradients_1[_e];
  60090. var serializedGradient = {
  60091. gradient: angularSpeedGradient.gradient,
  60092. factor1: angularSpeedGradient.factor1
  60093. };
  60094. if (angularSpeedGradient.factor2 !== undefined) {
  60095. serializedGradient.factor2 = angularSpeedGradient.factor2;
  60096. }
  60097. serializationObject.angularSpeedGradients.push(serializedGradient);
  60098. }
  60099. }
  60100. var velocityGradients = particleSystem.getVelocityGradients();
  60101. if (velocityGradients) {
  60102. serializationObject.velocityGradients = [];
  60103. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  60104. var velocityGradient = velocityGradients_1[_f];
  60105. var serializedGradient = {
  60106. gradient: velocityGradient.gradient,
  60107. factor1: velocityGradient.factor1
  60108. };
  60109. if (velocityGradient.factor2 !== undefined) {
  60110. serializedGradient.factor2 = velocityGradient.factor2;
  60111. }
  60112. serializationObject.velocityGradients.push(serializedGradient);
  60113. }
  60114. }
  60115. var dragGradients = particleSystem.getDragGradients();
  60116. if (dragGradients) {
  60117. serializationObject.dragyGradients = [];
  60118. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  60119. var dragGradient = dragGradients_1[_g];
  60120. var serializedGradient = {
  60121. gradient: dragGradient.gradient,
  60122. factor1: dragGradient.factor1
  60123. };
  60124. if (dragGradient.factor2 !== undefined) {
  60125. serializedGradient.factor2 = dragGradient.factor2;
  60126. }
  60127. serializationObject.dragGradients.push(serializedGradient);
  60128. }
  60129. }
  60130. var emitRateGradients = particleSystem.getEmitRateGradients();
  60131. if (emitRateGradients) {
  60132. serializationObject.emitRateGradients = [];
  60133. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  60134. var emitRateGradient = emitRateGradients_1[_h];
  60135. var serializedGradient = {
  60136. gradient: emitRateGradient.gradient,
  60137. factor1: emitRateGradient.factor1
  60138. };
  60139. if (emitRateGradient.factor2 !== undefined) {
  60140. serializedGradient.factor2 = emitRateGradient.factor2;
  60141. }
  60142. serializationObject.emitRateGradients.push(serializedGradient);
  60143. }
  60144. }
  60145. var startSizeGradients = particleSystem.getStartSizeGradients();
  60146. if (startSizeGradients) {
  60147. serializationObject.startSizeGradients = [];
  60148. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  60149. var startSizeGradient = startSizeGradients_1[_j];
  60150. var serializedGradient = {
  60151. gradient: startSizeGradient.gradient,
  60152. factor1: startSizeGradient.factor1
  60153. };
  60154. if (startSizeGradient.factor2 !== undefined) {
  60155. serializedGradient.factor2 = startSizeGradient.factor2;
  60156. }
  60157. serializationObject.startSizeGradients.push(serializedGradient);
  60158. }
  60159. }
  60160. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  60161. if (lifeTimeGradients) {
  60162. serializationObject.lifeTimeGradients = [];
  60163. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  60164. var lifeTimeGradient = lifeTimeGradients_1[_k];
  60165. var serializedGradient = {
  60166. gradient: lifeTimeGradient.gradient,
  60167. factor1: lifeTimeGradient.factor1
  60168. };
  60169. if (lifeTimeGradient.factor2 !== undefined) {
  60170. serializedGradient.factor2 = lifeTimeGradient.factor2;
  60171. }
  60172. serializationObject.lifeTimeGradients.push(serializedGradient);
  60173. }
  60174. }
  60175. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  60176. if (limitVelocityGradients) {
  60177. serializationObject.limitVelocityGradients = [];
  60178. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  60179. var limitVelocityGradient = limitVelocityGradients_1[_l];
  60180. var serializedGradient = {
  60181. gradient: limitVelocityGradient.gradient,
  60182. factor1: limitVelocityGradient.factor1
  60183. };
  60184. if (limitVelocityGradient.factor2 !== undefined) {
  60185. serializedGradient.factor2 = limitVelocityGradient.factor2;
  60186. }
  60187. serializationObject.limitVelocityGradients.push(serializedGradient);
  60188. }
  60189. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  60190. }
  60191. if (particleSystem.noiseTexture) {
  60192. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  60193. }
  60194. };
  60195. /** @hidden */
  60196. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  60197. // Texture
  60198. if (parsedParticleSystem.textureName) {
  60199. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  60200. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  60201. }
  60202. // Emitter
  60203. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  60204. particleSystem.emitter = BABYLON.Vector3.Zero();
  60205. }
  60206. else if (parsedParticleSystem.emitterId) {
  60207. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  60208. }
  60209. else {
  60210. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  60211. }
  60212. // Misc.
  60213. if (parsedParticleSystem.renderingGroupId !== undefined) {
  60214. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  60215. }
  60216. if (parsedParticleSystem.isBillboardBased !== undefined) {
  60217. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  60218. }
  60219. if (parsedParticleSystem.billboardMode !== undefined) {
  60220. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  60221. }
  60222. // Animations
  60223. if (parsedParticleSystem.animations) {
  60224. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  60225. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  60226. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  60227. }
  60228. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  60229. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  60230. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  60231. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  60232. }
  60233. if (parsedParticleSystem.autoAnimate) {
  60234. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  60235. }
  60236. // Particle system
  60237. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  60238. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  60239. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  60240. particleSystem.minSize = parsedParticleSystem.minSize;
  60241. particleSystem.maxSize = parsedParticleSystem.maxSize;
  60242. if (parsedParticleSystem.minScaleX) {
  60243. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  60244. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  60245. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  60246. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  60247. }
  60248. if (parsedParticleSystem.preWarmCycles !== undefined) {
  60249. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  60250. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  60251. }
  60252. if (parsedParticleSystem.minInitialRotation !== undefined) {
  60253. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  60254. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  60255. }
  60256. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  60257. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  60258. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  60259. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  60260. particleSystem.emitRate = parsedParticleSystem.emitRate;
  60261. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  60262. if (parsedParticleSystem.noiseStrength) {
  60263. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  60264. }
  60265. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  60266. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  60267. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  60268. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  60269. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  60270. particleSystem.blendMode = parsedParticleSystem.blendMode;
  60271. if (parsedParticleSystem.colorGradients) {
  60272. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  60273. var colorGradient = _a[_i];
  60274. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  60275. }
  60276. }
  60277. if (parsedParticleSystem.rampGradients) {
  60278. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  60279. var rampGradient = _c[_b];
  60280. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  60281. }
  60282. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  60283. }
  60284. if (parsedParticleSystem.colorRemapGradients) {
  60285. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  60286. var colorRemapGradient = _e[_d];
  60287. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  60288. }
  60289. }
  60290. if (parsedParticleSystem.alphaRemapGradients) {
  60291. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  60292. var alphaRemapGradient = _g[_f];
  60293. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  60294. }
  60295. }
  60296. if (parsedParticleSystem.sizeGradients) {
  60297. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  60298. var sizeGradient = _j[_h];
  60299. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60300. }
  60301. }
  60302. if (parsedParticleSystem.sizeGradients) {
  60303. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  60304. var sizeGradient = _l[_k];
  60305. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60306. }
  60307. }
  60308. if (parsedParticleSystem.angularSpeedGradients) {
  60309. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  60310. var angularSpeedGradient = _o[_m];
  60311. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  60312. }
  60313. }
  60314. if (parsedParticleSystem.velocityGradients) {
  60315. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  60316. var velocityGradient = _q[_p];
  60317. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  60318. }
  60319. }
  60320. if (parsedParticleSystem.dragGradients) {
  60321. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  60322. var dragGradient = _s[_r];
  60323. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  60324. }
  60325. }
  60326. if (parsedParticleSystem.emitRateGradients) {
  60327. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  60328. var emitRateGradient = _u[_t];
  60329. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  60330. }
  60331. }
  60332. if (parsedParticleSystem.startSizeGradients) {
  60333. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  60334. var startSizeGradient = _w[_v];
  60335. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  60336. }
  60337. }
  60338. if (parsedParticleSystem.lifeTimeGradients) {
  60339. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  60340. var lifeTimeGradient = _y[_x];
  60341. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  60342. }
  60343. }
  60344. if (parsedParticleSystem.limitVelocityGradients) {
  60345. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  60346. var limitVelocityGradient = _0[_z];
  60347. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  60348. }
  60349. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  60350. }
  60351. if (parsedParticleSystem.noiseTexture) {
  60352. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  60353. }
  60354. // Emitter
  60355. var emitterType;
  60356. if (parsedParticleSystem.particleEmitterType) {
  60357. switch (parsedParticleSystem.particleEmitterType.type) {
  60358. case "SphereParticleEmitter":
  60359. emitterType = new BABYLON.SphereParticleEmitter();
  60360. break;
  60361. case "SphereDirectedParticleEmitter":
  60362. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  60363. break;
  60364. case "ConeEmitter":
  60365. case "ConeParticleEmitter":
  60366. emitterType = new BABYLON.ConeParticleEmitter();
  60367. break;
  60368. case "CylinderParticleEmitter":
  60369. emitterType = new BABYLON.CylinderParticleEmitter();
  60370. break;
  60371. case "HemisphericParticleEmitter":
  60372. emitterType = new BABYLON.HemisphericParticleEmitter();
  60373. break;
  60374. case "BoxEmitter":
  60375. case "BoxParticleEmitter":
  60376. default:
  60377. emitterType = new BABYLON.BoxParticleEmitter();
  60378. break;
  60379. }
  60380. emitterType.parse(parsedParticleSystem.particleEmitterType);
  60381. }
  60382. else {
  60383. emitterType = new BABYLON.BoxParticleEmitter();
  60384. emitterType.parse(parsedParticleSystem);
  60385. }
  60386. particleSystem.particleEmitterType = emitterType;
  60387. // Animation sheet
  60388. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  60389. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  60390. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  60391. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  60392. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  60393. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  60394. };
  60395. /**
  60396. * Parses a JSON object to create a particle system.
  60397. * @param parsedParticleSystem The JSON object to parse
  60398. * @param scene The scene to create the particle system in
  60399. * @param rootUrl The root url to use to load external dependencies like texture
  60400. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  60401. * @returns the Parsed particle system
  60402. */
  60403. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  60404. if (doNotStart === void 0) { doNotStart = false; }
  60405. var name = parsedParticleSystem.name;
  60406. var custom = null;
  60407. var program = null;
  60408. if (parsedParticleSystem.customShader) {
  60409. program = parsedParticleSystem.customShader;
  60410. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60411. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60412. }
  60413. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  60414. particleSystem.customShader = program;
  60415. if (parsedParticleSystem.id) {
  60416. particleSystem.id = parsedParticleSystem.id;
  60417. }
  60418. // SubEmitters
  60419. if (parsedParticleSystem.subEmitters) {
  60420. particleSystem.subEmitters = [];
  60421. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  60422. var cell = _a[_i];
  60423. var cellArray = [];
  60424. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  60425. var sub = cell_1[_b];
  60426. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  60427. }
  60428. particleSystem.subEmitters.push(cellArray);
  60429. }
  60430. }
  60431. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60432. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  60433. // Auto start
  60434. if (parsedParticleSystem.preventAutoStart) {
  60435. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  60436. }
  60437. if (!doNotStart && !particleSystem.preventAutoStart) {
  60438. particleSystem.start();
  60439. }
  60440. return particleSystem;
  60441. };
  60442. /**
  60443. * Billboard mode will only apply to Y axis
  60444. */
  60445. ParticleSystem.BILLBOARDMODE_Y = 2;
  60446. /**
  60447. * Billboard mode will apply to all axes
  60448. */
  60449. ParticleSystem.BILLBOARDMODE_ALL = 7;
  60450. /**
  60451. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  60452. */
  60453. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  60454. return ParticleSystem;
  60455. }(BABYLON.BaseParticleSystem));
  60456. BABYLON.ParticleSystem = ParticleSystem;
  60457. })(BABYLON || (BABYLON = {}));
  60458. //# sourceMappingURL=babylon.particleSystem.js.map
  60459. var BABYLON;
  60460. (function (BABYLON) {
  60461. /**
  60462. * Particle emitter emitting particles from the inside of a box.
  60463. * It emits the particles randomly between 2 given directions.
  60464. */
  60465. var BoxParticleEmitter = /** @class */ (function () {
  60466. /**
  60467. * Creates a new instance BoxParticleEmitter
  60468. */
  60469. function BoxParticleEmitter() {
  60470. /**
  60471. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60472. */
  60473. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60474. /**
  60475. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60476. */
  60477. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60478. /**
  60479. * 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.
  60480. */
  60481. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  60482. /**
  60483. * 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.
  60484. */
  60485. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  60486. }
  60487. /**
  60488. * Called by the particle System when the direction is computed for the created particle.
  60489. * @param worldMatrix is the world matrix of the particle system
  60490. * @param directionToUpdate is the direction vector to update with the result
  60491. * @param particle is the particle we are computed the direction for
  60492. */
  60493. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60494. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60495. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60496. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60497. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60498. };
  60499. /**
  60500. * Called by the particle System when the position is computed for the created particle.
  60501. * @param worldMatrix is the world matrix of the particle system
  60502. * @param positionToUpdate is the position vector to update with the result
  60503. * @param particle is the particle we are computed the position for
  60504. */
  60505. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60506. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  60507. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  60508. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  60509. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60510. };
  60511. /**
  60512. * Clones the current emitter and returns a copy of it
  60513. * @returns the new emitter
  60514. */
  60515. BoxParticleEmitter.prototype.clone = function () {
  60516. var newOne = new BoxParticleEmitter();
  60517. BABYLON.Tools.DeepCopy(this, newOne);
  60518. return newOne;
  60519. };
  60520. /**
  60521. * Called by the GPUParticleSystem to setup the update shader
  60522. * @param effect defines the update shader
  60523. */
  60524. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  60525. effect.setVector3("direction1", this.direction1);
  60526. effect.setVector3("direction2", this.direction2);
  60527. effect.setVector3("minEmitBox", this.minEmitBox);
  60528. effect.setVector3("maxEmitBox", this.maxEmitBox);
  60529. };
  60530. /**
  60531. * Returns a string to use to update the GPU particles update shader
  60532. * @returns a string containng the defines string
  60533. */
  60534. BoxParticleEmitter.prototype.getEffectDefines = function () {
  60535. return "#define BOXEMITTER";
  60536. };
  60537. /**
  60538. * Returns the string "BoxParticleEmitter"
  60539. * @returns a string containing the class name
  60540. */
  60541. BoxParticleEmitter.prototype.getClassName = function () {
  60542. return "BoxParticleEmitter";
  60543. };
  60544. /**
  60545. * Serializes the particle system to a JSON object.
  60546. * @returns the JSON object
  60547. */
  60548. BoxParticleEmitter.prototype.serialize = function () {
  60549. var serializationObject = {};
  60550. serializationObject.type = this.getClassName();
  60551. serializationObject.direction1 = this.direction1.asArray();
  60552. serializationObject.direction2 = this.direction2.asArray();
  60553. serializationObject.minEmitBox = this.minEmitBox.asArray();
  60554. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  60555. return serializationObject;
  60556. };
  60557. /**
  60558. * Parse properties from a JSON object
  60559. * @param serializationObject defines the JSON object
  60560. */
  60561. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  60562. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60563. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60564. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  60565. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  60566. };
  60567. return BoxParticleEmitter;
  60568. }());
  60569. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  60570. })(BABYLON || (BABYLON = {}));
  60571. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  60572. var BABYLON;
  60573. (function (BABYLON) {
  60574. /**
  60575. * Particle emitter emitting particles from the inside of a cylinder.
  60576. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  60577. */
  60578. var CylinderParticleEmitter = /** @class */ (function () {
  60579. /**
  60580. * Creates a new instance CylinderParticleEmitter
  60581. * @param radius the radius of the emission cylinder (1 by default)
  60582. * @param height the height of the emission cylinder (1 by default)
  60583. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60584. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60585. */
  60586. function CylinderParticleEmitter(
  60587. /**
  60588. * The radius of the emission cylinder.
  60589. */
  60590. radius,
  60591. /**
  60592. * The height of the emission cylinder.
  60593. */
  60594. height,
  60595. /**
  60596. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60597. */
  60598. radiusRange,
  60599. /**
  60600. * How much to randomize the particle direction [0-1].
  60601. */
  60602. directionRandomizer) {
  60603. if (radius === void 0) { radius = 1; }
  60604. if (height === void 0) { height = 1; }
  60605. if (radiusRange === void 0) { radiusRange = 1; }
  60606. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60607. this.radius = radius;
  60608. this.height = height;
  60609. this.radiusRange = radiusRange;
  60610. this.directionRandomizer = directionRandomizer;
  60611. }
  60612. /**
  60613. * Called by the particle System when the direction is computed for the created particle.
  60614. * @param worldMatrix is the world matrix of the particle system
  60615. * @param directionToUpdate is the direction vector to update with the result
  60616. * @param particle is the particle we are computed the direction for
  60617. */
  60618. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60619. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60620. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  60621. var angle = Math.atan2(direction.x, direction.z);
  60622. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  60623. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  60624. direction.x = Math.sin(angle);
  60625. direction.z = Math.cos(angle);
  60626. direction.normalize();
  60627. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60628. };
  60629. /**
  60630. * Called by the particle System when the position is computed for the created particle.
  60631. * @param worldMatrix is the world matrix of the particle system
  60632. * @param positionToUpdate is the position vector to update with the result
  60633. * @param particle is the particle we are computed the position for
  60634. */
  60635. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60636. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  60637. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60638. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  60639. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  60640. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  60641. var xPos = positionRadius * Math.cos(angle);
  60642. var zPos = positionRadius * Math.sin(angle);
  60643. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  60644. };
  60645. /**
  60646. * Clones the current emitter and returns a copy of it
  60647. * @returns the new emitter
  60648. */
  60649. CylinderParticleEmitter.prototype.clone = function () {
  60650. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  60651. BABYLON.Tools.DeepCopy(this, newOne);
  60652. return newOne;
  60653. };
  60654. /**
  60655. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60656. * @param effect defines the update shader
  60657. */
  60658. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  60659. effect.setFloat("radius", this.radius);
  60660. effect.setFloat("height", this.height);
  60661. effect.setFloat("radiusRange", this.radiusRange);
  60662. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60663. };
  60664. /**
  60665. * Returns a string to use to update the GPU particles update shader
  60666. * @returns a string containng the defines string
  60667. */
  60668. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  60669. return "#define CYLINDEREMITTER";
  60670. };
  60671. /**
  60672. * Returns the string "CylinderParticleEmitter"
  60673. * @returns a string containing the class name
  60674. */
  60675. CylinderParticleEmitter.prototype.getClassName = function () {
  60676. return "CylinderParticleEmitter";
  60677. };
  60678. /**
  60679. * Serializes the particle system to a JSON object.
  60680. * @returns the JSON object
  60681. */
  60682. CylinderParticleEmitter.prototype.serialize = function () {
  60683. var serializationObject = {};
  60684. serializationObject.type = this.getClassName();
  60685. serializationObject.radius = this.radius;
  60686. serializationObject.height = this.height;
  60687. serializationObject.radiusRange = this.radiusRange;
  60688. serializationObject.directionRandomizer = this.directionRandomizer;
  60689. return serializationObject;
  60690. };
  60691. /**
  60692. * Parse properties from a JSON object
  60693. * @param serializationObject defines the JSON object
  60694. */
  60695. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  60696. this.radius = serializationObject.radius;
  60697. this.height = serializationObject.height;
  60698. this.radiusRange = serializationObject.radiusRange;
  60699. this.directionRandomizer = serializationObject.directionRandomizer;
  60700. };
  60701. return CylinderParticleEmitter;
  60702. }());
  60703. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  60704. /**
  60705. * Particle emitter emitting particles from the inside of a cylinder.
  60706. * It emits the particles randomly between two vectors.
  60707. */
  60708. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  60709. __extends(CylinderDirectedParticleEmitter, _super);
  60710. /**
  60711. * Creates a new instance CylinderDirectedParticleEmitter
  60712. * @param radius the radius of the emission cylinder (1 by default)
  60713. * @param height the height of the emission cylinder (1 by default)
  60714. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60715. * @param direction1 the min limit of the emission direction (up vector by default)
  60716. * @param direction2 the max limit of the emission direction (up vector by default)
  60717. */
  60718. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  60719. /**
  60720. * The min limit of the emission direction.
  60721. */
  60722. direction1,
  60723. /**
  60724. * The max limit of the emission direction.
  60725. */
  60726. direction2) {
  60727. if (radius === void 0) { radius = 1; }
  60728. if (height === void 0) { height = 1; }
  60729. if (radiusRange === void 0) { radiusRange = 1; }
  60730. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60731. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60732. var _this = _super.call(this, radius, height, radiusRange) || this;
  60733. _this.direction1 = direction1;
  60734. _this.direction2 = direction2;
  60735. return _this;
  60736. }
  60737. /**
  60738. * Called by the particle System when the direction is computed for the created particle.
  60739. * @param worldMatrix is the world matrix of the particle system
  60740. * @param directionToUpdate is the direction vector to update with the result
  60741. * @param particle is the particle we are computed the direction for
  60742. */
  60743. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60744. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60745. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60746. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60747. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60748. };
  60749. /**
  60750. * Clones the current emitter and returns a copy of it
  60751. * @returns the new emitter
  60752. */
  60753. CylinderDirectedParticleEmitter.prototype.clone = function () {
  60754. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  60755. BABYLON.Tools.DeepCopy(this, newOne);
  60756. return newOne;
  60757. };
  60758. /**
  60759. * Called by the GPUParticleSystem to setup the update shader
  60760. * @param effect defines the update shader
  60761. */
  60762. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60763. effect.setFloat("radius", this.radius);
  60764. effect.setFloat("height", this.height);
  60765. effect.setFloat("radiusRange", this.radiusRange);
  60766. effect.setVector3("direction1", this.direction1);
  60767. effect.setVector3("direction2", this.direction2);
  60768. };
  60769. /**
  60770. * Returns a string to use to update the GPU particles update shader
  60771. * @returns a string containng the defines string
  60772. */
  60773. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60774. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  60775. };
  60776. /**
  60777. * Returns the string "CylinderDirectedParticleEmitter"
  60778. * @returns a string containing the class name
  60779. */
  60780. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  60781. return "CylinderDirectedParticleEmitter";
  60782. };
  60783. /**
  60784. * Serializes the particle system to a JSON object.
  60785. * @returns the JSON object
  60786. */
  60787. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  60788. var serializationObject = _super.prototype.serialize.call(this);
  60789. serializationObject.direction1 = this.direction1.asArray();
  60790. serializationObject.direction2 = this.direction2.asArray();
  60791. return serializationObject;
  60792. };
  60793. /**
  60794. * Parse properties from a JSON object
  60795. * @param serializationObject defines the JSON object
  60796. */
  60797. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60798. _super.prototype.parse.call(this, serializationObject);
  60799. this.direction1.copyFrom(serializationObject.direction1);
  60800. this.direction2.copyFrom(serializationObject.direction2);
  60801. };
  60802. return CylinderDirectedParticleEmitter;
  60803. }(CylinderParticleEmitter));
  60804. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  60805. })(BABYLON || (BABYLON = {}));
  60806. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  60807. var BABYLON;
  60808. (function (BABYLON) {
  60809. /**
  60810. * Particle emitter emitting particles from the inside of a cone.
  60811. * It emits the particles alongside the cone volume from the base to the particle.
  60812. * The emission direction might be randomized.
  60813. */
  60814. var ConeParticleEmitter = /** @class */ (function () {
  60815. /**
  60816. * Creates a new instance ConeParticleEmitter
  60817. * @param radius the radius of the emission cone (1 by default)
  60818. * @param angles the cone base angle (PI by default)
  60819. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  60820. */
  60821. function ConeParticleEmitter(radius, angle,
  60822. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  60823. directionRandomizer) {
  60824. if (radius === void 0) { radius = 1; }
  60825. if (angle === void 0) { angle = Math.PI; }
  60826. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60827. this.directionRandomizer = directionRandomizer;
  60828. /**
  60829. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  60830. */
  60831. this.radiusRange = 1;
  60832. /**
  60833. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  60834. */
  60835. this.heightRange = 1;
  60836. /**
  60837. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  60838. */
  60839. this.emitFromSpawnPointOnly = false;
  60840. this.angle = angle;
  60841. this.radius = radius;
  60842. }
  60843. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  60844. /**
  60845. * Gets or sets the radius of the emission cone
  60846. */
  60847. get: function () {
  60848. return this._radius;
  60849. },
  60850. set: function (value) {
  60851. this._radius = value;
  60852. this._buildHeight();
  60853. },
  60854. enumerable: true,
  60855. configurable: true
  60856. });
  60857. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  60858. /**
  60859. * Gets or sets the angle of the emission cone
  60860. */
  60861. get: function () {
  60862. return this._angle;
  60863. },
  60864. set: function (value) {
  60865. this._angle = value;
  60866. this._buildHeight();
  60867. },
  60868. enumerable: true,
  60869. configurable: true
  60870. });
  60871. ConeParticleEmitter.prototype._buildHeight = function () {
  60872. if (this._angle !== 0) {
  60873. this._height = this._radius / Math.tan(this._angle / 2);
  60874. }
  60875. else {
  60876. this._height = 1;
  60877. }
  60878. };
  60879. /**
  60880. * Called by the particle System when the direction is computed for the created particle.
  60881. * @param worldMatrix is the world matrix of the particle system
  60882. * @param directionToUpdate is the direction vector to update with the result
  60883. * @param particle is the particle we are computed the direction for
  60884. */
  60885. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60886. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  60887. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  60888. }
  60889. else {
  60890. // measure the direction Vector from the emitter to the particle.
  60891. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60892. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60893. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60894. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60895. direction.x += randX;
  60896. direction.y += randY;
  60897. direction.z += randZ;
  60898. direction.normalize();
  60899. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60900. }
  60901. };
  60902. /**
  60903. * Called by the particle System when the position is computed for the created particle.
  60904. * @param worldMatrix is the world matrix of the particle system
  60905. * @param positionToUpdate is the position vector to update with the result
  60906. * @param particle is the particle we are computed the position for
  60907. */
  60908. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60909. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  60910. var h;
  60911. if (!this.emitFromSpawnPointOnly) {
  60912. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  60913. // Better distribution in a cone at normal angles.
  60914. h = 1 - h * h;
  60915. }
  60916. else {
  60917. h = 0.0001;
  60918. }
  60919. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  60920. radius = radius * h;
  60921. var randX = radius * Math.sin(s);
  60922. var randZ = radius * Math.cos(s);
  60923. var randY = h * this._height;
  60924. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60925. };
  60926. /**
  60927. * Clones the current emitter and returns a copy of it
  60928. * @returns the new emitter
  60929. */
  60930. ConeParticleEmitter.prototype.clone = function () {
  60931. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  60932. BABYLON.Tools.DeepCopy(this, newOne);
  60933. return newOne;
  60934. };
  60935. /**
  60936. * Called by the GPUParticleSystem to setup the update shader
  60937. * @param effect defines the update shader
  60938. */
  60939. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  60940. effect.setFloat2("radius", this._radius, this.radiusRange);
  60941. effect.setFloat("coneAngle", this._angle);
  60942. effect.setFloat2("height", this._height, this.heightRange);
  60943. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60944. };
  60945. /**
  60946. * Returns a string to use to update the GPU particles update shader
  60947. * @returns a string containng the defines string
  60948. */
  60949. ConeParticleEmitter.prototype.getEffectDefines = function () {
  60950. var defines = "#define CONEEMITTER";
  60951. if (this.emitFromSpawnPointOnly) {
  60952. defines += "\n#define CONEEMITTERSPAWNPOINT";
  60953. }
  60954. return defines;
  60955. };
  60956. /**
  60957. * Returns the string "ConeParticleEmitter"
  60958. * @returns a string containing the class name
  60959. */
  60960. ConeParticleEmitter.prototype.getClassName = function () {
  60961. return "ConeParticleEmitter";
  60962. };
  60963. /**
  60964. * Serializes the particle system to a JSON object.
  60965. * @returns the JSON object
  60966. */
  60967. ConeParticleEmitter.prototype.serialize = function () {
  60968. var serializationObject = {};
  60969. serializationObject.type = this.getClassName();
  60970. serializationObject.radius = this._radius;
  60971. serializationObject.angle = this._angle;
  60972. serializationObject.directionRandomizer = this.directionRandomizer;
  60973. return serializationObject;
  60974. };
  60975. /**
  60976. * Parse properties from a JSON object
  60977. * @param serializationObject defines the JSON object
  60978. */
  60979. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  60980. this.radius = serializationObject.radius;
  60981. this.angle = serializationObject.angle;
  60982. this.directionRandomizer = serializationObject.directionRandomizer;
  60983. };
  60984. return ConeParticleEmitter;
  60985. }());
  60986. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  60987. })(BABYLON || (BABYLON = {}));
  60988. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  60989. var BABYLON;
  60990. (function (BABYLON) {
  60991. /**
  60992. * Particle emitter emitting particles from the inside of a sphere.
  60993. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  60994. */
  60995. var SphereParticleEmitter = /** @class */ (function () {
  60996. /**
  60997. * Creates a new instance SphereParticleEmitter
  60998. * @param radius the radius of the emission sphere (1 by default)
  60999. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61000. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61001. */
  61002. function SphereParticleEmitter(
  61003. /**
  61004. * The radius of the emission sphere.
  61005. */
  61006. radius,
  61007. /**
  61008. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61009. */
  61010. radiusRange,
  61011. /**
  61012. * How much to randomize the particle direction [0-1].
  61013. */
  61014. directionRandomizer) {
  61015. if (radius === void 0) { radius = 1; }
  61016. if (radiusRange === void 0) { radiusRange = 1; }
  61017. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61018. this.radius = radius;
  61019. this.radiusRange = radiusRange;
  61020. this.directionRandomizer = directionRandomizer;
  61021. }
  61022. /**
  61023. * Called by the particle System when the direction is computed for the created particle.
  61024. * @param worldMatrix is the world matrix of the particle system
  61025. * @param directionToUpdate is the direction vector to update with the result
  61026. * @param particle is the particle we are computed the direction for
  61027. */
  61028. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61029. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61030. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61031. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61032. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61033. direction.x += randX;
  61034. direction.y += randY;
  61035. direction.z += randZ;
  61036. direction.normalize();
  61037. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61038. };
  61039. /**
  61040. * Called by the particle System when the position is computed for the created particle.
  61041. * @param worldMatrix is the world matrix of the particle system
  61042. * @param positionToUpdate is the position vector to update with the result
  61043. * @param particle is the particle we are computed the position for
  61044. */
  61045. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61046. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61047. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61048. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61049. var theta = Math.acos(2 * v - 1);
  61050. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61051. var randY = randRadius * Math.cos(theta);
  61052. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61053. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61054. };
  61055. /**
  61056. * Clones the current emitter and returns a copy of it
  61057. * @returns the new emitter
  61058. */
  61059. SphereParticleEmitter.prototype.clone = function () {
  61060. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  61061. BABYLON.Tools.DeepCopy(this, newOne);
  61062. return newOne;
  61063. };
  61064. /**
  61065. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61066. * @param effect defines the update shader
  61067. */
  61068. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  61069. effect.setFloat("radius", this.radius);
  61070. effect.setFloat("radiusRange", this.radiusRange);
  61071. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61072. };
  61073. /**
  61074. * Returns a string to use to update the GPU particles update shader
  61075. * @returns a string containng the defines string
  61076. */
  61077. SphereParticleEmitter.prototype.getEffectDefines = function () {
  61078. return "#define SPHEREEMITTER";
  61079. };
  61080. /**
  61081. * Returns the string "SphereParticleEmitter"
  61082. * @returns a string containing the class name
  61083. */
  61084. SphereParticleEmitter.prototype.getClassName = function () {
  61085. return "SphereParticleEmitter";
  61086. };
  61087. /**
  61088. * Serializes the particle system to a JSON object.
  61089. * @returns the JSON object
  61090. */
  61091. SphereParticleEmitter.prototype.serialize = function () {
  61092. var serializationObject = {};
  61093. serializationObject.type = this.getClassName();
  61094. serializationObject.radius = this.radius;
  61095. serializationObject.radiusRange = this.radiusRange;
  61096. serializationObject.directionRandomizer = this.directionRandomizer;
  61097. return serializationObject;
  61098. };
  61099. /**
  61100. * Parse properties from a JSON object
  61101. * @param serializationObject defines the JSON object
  61102. */
  61103. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  61104. this.radius = serializationObject.radius;
  61105. this.radiusRange = serializationObject.radiusRange;
  61106. this.directionRandomizer = serializationObject.directionRandomizer;
  61107. };
  61108. return SphereParticleEmitter;
  61109. }());
  61110. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  61111. /**
  61112. * Particle emitter emitting particles from the inside of a sphere.
  61113. * It emits the particles randomly between two vectors.
  61114. */
  61115. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  61116. __extends(SphereDirectedParticleEmitter, _super);
  61117. /**
  61118. * Creates a new instance SphereDirectedParticleEmitter
  61119. * @param radius the radius of the emission sphere (1 by default)
  61120. * @param direction1 the min limit of the emission direction (up vector by default)
  61121. * @param direction2 the max limit of the emission direction (up vector by default)
  61122. */
  61123. function SphereDirectedParticleEmitter(radius,
  61124. /**
  61125. * The min limit of the emission direction.
  61126. */
  61127. direction1,
  61128. /**
  61129. * The max limit of the emission direction.
  61130. */
  61131. direction2) {
  61132. if (radius === void 0) { radius = 1; }
  61133. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61134. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61135. var _this = _super.call(this, radius) || this;
  61136. _this.direction1 = direction1;
  61137. _this.direction2 = direction2;
  61138. return _this;
  61139. }
  61140. /**
  61141. * Called by the particle System when the direction is computed for the created particle.
  61142. * @param worldMatrix is the world matrix of the particle system
  61143. * @param directionToUpdate is the direction vector to update with the result
  61144. * @param particle is the particle we are computed the direction for
  61145. */
  61146. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61147. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61148. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61149. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61150. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61151. };
  61152. /**
  61153. * Clones the current emitter and returns a copy of it
  61154. * @returns the new emitter
  61155. */
  61156. SphereDirectedParticleEmitter.prototype.clone = function () {
  61157. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  61158. BABYLON.Tools.DeepCopy(this, newOne);
  61159. return newOne;
  61160. };
  61161. /**
  61162. * Called by the GPUParticleSystem to setup the update shader
  61163. * @param effect defines the update shader
  61164. */
  61165. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61166. effect.setFloat("radius", this.radius);
  61167. effect.setFloat("radiusRange", this.radiusRange);
  61168. effect.setVector3("direction1", this.direction1);
  61169. effect.setVector3("direction2", this.direction2);
  61170. };
  61171. /**
  61172. * Returns a string to use to update the GPU particles update shader
  61173. * @returns a string containng the defines string
  61174. */
  61175. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61176. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  61177. };
  61178. /**
  61179. * Returns the string "SphereDirectedParticleEmitter"
  61180. * @returns a string containing the class name
  61181. */
  61182. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  61183. return "SphereDirectedParticleEmitter";
  61184. };
  61185. /**
  61186. * Serializes the particle system to a JSON object.
  61187. * @returns the JSON object
  61188. */
  61189. SphereDirectedParticleEmitter.prototype.serialize = function () {
  61190. var serializationObject = _super.prototype.serialize.call(this);
  61191. serializationObject.direction1 = this.direction1.asArray();
  61192. serializationObject.direction2 = this.direction2.asArray();
  61193. return serializationObject;
  61194. };
  61195. /**
  61196. * Parse properties from a JSON object
  61197. * @param serializationObject defines the JSON object
  61198. */
  61199. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61200. _super.prototype.parse.call(this, serializationObject);
  61201. this.direction1.copyFrom(serializationObject.direction1);
  61202. this.direction2.copyFrom(serializationObject.direction2);
  61203. };
  61204. return SphereDirectedParticleEmitter;
  61205. }(SphereParticleEmitter));
  61206. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  61207. })(BABYLON || (BABYLON = {}));
  61208. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  61209. var BABYLON;
  61210. (function (BABYLON) {
  61211. /**
  61212. * Particle emitter emitting particles from the inside of a hemisphere.
  61213. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  61214. */
  61215. var HemisphericParticleEmitter = /** @class */ (function () {
  61216. /**
  61217. * Creates a new instance HemisphericParticleEmitter
  61218. * @param radius the radius of the emission hemisphere (1 by default)
  61219. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61220. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61221. */
  61222. function HemisphericParticleEmitter(
  61223. /**
  61224. * The radius of the emission hemisphere.
  61225. */
  61226. radius,
  61227. /**
  61228. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61229. */
  61230. radiusRange,
  61231. /**
  61232. * How much to randomize the particle direction [0-1].
  61233. */
  61234. directionRandomizer) {
  61235. if (radius === void 0) { radius = 1; }
  61236. if (radiusRange === void 0) { radiusRange = 1; }
  61237. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61238. this.radius = radius;
  61239. this.radiusRange = radiusRange;
  61240. this.directionRandomizer = directionRandomizer;
  61241. }
  61242. /**
  61243. * Called by the particle System when the direction is computed for the created particle.
  61244. * @param worldMatrix is the world matrix of the particle system
  61245. * @param directionToUpdate is the direction vector to update with the result
  61246. * @param particle is the particle we are computed the direction for
  61247. */
  61248. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61249. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61250. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61251. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61252. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61253. direction.x += randX;
  61254. direction.y += randY;
  61255. direction.z += randZ;
  61256. direction.normalize();
  61257. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61258. };
  61259. /**
  61260. * Called by the particle System when the position is computed for the created particle.
  61261. * @param worldMatrix is the world matrix of the particle system
  61262. * @param positionToUpdate is the position vector to update with the result
  61263. * @param particle is the particle we are computed the position for
  61264. */
  61265. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61266. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61267. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61268. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61269. var theta = Math.acos(2 * v - 1);
  61270. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61271. var randY = randRadius * Math.cos(theta);
  61272. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61273. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  61274. };
  61275. /**
  61276. * Clones the current emitter and returns a copy of it
  61277. * @returns the new emitter
  61278. */
  61279. HemisphericParticleEmitter.prototype.clone = function () {
  61280. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  61281. BABYLON.Tools.DeepCopy(this, newOne);
  61282. return newOne;
  61283. };
  61284. /**
  61285. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61286. * @param effect defines the update shader
  61287. */
  61288. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  61289. effect.setFloat("radius", this.radius);
  61290. effect.setFloat("radiusRange", this.radiusRange);
  61291. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61292. };
  61293. /**
  61294. * Returns a string to use to update the GPU particles update shader
  61295. * @returns a string containng the defines string
  61296. */
  61297. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  61298. return "#define HEMISPHERICEMITTER";
  61299. };
  61300. /**
  61301. * Returns the string "HemisphericParticleEmitter"
  61302. * @returns a string containing the class name
  61303. */
  61304. HemisphericParticleEmitter.prototype.getClassName = function () {
  61305. return "HemisphericParticleEmitter";
  61306. };
  61307. /**
  61308. * Serializes the particle system to a JSON object.
  61309. * @returns the JSON object
  61310. */
  61311. HemisphericParticleEmitter.prototype.serialize = function () {
  61312. var serializationObject = {};
  61313. serializationObject.type = this.getClassName();
  61314. serializationObject.radius = this.radius;
  61315. serializationObject.radiusRange = this.radiusRange;
  61316. serializationObject.directionRandomizer = this.directionRandomizer;
  61317. return serializationObject;
  61318. };
  61319. /**
  61320. * Parse properties from a JSON object
  61321. * @param serializationObject defines the JSON object
  61322. */
  61323. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  61324. this.radius = serializationObject.radius;
  61325. this.radiusRange = serializationObject.radiusRange;
  61326. this.directionRandomizer = serializationObject.directionRandomizer;
  61327. };
  61328. return HemisphericParticleEmitter;
  61329. }());
  61330. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  61331. })(BABYLON || (BABYLON = {}));
  61332. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  61333. var BABYLON;
  61334. (function (BABYLON) {
  61335. /**
  61336. * Particle emitter emitting particles from a point.
  61337. * It emits the particles randomly between 2 given directions.
  61338. */
  61339. var PointParticleEmitter = /** @class */ (function () {
  61340. /**
  61341. * Creates a new instance PointParticleEmitter
  61342. */
  61343. function PointParticleEmitter() {
  61344. /**
  61345. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61346. */
  61347. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61348. /**
  61349. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61350. */
  61351. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61352. }
  61353. /**
  61354. * Called by the particle System when the direction is computed for the created particle.
  61355. * @param worldMatrix is the world matrix of the particle system
  61356. * @param directionToUpdate is the direction vector to update with the result
  61357. * @param particle is the particle we are computed the direction for
  61358. */
  61359. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61360. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61361. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61362. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61363. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61364. };
  61365. /**
  61366. * Called by the particle System when the position is computed for the created particle.
  61367. * @param worldMatrix is the world matrix of the particle system
  61368. * @param positionToUpdate is the position vector to update with the result
  61369. * @param particle is the particle we are computed the position for
  61370. */
  61371. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61372. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  61373. };
  61374. /**
  61375. * Clones the current emitter and returns a copy of it
  61376. * @returns the new emitter
  61377. */
  61378. PointParticleEmitter.prototype.clone = function () {
  61379. var newOne = new PointParticleEmitter();
  61380. BABYLON.Tools.DeepCopy(this, newOne);
  61381. return newOne;
  61382. };
  61383. /**
  61384. * Called by the GPUParticleSystem to setup the update shader
  61385. * @param effect defines the update shader
  61386. */
  61387. PointParticleEmitter.prototype.applyToShader = function (effect) {
  61388. effect.setVector3("direction1", this.direction1);
  61389. effect.setVector3("direction2", this.direction2);
  61390. };
  61391. /**
  61392. * Returns a string to use to update the GPU particles update shader
  61393. * @returns a string containng the defines string
  61394. */
  61395. PointParticleEmitter.prototype.getEffectDefines = function () {
  61396. return "#define POINTEMITTER";
  61397. };
  61398. /**
  61399. * Returns the string "PointParticleEmitter"
  61400. * @returns a string containing the class name
  61401. */
  61402. PointParticleEmitter.prototype.getClassName = function () {
  61403. return "PointParticleEmitter";
  61404. };
  61405. /**
  61406. * Serializes the particle system to a JSON object.
  61407. * @returns the JSON object
  61408. */
  61409. PointParticleEmitter.prototype.serialize = function () {
  61410. var serializationObject = {};
  61411. serializationObject.type = this.getClassName();
  61412. serializationObject.direction1 = this.direction1.asArray();
  61413. serializationObject.direction2 = this.direction2.asArray();
  61414. return serializationObject;
  61415. };
  61416. /**
  61417. * Parse properties from a JSON object
  61418. * @param serializationObject defines the JSON object
  61419. */
  61420. PointParticleEmitter.prototype.parse = function (serializationObject) {
  61421. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61422. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61423. };
  61424. return PointParticleEmitter;
  61425. }());
  61426. BABYLON.PointParticleEmitter = PointParticleEmitter;
  61427. })(BABYLON || (BABYLON = {}));
  61428. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  61429. var BABYLON;
  61430. (function (BABYLON) {
  61431. // Adds the parsers to the scene parsers.
  61432. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  61433. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  61434. if (!individualParser) {
  61435. return;
  61436. }
  61437. // Particles Systems
  61438. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61439. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61440. var parsedParticleSystem = parsedData.particleSystems[index];
  61441. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  61442. }
  61443. }
  61444. });
  61445. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  61446. if (parsedParticleSystem.activeParticleCount) {
  61447. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61448. return ps;
  61449. }
  61450. else {
  61451. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61452. return ps;
  61453. }
  61454. });
  61455. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  61456. if (uniformsNames === void 0) { uniformsNames = []; }
  61457. if (samplers === void 0) { samplers = []; }
  61458. if (defines === void 0) { defines = ""; }
  61459. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  61460. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  61461. if (defines.indexOf(" BILLBOARD") === -1) {
  61462. defines += "\n#define BILLBOARD\n";
  61463. }
  61464. if (samplers.indexOf("diffuseSampler") === -1) {
  61465. samplers.push("diffuseSampler");
  61466. }
  61467. return this.createEffect({
  61468. vertex: "particles",
  61469. fragmentElement: fragmentName
  61470. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  61471. };
  61472. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  61473. var results = new Array();
  61474. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  61475. var particleSystem = this.getScene().particleSystems[index];
  61476. if (particleSystem.emitter === this) {
  61477. results.push(particleSystem);
  61478. }
  61479. }
  61480. return results;
  61481. };
  61482. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  61483. var results = new Array();
  61484. var descendants = this.getDescendants();
  61485. descendants.push(this);
  61486. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  61487. var particleSystem = this.getScene().particleSystems[index];
  61488. var emitter = particleSystem.emitter;
  61489. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  61490. results.push(particleSystem);
  61491. }
  61492. }
  61493. return results;
  61494. };
  61495. })(BABYLON || (BABYLON = {}));
  61496. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  61497. var BABYLON;
  61498. (function (BABYLON) {
  61499. /**
  61500. * Type of sub emitter
  61501. */
  61502. var SubEmitterType;
  61503. (function (SubEmitterType) {
  61504. /**
  61505. * Attached to the particle over it's lifetime
  61506. */
  61507. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  61508. /**
  61509. * Created when the particle dies
  61510. */
  61511. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  61512. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  61513. /**
  61514. * Sub emitter class used to emit particles from an existing particle
  61515. */
  61516. var SubEmitter = /** @class */ (function () {
  61517. /**
  61518. * Creates a sub emitter
  61519. * @param particleSystem the particle system to be used by the sub emitter
  61520. */
  61521. function SubEmitter(
  61522. /**
  61523. * the particle system to be used by the sub emitter
  61524. */
  61525. particleSystem) {
  61526. this.particleSystem = particleSystem;
  61527. /**
  61528. * Type of the submitter (Default: END)
  61529. */
  61530. this.type = SubEmitterType.END;
  61531. /**
  61532. * 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)
  61533. * Note: This only is supported when using an emitter of type Mesh
  61534. */
  61535. this.inheritDirection = false;
  61536. /**
  61537. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  61538. */
  61539. this.inheritedVelocityAmount = 0;
  61540. }
  61541. /**
  61542. * Clones the sub emitter
  61543. * @returns the cloned sub emitter
  61544. */
  61545. SubEmitter.prototype.clone = function () {
  61546. // Clone particle system
  61547. var emitter = this.particleSystem.emitter;
  61548. if (!emitter) {
  61549. emitter = new BABYLON.Vector3();
  61550. }
  61551. else if (emitter instanceof BABYLON.Vector3) {
  61552. emitter = emitter.clone();
  61553. }
  61554. else if (emitter instanceof BABYLON.AbstractMesh) {
  61555. emitter = new BABYLON.Mesh("", emitter.getScene());
  61556. emitter.isVisible = false;
  61557. }
  61558. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  61559. // Clone properties
  61560. clone.type = this.type;
  61561. clone.inheritDirection = this.inheritDirection;
  61562. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  61563. clone.particleSystem._disposeEmitterOnDispose = true;
  61564. clone.particleSystem.disposeOnStop = true;
  61565. return clone;
  61566. };
  61567. /**
  61568. * Serialize current object to a JSON object
  61569. * @returns the serialized object
  61570. */
  61571. SubEmitter.prototype.serialize = function () {
  61572. var serializationObject = {};
  61573. serializationObject.type = this.type;
  61574. serializationObject.inheritDirection = this.inheritDirection;
  61575. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  61576. serializationObject.particleSystem = this.particleSystem.serialize();
  61577. return serializationObject;
  61578. };
  61579. /**
  61580. * Creates a new SubEmitter from a serialized JSON version
  61581. * @param serializationObject defines the JSON object to read from
  61582. * @param scene defines the hosting scene
  61583. * @param rootUrl defines the rootUrl for data loading
  61584. * @returns a new SubEmitter
  61585. */
  61586. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  61587. var system = serializationObject.particleSystem;
  61588. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  61589. subEmitter.type = serializationObject.type;
  61590. subEmitter.inheritDirection = serializationObject.inheritDirection;
  61591. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  61592. subEmitter.particleSystem._isSubEmitter = true;
  61593. return subEmitter;
  61594. };
  61595. /** Release associated resources */
  61596. SubEmitter.prototype.dispose = function () {
  61597. this.particleSystem.dispose();
  61598. };
  61599. return SubEmitter;
  61600. }());
  61601. BABYLON.SubEmitter = SubEmitter;
  61602. })(BABYLON || (BABYLON = {}));
  61603. //# sourceMappingURL=babylon.subEmitter.js.map
  61604. var BABYLON;
  61605. (function (BABYLON) {
  61606. /**
  61607. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  61608. *
  61609. * This returned material effects how the mesh will look based on the code in the shaders.
  61610. *
  61611. * @see http://doc.babylonjs.com/how_to/shader_material
  61612. */
  61613. var ShaderMaterial = /** @class */ (function (_super) {
  61614. __extends(ShaderMaterial, _super);
  61615. /**
  61616. * Instantiate a new shader material.
  61617. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  61618. * This returned material effects how the mesh will look based on the code in the shaders.
  61619. * @see http://doc.babylonjs.com/how_to/shader_material
  61620. * @param name Define the name of the material in the scene
  61621. * @param scene Define the scene the material belongs to
  61622. * @param shaderPath Defines the route to the shader code in one of three ways:
  61623. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  61624. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  61625. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  61626. * @param options Define the options used to create the shader
  61627. */
  61628. function ShaderMaterial(name, scene, shaderPath, options) {
  61629. if (options === void 0) { options = {}; }
  61630. var _this = _super.call(this, name, scene) || this;
  61631. _this._textures = {};
  61632. _this._textureArrays = {};
  61633. _this._floats = {};
  61634. _this._ints = {};
  61635. _this._floatsArrays = {};
  61636. _this._colors3 = {};
  61637. _this._colors3Arrays = {};
  61638. _this._colors4 = {};
  61639. _this._vectors2 = {};
  61640. _this._vectors3 = {};
  61641. _this._vectors4 = {};
  61642. _this._matrices = {};
  61643. _this._matrices3x3 = {};
  61644. _this._matrices2x2 = {};
  61645. _this._vectors2Arrays = {};
  61646. _this._vectors3Arrays = {};
  61647. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  61648. _this._shaderPath = shaderPath;
  61649. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  61650. return _this;
  61651. }
  61652. /**
  61653. * Gets the current class name of the material e.g. "ShaderMaterial"
  61654. * Mainly use in serialization.
  61655. * @returns the class name
  61656. */
  61657. ShaderMaterial.prototype.getClassName = function () {
  61658. return "ShaderMaterial";
  61659. };
  61660. /**
  61661. * Specifies if the material will require alpha blending
  61662. * @returns a boolean specifying if alpha blending is needed
  61663. */
  61664. ShaderMaterial.prototype.needAlphaBlending = function () {
  61665. return (this.alpha < 1.0);
  61666. };
  61667. /**
  61668. * Specifies if this material should be rendered in alpha test mode
  61669. * @returns a boolean specifying if an alpha test is needed.
  61670. */
  61671. ShaderMaterial.prototype.needAlphaTesting = function () {
  61672. return this._options.needAlphaTesting;
  61673. };
  61674. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  61675. if (this._options.uniforms.indexOf(uniformName) === -1) {
  61676. this._options.uniforms.push(uniformName);
  61677. }
  61678. };
  61679. /**
  61680. * Set a texture in the shader.
  61681. * @param name Define the name of the uniform samplers as defined in the shader
  61682. * @param texture Define the texture to bind to this sampler
  61683. * @return the material itself allowing "fluent" like uniform updates
  61684. */
  61685. ShaderMaterial.prototype.setTexture = function (name, texture) {
  61686. if (this._options.samplers.indexOf(name) === -1) {
  61687. this._options.samplers.push(name);
  61688. }
  61689. this._textures[name] = texture;
  61690. return this;
  61691. };
  61692. /**
  61693. * Set a texture array in the shader.
  61694. * @param name Define the name of the uniform sampler array as defined in the shader
  61695. * @param textures Define the list of textures to bind to this sampler
  61696. * @return the material itself allowing "fluent" like uniform updates
  61697. */
  61698. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  61699. if (this._options.samplers.indexOf(name) === -1) {
  61700. this._options.samplers.push(name);
  61701. }
  61702. this._checkUniform(name);
  61703. this._textureArrays[name] = textures;
  61704. return this;
  61705. };
  61706. /**
  61707. * Set a float in the shader.
  61708. * @param name Define the name of the uniform as defined in the shader
  61709. * @param value Define the value to give to the uniform
  61710. * @return the material itself allowing "fluent" like uniform updates
  61711. */
  61712. ShaderMaterial.prototype.setFloat = function (name, value) {
  61713. this._checkUniform(name);
  61714. this._floats[name] = value;
  61715. return this;
  61716. };
  61717. /**
  61718. * Set a int in the shader.
  61719. * @param name Define the name of the uniform as defined in the shader
  61720. * @param value Define the value to give to the uniform
  61721. * @return the material itself allowing "fluent" like uniform updates
  61722. */
  61723. ShaderMaterial.prototype.setInt = function (name, value) {
  61724. this._checkUniform(name);
  61725. this._ints[name] = value;
  61726. return this;
  61727. };
  61728. /**
  61729. * Set an array of floats in the shader.
  61730. * @param name Define the name of the uniform as defined in the shader
  61731. * @param value Define the value to give to the uniform
  61732. * @return the material itself allowing "fluent" like uniform updates
  61733. */
  61734. ShaderMaterial.prototype.setFloats = function (name, value) {
  61735. this._checkUniform(name);
  61736. this._floatsArrays[name] = value;
  61737. return this;
  61738. };
  61739. /**
  61740. * Set a vec3 in the shader from a Color3.
  61741. * @param name Define the name of the uniform as defined in the shader
  61742. * @param value Define the value to give to the uniform
  61743. * @return the material itself allowing "fluent" like uniform updates
  61744. */
  61745. ShaderMaterial.prototype.setColor3 = function (name, value) {
  61746. this._checkUniform(name);
  61747. this._colors3[name] = value;
  61748. return this;
  61749. };
  61750. /**
  61751. * Set a vec3 array in the shader from a Color3 array.
  61752. * @param name Define the name of the uniform as defined in the shader
  61753. * @param value Define the value to give to the uniform
  61754. * @return the material itself allowing "fluent" like uniform updates
  61755. */
  61756. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  61757. this._checkUniform(name);
  61758. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  61759. color.toArray(arr, arr.length);
  61760. return arr;
  61761. }, []);
  61762. return this;
  61763. };
  61764. /**
  61765. * Set a vec4 in the shader from a Color4.
  61766. * @param name Define the name of the uniform as defined in the shader
  61767. * @param value Define the value to give to the uniform
  61768. * @return the material itself allowing "fluent" like uniform updates
  61769. */
  61770. ShaderMaterial.prototype.setColor4 = function (name, value) {
  61771. this._checkUniform(name);
  61772. this._colors4[name] = value;
  61773. return this;
  61774. };
  61775. /**
  61776. * Set a vec2 in the shader from a Vector2.
  61777. * @param name Define the name of the uniform as defined in the shader
  61778. * @param value Define the value to give to the uniform
  61779. * @return the material itself allowing "fluent" like uniform updates
  61780. */
  61781. ShaderMaterial.prototype.setVector2 = function (name, value) {
  61782. this._checkUniform(name);
  61783. this._vectors2[name] = value;
  61784. return this;
  61785. };
  61786. /**
  61787. * Set a vec3 in the shader from a Vector3.
  61788. * @param name Define the name of the uniform as defined in the shader
  61789. * @param value Define the value to give to the uniform
  61790. * @return the material itself allowing "fluent" like uniform updates
  61791. */
  61792. ShaderMaterial.prototype.setVector3 = function (name, value) {
  61793. this._checkUniform(name);
  61794. this._vectors3[name] = value;
  61795. return this;
  61796. };
  61797. /**
  61798. * Set a vec4 in the shader from a Vector4.
  61799. * @param name Define the name of the uniform as defined in the shader
  61800. * @param value Define the value to give to the uniform
  61801. * @return the material itself allowing "fluent" like uniform updates
  61802. */
  61803. ShaderMaterial.prototype.setVector4 = function (name, value) {
  61804. this._checkUniform(name);
  61805. this._vectors4[name] = value;
  61806. return this;
  61807. };
  61808. /**
  61809. * Set a mat4 in the shader from a Matrix.
  61810. * @param name Define the name of the uniform as defined in the shader
  61811. * @param value Define the value to give to the uniform
  61812. * @return the material itself allowing "fluent" like uniform updates
  61813. */
  61814. ShaderMaterial.prototype.setMatrix = function (name, value) {
  61815. this._checkUniform(name);
  61816. this._matrices[name] = value;
  61817. return this;
  61818. };
  61819. /**
  61820. * Set a mat3 in the shader from a Float32Array.
  61821. * @param name Define the name of the uniform as defined in the shader
  61822. * @param value Define the value to give to the uniform
  61823. * @return the material itself allowing "fluent" like uniform updates
  61824. */
  61825. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  61826. this._checkUniform(name);
  61827. this._matrices3x3[name] = value;
  61828. return this;
  61829. };
  61830. /**
  61831. * Set a mat2 in the shader from a Float32Array.
  61832. * @param name Define the name of the uniform as defined in the shader
  61833. * @param value Define the value to give to the uniform
  61834. * @return the material itself allowing "fluent" like uniform updates
  61835. */
  61836. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  61837. this._checkUniform(name);
  61838. this._matrices2x2[name] = value;
  61839. return this;
  61840. };
  61841. /**
  61842. * Set a vec2 array in the shader from a number array.
  61843. * @param name Define the name of the uniform as defined in the shader
  61844. * @param value Define the value to give to the uniform
  61845. * @return the material itself allowing "fluent" like uniform updates
  61846. */
  61847. ShaderMaterial.prototype.setArray2 = function (name, value) {
  61848. this._checkUniform(name);
  61849. this._vectors2Arrays[name] = value;
  61850. return this;
  61851. };
  61852. /**
  61853. * Set a vec3 array in the shader from a number array.
  61854. * @param name Define the name of the uniform as defined in the shader
  61855. * @param value Define the value to give to the uniform
  61856. * @return the material itself allowing "fluent" like uniform updates
  61857. */
  61858. ShaderMaterial.prototype.setArray3 = function (name, value) {
  61859. this._checkUniform(name);
  61860. this._vectors3Arrays[name] = value;
  61861. return this;
  61862. };
  61863. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  61864. if (!mesh) {
  61865. return true;
  61866. }
  61867. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  61868. return false;
  61869. }
  61870. return false;
  61871. };
  61872. /**
  61873. * Checks if the material is ready to render the requested mesh
  61874. * @param mesh Define the mesh to render
  61875. * @param useInstances Define whether or not the material is used with instances
  61876. * @returns true if ready, otherwise false
  61877. */
  61878. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  61879. var scene = this.getScene();
  61880. var engine = scene.getEngine();
  61881. if (!this.checkReadyOnEveryCall) {
  61882. if (this._renderId === scene.getRenderId()) {
  61883. if (this._checkCache(scene, mesh, useInstances)) {
  61884. return true;
  61885. }
  61886. }
  61887. }
  61888. // Instances
  61889. var defines = [];
  61890. var attribs = [];
  61891. var fallbacks = new BABYLON.EffectFallbacks();
  61892. for (var index = 0; index < this._options.defines.length; index++) {
  61893. defines.push(this._options.defines[index]);
  61894. }
  61895. for (var index = 0; index < this._options.attributes.length; index++) {
  61896. attribs.push(this._options.attributes[index]);
  61897. }
  61898. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  61899. attribs.push(BABYLON.VertexBuffer.ColorKind);
  61900. defines.push("#define VERTEXCOLOR");
  61901. }
  61902. if (useInstances) {
  61903. defines.push("#define INSTANCES");
  61904. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  61905. }
  61906. // Bones
  61907. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61908. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61909. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61910. if (mesh.numBoneInfluencers > 4) {
  61911. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61912. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61913. }
  61914. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61915. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61916. fallbacks.addCPUSkinningFallback(0, mesh);
  61917. if (this._options.uniforms.indexOf("mBones") === -1) {
  61918. this._options.uniforms.push("mBones");
  61919. }
  61920. }
  61921. else {
  61922. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61923. }
  61924. // Textures
  61925. for (var name in this._textures) {
  61926. if (!this._textures[name].isReady()) {
  61927. return false;
  61928. }
  61929. }
  61930. // Alpha test
  61931. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  61932. defines.push("#define ALPHATEST");
  61933. }
  61934. var previousEffect = this._effect;
  61935. var join = defines.join("\n");
  61936. this._effect = engine.createEffect(this._shaderPath, {
  61937. attributes: attribs,
  61938. uniformsNames: this._options.uniforms,
  61939. uniformBuffersNames: this._options.uniformBuffers,
  61940. samplers: this._options.samplers,
  61941. defines: join,
  61942. fallbacks: fallbacks,
  61943. onCompiled: this.onCompiled,
  61944. onError: this.onError
  61945. }, engine);
  61946. if (!this._effect.isReady()) {
  61947. return false;
  61948. }
  61949. if (previousEffect !== this._effect) {
  61950. scene.resetCachedMaterial();
  61951. }
  61952. this._renderId = scene.getRenderId();
  61953. return true;
  61954. };
  61955. /**
  61956. * Binds the world matrix to the material
  61957. * @param world defines the world transformation matrix
  61958. */
  61959. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  61960. var scene = this.getScene();
  61961. if (!this._effect) {
  61962. return;
  61963. }
  61964. if (this._options.uniforms.indexOf("world") !== -1) {
  61965. this._effect.setMatrix("world", world);
  61966. }
  61967. if (this._options.uniforms.indexOf("worldView") !== -1) {
  61968. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  61969. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  61970. }
  61971. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  61972. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  61973. }
  61974. };
  61975. /**
  61976. * Binds the material to the mesh
  61977. * @param world defines the world transformation matrix
  61978. * @param mesh defines the mesh to bind the material to
  61979. */
  61980. ShaderMaterial.prototype.bind = function (world, mesh) {
  61981. // Std values
  61982. this.bindOnlyWorldMatrix(world);
  61983. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  61984. if (this._options.uniforms.indexOf("view") !== -1) {
  61985. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  61986. }
  61987. if (this._options.uniforms.indexOf("projection") !== -1) {
  61988. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  61989. }
  61990. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  61991. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  61992. }
  61993. // Bones
  61994. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  61995. var name;
  61996. // Texture
  61997. for (name in this._textures) {
  61998. this._effect.setTexture(name, this._textures[name]);
  61999. }
  62000. // Texture arrays
  62001. for (name in this._textureArrays) {
  62002. this._effect.setTextureArray(name, this._textureArrays[name]);
  62003. }
  62004. // Int
  62005. for (name in this._ints) {
  62006. this._effect.setInt(name, this._ints[name]);
  62007. }
  62008. // Float
  62009. for (name in this._floats) {
  62010. this._effect.setFloat(name, this._floats[name]);
  62011. }
  62012. // Floats
  62013. for (name in this._floatsArrays) {
  62014. this._effect.setArray(name, this._floatsArrays[name]);
  62015. }
  62016. // Color3
  62017. for (name in this._colors3) {
  62018. this._effect.setColor3(name, this._colors3[name]);
  62019. }
  62020. for (name in this._colors3Arrays) {
  62021. this._effect.setArray3(name, this._colors3Arrays[name]);
  62022. }
  62023. // Color4
  62024. for (name in this._colors4) {
  62025. var color = this._colors4[name];
  62026. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62027. }
  62028. // Vector2
  62029. for (name in this._vectors2) {
  62030. this._effect.setVector2(name, this._vectors2[name]);
  62031. }
  62032. // Vector3
  62033. for (name in this._vectors3) {
  62034. this._effect.setVector3(name, this._vectors3[name]);
  62035. }
  62036. // Vector4
  62037. for (name in this._vectors4) {
  62038. this._effect.setVector4(name, this._vectors4[name]);
  62039. }
  62040. // Matrix
  62041. for (name in this._matrices) {
  62042. this._effect.setMatrix(name, this._matrices[name]);
  62043. }
  62044. // Matrix 3x3
  62045. for (name in this._matrices3x3) {
  62046. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  62047. }
  62048. // Matrix 2x2
  62049. for (name in this._matrices2x2) {
  62050. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  62051. }
  62052. // Vector2Array
  62053. for (name in this._vectors2Arrays) {
  62054. this._effect.setArray2(name, this._vectors2Arrays[name]);
  62055. }
  62056. // Vector3Array
  62057. for (name in this._vectors3Arrays) {
  62058. this._effect.setArray3(name, this._vectors3Arrays[name]);
  62059. }
  62060. }
  62061. this._afterBind(mesh);
  62062. };
  62063. /**
  62064. * Gets the active textures from the material
  62065. * @returns an array of textures
  62066. */
  62067. ShaderMaterial.prototype.getActiveTextures = function () {
  62068. var activeTextures = _super.prototype.getActiveTextures.call(this);
  62069. for (var name in this._textures) {
  62070. activeTextures.push(this._textures[name]);
  62071. }
  62072. for (var name in this._textureArrays) {
  62073. var array = this._textureArrays[name];
  62074. for (var index = 0; index < array.length; index++) {
  62075. activeTextures.push(array[index]);
  62076. }
  62077. }
  62078. return activeTextures;
  62079. };
  62080. /**
  62081. * Specifies if the material uses a texture
  62082. * @param texture defines the texture to check against the material
  62083. * @returns a boolean specifying if the material uses the texture
  62084. */
  62085. ShaderMaterial.prototype.hasTexture = function (texture) {
  62086. if (_super.prototype.hasTexture.call(this, texture)) {
  62087. return true;
  62088. }
  62089. for (var name in this._textures) {
  62090. if (this._textures[name] === texture) {
  62091. return true;
  62092. }
  62093. }
  62094. for (var name in this._textureArrays) {
  62095. var array = this._textureArrays[name];
  62096. for (var index = 0; index < array.length; index++) {
  62097. if (array[index] === texture) {
  62098. return true;
  62099. }
  62100. }
  62101. }
  62102. return false;
  62103. };
  62104. /**
  62105. * Makes a duplicate of the material, and gives it a new name
  62106. * @param name defines the new name for the duplicated material
  62107. * @returns the cloned material
  62108. */
  62109. ShaderMaterial.prototype.clone = function (name) {
  62110. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  62111. return newShaderMaterial;
  62112. };
  62113. /**
  62114. * Disposes the material
  62115. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  62116. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  62117. */
  62118. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62119. if (forceDisposeTextures) {
  62120. var name;
  62121. for (name in this._textures) {
  62122. this._textures[name].dispose();
  62123. }
  62124. for (name in this._textureArrays) {
  62125. var array = this._textureArrays[name];
  62126. for (var index = 0; index < array.length; index++) {
  62127. array[index].dispose();
  62128. }
  62129. }
  62130. }
  62131. this._textures = {};
  62132. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62133. };
  62134. /**
  62135. * Serializes this material in a JSON representation
  62136. * @returns the serialized material object
  62137. */
  62138. ShaderMaterial.prototype.serialize = function () {
  62139. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62140. serializationObject.customType = "BABYLON.ShaderMaterial";
  62141. serializationObject.options = this._options;
  62142. serializationObject.shaderPath = this._shaderPath;
  62143. var name;
  62144. // Texture
  62145. serializationObject.textures = {};
  62146. for (name in this._textures) {
  62147. serializationObject.textures[name] = this._textures[name].serialize();
  62148. }
  62149. // Texture arrays
  62150. serializationObject.textureArrays = {};
  62151. for (name in this._textureArrays) {
  62152. serializationObject.textureArrays[name] = [];
  62153. var array = this._textureArrays[name];
  62154. for (var index = 0; index < array.length; index++) {
  62155. serializationObject.textureArrays[name].push(array[index].serialize());
  62156. }
  62157. }
  62158. // Float
  62159. serializationObject.floats = {};
  62160. for (name in this._floats) {
  62161. serializationObject.floats[name] = this._floats[name];
  62162. }
  62163. // Float s
  62164. serializationObject.FloatArrays = {};
  62165. for (name in this._floatsArrays) {
  62166. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  62167. }
  62168. // Color3
  62169. serializationObject.colors3 = {};
  62170. for (name in this._colors3) {
  62171. serializationObject.colors3[name] = this._colors3[name].asArray();
  62172. }
  62173. // Color3 array
  62174. serializationObject.colors3Arrays = {};
  62175. for (name in this._colors3Arrays) {
  62176. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  62177. }
  62178. // Color4
  62179. serializationObject.colors4 = {};
  62180. for (name in this._colors4) {
  62181. serializationObject.colors4[name] = this._colors4[name].asArray();
  62182. }
  62183. // Vector2
  62184. serializationObject.vectors2 = {};
  62185. for (name in this._vectors2) {
  62186. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  62187. }
  62188. // Vector3
  62189. serializationObject.vectors3 = {};
  62190. for (name in this._vectors3) {
  62191. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  62192. }
  62193. // Vector4
  62194. serializationObject.vectors4 = {};
  62195. for (name in this._vectors4) {
  62196. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  62197. }
  62198. // Matrix
  62199. serializationObject.matrices = {};
  62200. for (name in this._matrices) {
  62201. serializationObject.matrices[name] = this._matrices[name].asArray();
  62202. }
  62203. // Matrix 3x3
  62204. serializationObject.matrices3x3 = {};
  62205. for (name in this._matrices3x3) {
  62206. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  62207. }
  62208. // Matrix 2x2
  62209. serializationObject.matrices2x2 = {};
  62210. for (name in this._matrices2x2) {
  62211. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  62212. }
  62213. // Vector2Array
  62214. serializationObject.vectors2Arrays = {};
  62215. for (name in this._vectors2Arrays) {
  62216. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  62217. }
  62218. // Vector3Array
  62219. serializationObject.vectors3Arrays = {};
  62220. for (name in this._vectors3Arrays) {
  62221. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  62222. }
  62223. return serializationObject;
  62224. };
  62225. /**
  62226. * Creates a shader material from parsed shader material data
  62227. * @param source defines the JSON represnetation of the material
  62228. * @param scene defines the hosting scene
  62229. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  62230. * @returns a new material
  62231. */
  62232. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  62233. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  62234. var name;
  62235. // Texture
  62236. for (name in source.textures) {
  62237. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  62238. }
  62239. // Texture arrays
  62240. for (name in source.textureArrays) {
  62241. var array = source.textureArrays[name];
  62242. var textureArray = new Array();
  62243. for (var index = 0; index < array.length; index++) {
  62244. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  62245. }
  62246. material.setTextureArray(name, textureArray);
  62247. }
  62248. // Float
  62249. for (name in source.floats) {
  62250. material.setFloat(name, source.floats[name]);
  62251. }
  62252. // Float s
  62253. for (name in source.floatsArrays) {
  62254. material.setFloats(name, source.floatsArrays[name]);
  62255. }
  62256. // Color3
  62257. for (name in source.colors3) {
  62258. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  62259. }
  62260. // Color3 arrays
  62261. for (name in source.colors3Arrays) {
  62262. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  62263. if (i % 3 === 0) {
  62264. arr.push([num]);
  62265. }
  62266. else {
  62267. arr[arr.length - 1].push(num);
  62268. }
  62269. return arr;
  62270. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  62271. material.setColor3Array(name, colors);
  62272. }
  62273. // Color4
  62274. for (name in source.colors4) {
  62275. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  62276. }
  62277. // Vector2
  62278. for (name in source.vectors2) {
  62279. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  62280. }
  62281. // Vector3
  62282. for (name in source.vectors3) {
  62283. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  62284. }
  62285. // Vector4
  62286. for (name in source.vectors4) {
  62287. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  62288. }
  62289. // Matrix
  62290. for (name in source.matrices) {
  62291. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  62292. }
  62293. // Matrix 3x3
  62294. for (name in source.matrices3x3) {
  62295. material.setMatrix3x3(name, source.matrices3x3[name]);
  62296. }
  62297. // Matrix 2x2
  62298. for (name in source.matrices2x2) {
  62299. material.setMatrix2x2(name, source.matrices2x2[name]);
  62300. }
  62301. // Vector2Array
  62302. for (name in source.vectors2Arrays) {
  62303. material.setArray2(name, source.vectors2Arrays[name]);
  62304. }
  62305. // Vector3Array
  62306. for (name in source.vectors3Arrays) {
  62307. material.setArray3(name, source.vectors3Arrays[name]);
  62308. }
  62309. return material;
  62310. };
  62311. return ShaderMaterial;
  62312. }(BABYLON.Material));
  62313. BABYLON.ShaderMaterial = ShaderMaterial;
  62314. })(BABYLON || (BABYLON = {}));
  62315. //# sourceMappingURL=babylon.shaderMaterial.js.map
  62316. var BABYLON;
  62317. (function (BABYLON) {
  62318. var GroundMesh = /** @class */ (function (_super) {
  62319. __extends(GroundMesh, _super);
  62320. function GroundMesh(name, scene) {
  62321. var _this = _super.call(this, name, scene) || this;
  62322. _this.generateOctree = false;
  62323. return _this;
  62324. }
  62325. GroundMesh.prototype.getClassName = function () {
  62326. return "GroundMesh";
  62327. };
  62328. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  62329. get: function () {
  62330. return Math.min(this._subdivisionsX, this._subdivisionsY);
  62331. },
  62332. enumerable: true,
  62333. configurable: true
  62334. });
  62335. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  62336. get: function () {
  62337. return this._subdivisionsX;
  62338. },
  62339. enumerable: true,
  62340. configurable: true
  62341. });
  62342. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  62343. get: function () {
  62344. return this._subdivisionsY;
  62345. },
  62346. enumerable: true,
  62347. configurable: true
  62348. });
  62349. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  62350. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  62351. this._subdivisionsX = chunksCount;
  62352. this._subdivisionsY = chunksCount;
  62353. this.subdivide(chunksCount);
  62354. // Call the octree system optimization if it is defined.
  62355. var thisAsAny = this;
  62356. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  62357. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  62358. }
  62359. };
  62360. /**
  62361. * Returns a height (y) value in the Worl system :
  62362. * the ground altitude at the coordinates (x, z) expressed in the World system.
  62363. * Returns the ground y position if (x, z) are outside the ground surface.
  62364. */
  62365. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  62366. var world = this.getWorldMatrix();
  62367. var invMat = BABYLON.Tmp.Matrix[5];
  62368. world.invertToRef(invMat);
  62369. var tmpVect = BABYLON.Tmp.Vector3[8];
  62370. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  62371. x = tmpVect.x;
  62372. z = tmpVect.z;
  62373. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  62374. return this.position.y;
  62375. }
  62376. if (!this._heightQuads || this._heightQuads.length == 0) {
  62377. this._initHeightQuads();
  62378. this._computeHeightQuads();
  62379. }
  62380. var facet = this._getFacetAt(x, z);
  62381. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  62382. // return y in the World system
  62383. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  62384. return tmpVect.y;
  62385. };
  62386. /**
  62387. * Returns a normalized vector (Vector3) orthogonal to the ground
  62388. * at the ground coordinates (x, z) expressed in the World system.
  62389. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  62390. */
  62391. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  62392. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  62393. this.getNormalAtCoordinatesToRef(x, z, normal);
  62394. return normal;
  62395. };
  62396. /**
  62397. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  62398. * at the ground coordinates (x, z) expressed in the World system.
  62399. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  62400. * Returns the GroundMesh.
  62401. */
  62402. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  62403. var world = this.getWorldMatrix();
  62404. var tmpMat = BABYLON.Tmp.Matrix[5];
  62405. world.invertToRef(tmpMat);
  62406. var tmpVect = BABYLON.Tmp.Vector3[8];
  62407. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  62408. x = tmpVect.x;
  62409. z = tmpVect.z;
  62410. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  62411. return this;
  62412. }
  62413. if (!this._heightQuads || this._heightQuads.length == 0) {
  62414. this._initHeightQuads();
  62415. this._computeHeightQuads();
  62416. }
  62417. var facet = this._getFacetAt(x, z);
  62418. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  62419. return this;
  62420. };
  62421. /**
  62422. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  62423. * if the ground has been updated.
  62424. * This can be used in the render loop.
  62425. * Returns the GroundMesh.
  62426. */
  62427. GroundMesh.prototype.updateCoordinateHeights = function () {
  62428. if (!this._heightQuads || this._heightQuads.length == 0) {
  62429. this._initHeightQuads();
  62430. }
  62431. this._computeHeightQuads();
  62432. return this;
  62433. };
  62434. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  62435. GroundMesh.prototype._getFacetAt = function (x, z) {
  62436. // retrieve col and row from x, z coordinates in the ground local system
  62437. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  62438. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  62439. var quad = this._heightQuads[row * this._subdivisionsX + col];
  62440. var facet;
  62441. if (z < quad.slope.x * x + quad.slope.y) {
  62442. facet = quad.facet1;
  62443. }
  62444. else {
  62445. facet = quad.facet2;
  62446. }
  62447. return facet;
  62448. };
  62449. // Creates and populates the heightMap array with "facet" elements :
  62450. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  62451. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  62452. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  62453. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  62454. // Returns the GroundMesh.
  62455. GroundMesh.prototype._initHeightQuads = function () {
  62456. var subdivisionsX = this._subdivisionsX;
  62457. var subdivisionsY = this._subdivisionsY;
  62458. this._heightQuads = new Array();
  62459. for (var row = 0; row < subdivisionsY; row++) {
  62460. for (var col = 0; col < subdivisionsX; col++) {
  62461. 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) };
  62462. this._heightQuads[row * subdivisionsX + col] = quad;
  62463. }
  62464. }
  62465. return this;
  62466. };
  62467. // Compute each quad element values and update the the heightMap array :
  62468. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  62469. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  62470. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  62471. // Returns the GroundMesh.
  62472. GroundMesh.prototype._computeHeightQuads = function () {
  62473. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62474. if (!positions) {
  62475. return this;
  62476. }
  62477. var v1 = BABYLON.Tmp.Vector3[3];
  62478. var v2 = BABYLON.Tmp.Vector3[2];
  62479. var v3 = BABYLON.Tmp.Vector3[1];
  62480. var v4 = BABYLON.Tmp.Vector3[0];
  62481. var v1v2 = BABYLON.Tmp.Vector3[4];
  62482. var v1v3 = BABYLON.Tmp.Vector3[5];
  62483. var v1v4 = BABYLON.Tmp.Vector3[6];
  62484. var norm1 = BABYLON.Tmp.Vector3[7];
  62485. var norm2 = BABYLON.Tmp.Vector3[8];
  62486. var i = 0;
  62487. var j = 0;
  62488. var k = 0;
  62489. var cd = 0; // 2D slope coefficient : z = cd * x + h
  62490. var h = 0;
  62491. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  62492. var d2 = 0;
  62493. var subdivisionsX = this._subdivisionsX;
  62494. var subdivisionsY = this._subdivisionsY;
  62495. for (var row = 0; row < subdivisionsY; row++) {
  62496. for (var col = 0; col < subdivisionsX; col++) {
  62497. i = col * 3;
  62498. j = row * (subdivisionsX + 1) * 3;
  62499. k = (row + 1) * (subdivisionsX + 1) * 3;
  62500. v1.x = positions[j + i];
  62501. v1.y = positions[j + i + 1];
  62502. v1.z = positions[j + i + 2];
  62503. v2.x = positions[j + i + 3];
  62504. v2.y = positions[j + i + 4];
  62505. v2.z = positions[j + i + 5];
  62506. v3.x = positions[k + i];
  62507. v3.y = positions[k + i + 1];
  62508. v3.z = positions[k + i + 2];
  62509. v4.x = positions[k + i + 3];
  62510. v4.y = positions[k + i + 4];
  62511. v4.z = positions[k + i + 5];
  62512. // 2D slope V1V4
  62513. cd = (v4.z - v1.z) / (v4.x - v1.x);
  62514. h = v1.z - cd * v1.x; // v1 belongs to the slope
  62515. // facet equations :
  62516. // we compute each facet normal vector
  62517. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  62518. // we compute the value d by applying the equation to v1 which belongs to the plane
  62519. // then we store the facet equation in a Vector4
  62520. v2.subtractToRef(v1, v1v2);
  62521. v3.subtractToRef(v1, v1v3);
  62522. v4.subtractToRef(v1, v1v4);
  62523. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  62524. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  62525. norm1.normalize();
  62526. norm2.normalize();
  62527. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  62528. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  62529. var quad = this._heightQuads[row * subdivisionsX + col];
  62530. quad.slope.copyFromFloats(cd, h);
  62531. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  62532. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  62533. }
  62534. }
  62535. return this;
  62536. };
  62537. GroundMesh.prototype.serialize = function (serializationObject) {
  62538. _super.prototype.serialize.call(this, serializationObject);
  62539. serializationObject.subdivisionsX = this._subdivisionsX;
  62540. serializationObject.subdivisionsY = this._subdivisionsY;
  62541. serializationObject.minX = this._minX;
  62542. serializationObject.maxX = this._maxX;
  62543. serializationObject.minZ = this._minZ;
  62544. serializationObject.maxZ = this._maxZ;
  62545. serializationObject.width = this._width;
  62546. serializationObject.height = this._height;
  62547. };
  62548. GroundMesh.Parse = function (parsedMesh, scene) {
  62549. var result = new GroundMesh(parsedMesh.name, scene);
  62550. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  62551. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  62552. result._minX = parsedMesh.minX;
  62553. result._maxX = parsedMesh.maxX;
  62554. result._minZ = parsedMesh.minZ;
  62555. result._maxZ = parsedMesh.maxZ;
  62556. result._width = parsedMesh.width;
  62557. result._height = parsedMesh.height;
  62558. return result;
  62559. };
  62560. return GroundMesh;
  62561. }(BABYLON.Mesh));
  62562. BABYLON.GroundMesh = GroundMesh;
  62563. })(BABYLON || (BABYLON = {}));
  62564. //# sourceMappingURL=babylon.groundMesh.js.map
  62565. var BABYLON;
  62566. (function (BABYLON) {
  62567. /**
  62568. * Creates an instance based on a source mesh.
  62569. */
  62570. var InstancedMesh = /** @class */ (function (_super) {
  62571. __extends(InstancedMesh, _super);
  62572. function InstancedMesh(name, source) {
  62573. var _this = _super.call(this, name, source.getScene()) || this;
  62574. source.instances.push(_this);
  62575. _this._sourceMesh = source;
  62576. _this.position.copyFrom(source.position);
  62577. _this.rotation.copyFrom(source.rotation);
  62578. _this.scaling.copyFrom(source.scaling);
  62579. if (source.rotationQuaternion) {
  62580. _this.rotationQuaternion = source.rotationQuaternion.clone();
  62581. }
  62582. _this.infiniteDistance = source.infiniteDistance;
  62583. _this.setPivotMatrix(source.getPivotMatrix());
  62584. _this.refreshBoundingInfo();
  62585. _this._syncSubMeshes();
  62586. return _this;
  62587. }
  62588. /**
  62589. * Returns the string "InstancedMesh".
  62590. */
  62591. InstancedMesh.prototype.getClassName = function () {
  62592. return "InstancedMesh";
  62593. };
  62594. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  62595. // Methods
  62596. get: function () {
  62597. return this._sourceMesh.receiveShadows;
  62598. },
  62599. enumerable: true,
  62600. configurable: true
  62601. });
  62602. Object.defineProperty(InstancedMesh.prototype, "material", {
  62603. get: function () {
  62604. return this._sourceMesh.material;
  62605. },
  62606. enumerable: true,
  62607. configurable: true
  62608. });
  62609. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  62610. get: function () {
  62611. return this._sourceMesh.visibility;
  62612. },
  62613. enumerable: true,
  62614. configurable: true
  62615. });
  62616. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  62617. get: function () {
  62618. return this._sourceMesh.skeleton;
  62619. },
  62620. enumerable: true,
  62621. configurable: true
  62622. });
  62623. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  62624. get: function () {
  62625. return this._sourceMesh.renderingGroupId;
  62626. },
  62627. set: function (value) {
  62628. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  62629. return;
  62630. }
  62631. //no-op with warning
  62632. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  62633. },
  62634. enumerable: true,
  62635. configurable: true
  62636. });
  62637. /**
  62638. * Returns the total number of vertices (integer).
  62639. */
  62640. InstancedMesh.prototype.getTotalVertices = function () {
  62641. return this._sourceMesh.getTotalVertices();
  62642. };
  62643. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  62644. get: function () {
  62645. return this._sourceMesh;
  62646. },
  62647. enumerable: true,
  62648. configurable: true
  62649. });
  62650. /**
  62651. * Is this node ready to be used/rendered
  62652. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  62653. * @return {boolean} is it ready
  62654. */
  62655. InstancedMesh.prototype.isReady = function (completeCheck) {
  62656. if (completeCheck === void 0) { completeCheck = false; }
  62657. return this._sourceMesh.isReady(completeCheck, true);
  62658. };
  62659. /**
  62660. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  62661. */
  62662. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  62663. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  62664. };
  62665. /**
  62666. * Sets the vertex data of the mesh geometry for the requested `kind`.
  62667. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  62668. * The `data` are either a numeric array either a Float32Array.
  62669. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  62670. * 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).
  62671. * Note that a new underlying VertexBuffer object is created each call.
  62672. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  62673. *
  62674. * Possible `kind` values :
  62675. * - BABYLON.VertexBuffer.PositionKind
  62676. * - BABYLON.VertexBuffer.UVKind
  62677. * - BABYLON.VertexBuffer.UV2Kind
  62678. * - BABYLON.VertexBuffer.UV3Kind
  62679. * - BABYLON.VertexBuffer.UV4Kind
  62680. * - BABYLON.VertexBuffer.UV5Kind
  62681. * - BABYLON.VertexBuffer.UV6Kind
  62682. * - BABYLON.VertexBuffer.ColorKind
  62683. * - BABYLON.VertexBuffer.MatricesIndicesKind
  62684. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  62685. * - BABYLON.VertexBuffer.MatricesWeightsKind
  62686. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  62687. *
  62688. * Returns the Mesh.
  62689. */
  62690. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  62691. if (this.sourceMesh) {
  62692. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  62693. }
  62694. return this.sourceMesh;
  62695. };
  62696. /**
  62697. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  62698. * If the mesh has no geometry, it is simply returned as it is.
  62699. * The `data` are either a numeric array either a Float32Array.
  62700. * No new underlying VertexBuffer object is created.
  62701. * 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.
  62702. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  62703. *
  62704. * Possible `kind` values :
  62705. * - BABYLON.VertexBuffer.PositionKind
  62706. * - BABYLON.VertexBuffer.UVKind
  62707. * - BABYLON.VertexBuffer.UV2Kind
  62708. * - BABYLON.VertexBuffer.UV3Kind
  62709. * - BABYLON.VertexBuffer.UV4Kind
  62710. * - BABYLON.VertexBuffer.UV5Kind
  62711. * - BABYLON.VertexBuffer.UV6Kind
  62712. * - BABYLON.VertexBuffer.ColorKind
  62713. * - BABYLON.VertexBuffer.MatricesIndicesKind
  62714. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  62715. * - BABYLON.VertexBuffer.MatricesWeightsKind
  62716. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  62717. *
  62718. * Returns the Mesh.
  62719. */
  62720. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  62721. if (this.sourceMesh) {
  62722. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  62723. }
  62724. return this.sourceMesh;
  62725. };
  62726. /**
  62727. * Sets the mesh indices.
  62728. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  62729. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  62730. * This method creates a new index buffer each call.
  62731. * Returns the Mesh.
  62732. */
  62733. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  62734. if (totalVertices === void 0) { totalVertices = null; }
  62735. if (this.sourceMesh) {
  62736. this.sourceMesh.setIndices(indices, totalVertices);
  62737. }
  62738. return this.sourceMesh;
  62739. };
  62740. /**
  62741. * Boolean : True if the mesh owns the requested kind of data.
  62742. */
  62743. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  62744. return this._sourceMesh.isVerticesDataPresent(kind);
  62745. };
  62746. /**
  62747. * Returns an array of indices (IndicesArray).
  62748. */
  62749. InstancedMesh.prototype.getIndices = function () {
  62750. return this._sourceMesh.getIndices();
  62751. };
  62752. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  62753. get: function () {
  62754. return this._sourceMesh._positions;
  62755. },
  62756. enumerable: true,
  62757. configurable: true
  62758. });
  62759. /**
  62760. * Sets a new updated BoundingInfo to the mesh.
  62761. * Returns the mesh.
  62762. */
  62763. InstancedMesh.prototype.refreshBoundingInfo = function () {
  62764. var meshBB = this._sourceMesh.getBoundingInfo();
  62765. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  62766. this._updateBoundingInfo();
  62767. return this;
  62768. };
  62769. /** @hidden */
  62770. InstancedMesh.prototype._preActivate = function () {
  62771. if (this._currentLOD) {
  62772. this._currentLOD._preActivate();
  62773. }
  62774. return this;
  62775. };
  62776. /** @hidden */
  62777. InstancedMesh.prototype._activate = function (renderId) {
  62778. if (this._currentLOD) {
  62779. this._currentLOD._registerInstanceForRenderId(this, renderId);
  62780. }
  62781. return this;
  62782. };
  62783. /**
  62784. * Returns the current associated LOD AbstractMesh.
  62785. */
  62786. InstancedMesh.prototype.getLOD = function (camera) {
  62787. if (!camera) {
  62788. return this;
  62789. }
  62790. var boundingInfo = this.getBoundingInfo();
  62791. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  62792. if (this._currentLOD === this.sourceMesh) {
  62793. return this;
  62794. }
  62795. return this._currentLOD;
  62796. };
  62797. /** @hidden */
  62798. InstancedMesh.prototype._syncSubMeshes = function () {
  62799. this.releaseSubMeshes();
  62800. if (this._sourceMesh.subMeshes) {
  62801. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  62802. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  62803. }
  62804. }
  62805. return this;
  62806. };
  62807. /** @hidden */
  62808. InstancedMesh.prototype._generatePointsArray = function () {
  62809. return this._sourceMesh._generatePointsArray();
  62810. };
  62811. /**
  62812. * Creates a new InstancedMesh from the current mesh.
  62813. * - name (string) : the cloned mesh name
  62814. * - newParent (optional Node) : the optional Node to parent the clone to.
  62815. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  62816. *
  62817. * Returns the clone.
  62818. */
  62819. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  62820. var result = this._sourceMesh.createInstance(name);
  62821. // Deep copy
  62822. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  62823. // Bounding info
  62824. this.refreshBoundingInfo();
  62825. // Parent
  62826. if (newParent) {
  62827. result.parent = newParent;
  62828. }
  62829. if (!doNotCloneChildren) {
  62830. // Children
  62831. for (var index = 0; index < this.getScene().meshes.length; index++) {
  62832. var mesh = this.getScene().meshes[index];
  62833. if (mesh.parent === this) {
  62834. mesh.clone(mesh.name, result);
  62835. }
  62836. }
  62837. }
  62838. result.computeWorldMatrix(true);
  62839. return result;
  62840. };
  62841. /**
  62842. * Disposes the InstancedMesh.
  62843. * Returns nothing.
  62844. */
  62845. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  62846. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  62847. // Remove from mesh
  62848. var index = this._sourceMesh.instances.indexOf(this);
  62849. this._sourceMesh.instances.splice(index, 1);
  62850. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  62851. };
  62852. return InstancedMesh;
  62853. }(BABYLON.AbstractMesh));
  62854. BABYLON.InstancedMesh = InstancedMesh;
  62855. })(BABYLON || (BABYLON = {}));
  62856. //# sourceMappingURL=babylon.instancedMesh.js.map
  62857. var BABYLON;
  62858. (function (BABYLON) {
  62859. var LinesMesh = /** @class */ (function (_super) {
  62860. __extends(LinesMesh, _super);
  62861. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  62862. if (scene === void 0) { scene = null; }
  62863. if (parent === void 0) { parent = null; }
  62864. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  62865. _this.useVertexColor = useVertexColor;
  62866. _this.useVertexAlpha = useVertexAlpha;
  62867. _this.color = new BABYLON.Color3(1, 1, 1);
  62868. _this.alpha = 1;
  62869. if (source) {
  62870. _this.color = source.color.clone();
  62871. _this.alpha = source.alpha;
  62872. _this.useVertexColor = source.useVertexColor;
  62873. _this.useVertexAlpha = source.useVertexAlpha;
  62874. }
  62875. _this._intersectionThreshold = 0.1;
  62876. var defines = [];
  62877. var options = {
  62878. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  62879. uniforms: ["world", "viewProjection"],
  62880. needAlphaBlending: true,
  62881. defines: defines
  62882. };
  62883. if (useVertexAlpha === false) {
  62884. options.needAlphaBlending = false;
  62885. }
  62886. if (!useVertexColor) {
  62887. options.uniforms.push("color");
  62888. }
  62889. else {
  62890. options.defines.push("#define VERTEXCOLOR");
  62891. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  62892. }
  62893. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  62894. return _this;
  62895. }
  62896. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  62897. /**
  62898. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62899. * This margin is expressed in world space coordinates, so its value may vary.
  62900. * Default value is 0.1
  62901. * @returns the intersection Threshold value.
  62902. */
  62903. get: function () {
  62904. return this._intersectionThreshold;
  62905. },
  62906. /**
  62907. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62908. * This margin is expressed in world space coordinates, so its value may vary.
  62909. * @param value the new threshold to apply
  62910. */
  62911. set: function (value) {
  62912. if (this._intersectionThreshold === value) {
  62913. return;
  62914. }
  62915. this._intersectionThreshold = value;
  62916. if (this.geometry) {
  62917. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  62918. }
  62919. },
  62920. enumerable: true,
  62921. configurable: true
  62922. });
  62923. /**
  62924. * Returns the string "LineMesh"
  62925. */
  62926. LinesMesh.prototype.getClassName = function () {
  62927. return "LinesMesh";
  62928. };
  62929. Object.defineProperty(LinesMesh.prototype, "material", {
  62930. /**
  62931. * @hidden
  62932. */
  62933. get: function () {
  62934. return this._colorShader;
  62935. },
  62936. /**
  62937. * @hidden
  62938. */
  62939. set: function (value) {
  62940. // Do nothing
  62941. },
  62942. enumerable: true,
  62943. configurable: true
  62944. });
  62945. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  62946. /**
  62947. * @hidden
  62948. */
  62949. get: function () {
  62950. return false;
  62951. },
  62952. enumerable: true,
  62953. configurable: true
  62954. });
  62955. /** @hidden */
  62956. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  62957. if (!this._geometry) {
  62958. return this;
  62959. }
  62960. // VBOs
  62961. this._geometry._bind(this._colorShader.getEffect());
  62962. // Color
  62963. if (!this.useVertexColor) {
  62964. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  62965. }
  62966. return this;
  62967. };
  62968. /** @hidden */
  62969. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  62970. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  62971. return this;
  62972. }
  62973. var engine = this.getScene().getEngine();
  62974. // Draw order
  62975. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  62976. return this;
  62977. };
  62978. LinesMesh.prototype.dispose = function (doNotRecurse) {
  62979. this._colorShader.dispose();
  62980. _super.prototype.dispose.call(this, doNotRecurse);
  62981. };
  62982. /**
  62983. * Returns a new LineMesh object cloned from the current one.
  62984. */
  62985. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  62986. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  62987. };
  62988. return LinesMesh;
  62989. }(BABYLON.Mesh));
  62990. BABYLON.LinesMesh = LinesMesh;
  62991. })(BABYLON || (BABYLON = {}));
  62992. //# sourceMappingURL=babylon.linesMesh.js.map
  62993. var BABYLON;
  62994. (function (BABYLON) {
  62995. /**
  62996. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62997. * The underlying implementation relies on an associative array to ensure the best performances.
  62998. * The value can be anything including 'null' but except 'undefined'
  62999. */
  63000. var StringDictionary = /** @class */ (function () {
  63001. function StringDictionary() {
  63002. this._count = 0;
  63003. this._data = {};
  63004. }
  63005. /**
  63006. * This will clear this dictionary and copy the content from the 'source' one.
  63007. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63008. * @param source the dictionary to take the content from and copy to this dictionary
  63009. */
  63010. StringDictionary.prototype.copyFrom = function (source) {
  63011. var _this = this;
  63012. this.clear();
  63013. source.forEach(function (t, v) { return _this.add(t, v); });
  63014. };
  63015. /**
  63016. * Get a value based from its key
  63017. * @param key the given key to get the matching value from
  63018. * @return the value if found, otherwise undefined is returned
  63019. */
  63020. StringDictionary.prototype.get = function (key) {
  63021. var val = this._data[key];
  63022. if (val !== undefined) {
  63023. return val;
  63024. }
  63025. return undefined;
  63026. };
  63027. /**
  63028. * Get a value from its key or add it if it doesn't exist.
  63029. * This method will ensure you that a given key/data will be present in the dictionary.
  63030. * @param key the given key to get the matching value from
  63031. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63032. * The factory will only be invoked if there's no data for the given key.
  63033. * @return the value corresponding to the key.
  63034. */
  63035. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63036. var val = this.get(key);
  63037. if (val !== undefined) {
  63038. return val;
  63039. }
  63040. val = factory(key);
  63041. if (val) {
  63042. this.add(key, val);
  63043. }
  63044. return val;
  63045. };
  63046. /**
  63047. * Get a value from its key if present in the dictionary otherwise add it
  63048. * @param key the key to get the value from
  63049. * @param val if there's no such key/value pair in the dictionary add it with this value
  63050. * @return the value corresponding to the key
  63051. */
  63052. StringDictionary.prototype.getOrAdd = function (key, val) {
  63053. var curVal = this.get(key);
  63054. if (curVal !== undefined) {
  63055. return curVal;
  63056. }
  63057. this.add(key, val);
  63058. return val;
  63059. };
  63060. /**
  63061. * Check if there's a given key in the dictionary
  63062. * @param key the key to check for
  63063. * @return true if the key is present, false otherwise
  63064. */
  63065. StringDictionary.prototype.contains = function (key) {
  63066. return this._data[key] !== undefined;
  63067. };
  63068. /**
  63069. * Add a new key and its corresponding value
  63070. * @param key the key to add
  63071. * @param value the value corresponding to the key
  63072. * @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
  63073. */
  63074. StringDictionary.prototype.add = function (key, value) {
  63075. if (this._data[key] !== undefined) {
  63076. return false;
  63077. }
  63078. this._data[key] = value;
  63079. ++this._count;
  63080. return true;
  63081. };
  63082. StringDictionary.prototype.set = function (key, value) {
  63083. if (this._data[key] === undefined) {
  63084. return false;
  63085. }
  63086. this._data[key] = value;
  63087. return true;
  63088. };
  63089. /**
  63090. * Get the element of the given key and remove it from the dictionary
  63091. * @param key
  63092. */
  63093. StringDictionary.prototype.getAndRemove = function (key) {
  63094. var val = this.get(key);
  63095. if (val !== undefined) {
  63096. delete this._data[key];
  63097. --this._count;
  63098. return val;
  63099. }
  63100. return null;
  63101. };
  63102. /**
  63103. * Remove a key/value from the dictionary.
  63104. * @param key the key to remove
  63105. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63106. */
  63107. StringDictionary.prototype.remove = function (key) {
  63108. if (this.contains(key)) {
  63109. delete this._data[key];
  63110. --this._count;
  63111. return true;
  63112. }
  63113. return false;
  63114. };
  63115. /**
  63116. * Clear the whole content of the dictionary
  63117. */
  63118. StringDictionary.prototype.clear = function () {
  63119. this._data = {};
  63120. this._count = 0;
  63121. };
  63122. Object.defineProperty(StringDictionary.prototype, "count", {
  63123. get: function () {
  63124. return this._count;
  63125. },
  63126. enumerable: true,
  63127. configurable: true
  63128. });
  63129. /**
  63130. * Execute a callback on each key/val of the dictionary.
  63131. * Note that you can remove any element in this dictionary in the callback implementation
  63132. * @param callback the callback to execute on a given key/value pair
  63133. */
  63134. StringDictionary.prototype.forEach = function (callback) {
  63135. for (var cur in this._data) {
  63136. var val = this._data[cur];
  63137. callback(cur, val);
  63138. }
  63139. };
  63140. /**
  63141. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63142. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63143. * Note that you can remove any element in this dictionary in the callback implementation
  63144. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63145. */
  63146. StringDictionary.prototype.first = function (callback) {
  63147. for (var cur in this._data) {
  63148. var val = this._data[cur];
  63149. var res = callback(cur, val);
  63150. if (res) {
  63151. return res;
  63152. }
  63153. }
  63154. return null;
  63155. };
  63156. return StringDictionary;
  63157. }());
  63158. BABYLON.StringDictionary = StringDictionary;
  63159. })(BABYLON || (BABYLON = {}));
  63160. //# sourceMappingURL=babylon.stringDictionary.js.map
  63161. var BABYLON;
  63162. (function (BABYLON) {
  63163. var Debug;
  63164. (function (Debug) {
  63165. /**
  63166. * Class used to render a debug view of a given skeleton
  63167. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  63168. */
  63169. var SkeletonViewer = /** @class */ (function () {
  63170. /**
  63171. * Creates a new SkeletonViewer
  63172. * @param skeleton defines the skeleton to render
  63173. * @param mesh defines the mesh attached to the skeleton
  63174. * @param scene defines the hosting scene
  63175. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  63176. * @param renderingGroupId defines the rendering group id to use with the viewer
  63177. */
  63178. function SkeletonViewer(
  63179. /** defines the skeleton to render */
  63180. skeleton,
  63181. /** defines the mesh attached to the skeleton */
  63182. mesh, scene,
  63183. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  63184. autoUpdateBonesMatrices,
  63185. /** defines the rendering group id to use with the viewer */
  63186. renderingGroupId) {
  63187. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  63188. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  63189. this.skeleton = skeleton;
  63190. this.mesh = mesh;
  63191. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  63192. this.renderingGroupId = renderingGroupId;
  63193. /** Gets or sets the color used to render the skeleton */
  63194. this.color = BABYLON.Color3.White();
  63195. this._debugLines = new Array();
  63196. this._isEnabled = false;
  63197. this._scene = scene;
  63198. this.update();
  63199. this._renderFunction = this.update.bind(this);
  63200. }
  63201. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  63202. get: function () {
  63203. return this._isEnabled;
  63204. },
  63205. /** Gets or sets a boolean indicating if the viewer is enabled */
  63206. set: function (value) {
  63207. if (this._isEnabled === value) {
  63208. return;
  63209. }
  63210. this._isEnabled = value;
  63211. if (value) {
  63212. this._scene.registerBeforeRender(this._renderFunction);
  63213. }
  63214. else {
  63215. this._scene.unregisterBeforeRender(this._renderFunction);
  63216. }
  63217. },
  63218. enumerable: true,
  63219. configurable: true
  63220. });
  63221. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  63222. if (x === void 0) { x = 0; }
  63223. if (y === void 0) { y = 0; }
  63224. if (z === void 0) { z = 0; }
  63225. var tmat = BABYLON.Tmp.Matrix[0];
  63226. var parentBone = bone.getParent();
  63227. tmat.copyFrom(bone.getLocalMatrix());
  63228. if (x !== 0 || y !== 0 || z !== 0) {
  63229. var tmat2 = BABYLON.Tmp.Matrix[1];
  63230. BABYLON.Matrix.IdentityToRef(tmat2);
  63231. tmat2.m[12] = x;
  63232. tmat2.m[13] = y;
  63233. tmat2.m[14] = z;
  63234. tmat2.multiplyToRef(tmat, tmat);
  63235. }
  63236. if (parentBone) {
  63237. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  63238. }
  63239. tmat.multiplyToRef(meshMat, tmat);
  63240. position.x = tmat.m[12];
  63241. position.y = tmat.m[13];
  63242. position.z = tmat.m[14];
  63243. };
  63244. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  63245. var len = bones.length;
  63246. var meshPos = this.mesh.position;
  63247. for (var i = 0; i < len; i++) {
  63248. var bone = bones[i];
  63249. var points = this._debugLines[i];
  63250. if (!points) {
  63251. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63252. this._debugLines[i] = points;
  63253. }
  63254. this._getBonePosition(points[0], bone, meshMat);
  63255. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  63256. points[0].subtractInPlace(meshPos);
  63257. points[1].subtractInPlace(meshPos);
  63258. }
  63259. };
  63260. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  63261. var len = bones.length;
  63262. var boneNum = 0;
  63263. var meshPos = this.mesh.position;
  63264. for (var i = len - 1; i >= 0; i--) {
  63265. var childBone = bones[i];
  63266. var parentBone = childBone.getParent();
  63267. if (!parentBone) {
  63268. continue;
  63269. }
  63270. var points = this._debugLines[boneNum];
  63271. if (!points) {
  63272. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63273. this._debugLines[boneNum] = points;
  63274. }
  63275. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  63276. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  63277. points[0].subtractInPlace(meshPos);
  63278. points[1].subtractInPlace(meshPos);
  63279. boneNum++;
  63280. }
  63281. };
  63282. /** Update the viewer to sync with current skeleton state */
  63283. SkeletonViewer.prototype.update = function () {
  63284. if (this.autoUpdateBonesMatrices) {
  63285. this.skeleton.computeAbsoluteTransforms();
  63286. }
  63287. if (this.skeleton.bones[0].length === undefined) {
  63288. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63289. }
  63290. else {
  63291. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63292. }
  63293. if (!this._debugMesh) {
  63294. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  63295. this._debugMesh.renderingGroupId = this.renderingGroupId;
  63296. }
  63297. else {
  63298. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  63299. }
  63300. this._debugMesh.position.copyFrom(this.mesh.position);
  63301. this._debugMesh.color = this.color;
  63302. };
  63303. /** Release associated resources */
  63304. SkeletonViewer.prototype.dispose = function () {
  63305. if (this._debugMesh) {
  63306. this.isEnabled = false;
  63307. this._debugMesh.dispose();
  63308. this._debugMesh = null;
  63309. }
  63310. };
  63311. return SkeletonViewer;
  63312. }());
  63313. Debug.SkeletonViewer = SkeletonViewer;
  63314. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63315. })(BABYLON || (BABYLON = {}));
  63316. //# sourceMappingURL=babylon.skeletonViewer.js.map
  63317. /**
  63318. * Module Debug contains the (visual) components to debug a scene correctly
  63319. */
  63320. var BABYLON;
  63321. (function (BABYLON) {
  63322. var Debug;
  63323. (function (Debug) {
  63324. /**
  63325. * The Axes viewer will show 3 axes in a specific point in space
  63326. */
  63327. var AxesViewer = /** @class */ (function () {
  63328. /**
  63329. * Creates a new AxesViewer
  63330. * @param scene defines the hosting scene
  63331. * @param scaleLines defines a number used to scale line length (1 by default)
  63332. */
  63333. function AxesViewer(scene, scaleLines) {
  63334. if (scaleLines === void 0) { scaleLines = 1; }
  63335. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63336. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63337. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63338. /**
  63339. * Gets or sets a number used to scale line length
  63340. */
  63341. this.scaleLines = 1;
  63342. this.scaleLines = scaleLines;
  63343. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  63344. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  63345. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  63346. this._xmesh.renderingGroupId = 2;
  63347. this._ymesh.renderingGroupId = 2;
  63348. this._zmesh.renderingGroupId = 2;
  63349. this._xmesh.material.checkReadyOnlyOnce = true;
  63350. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  63351. this._ymesh.material.checkReadyOnlyOnce = true;
  63352. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  63353. this._zmesh.material.checkReadyOnlyOnce = true;
  63354. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  63355. this.scene = scene;
  63356. }
  63357. /**
  63358. * Force the viewer to update
  63359. * @param position defines the position of the viewer
  63360. * @param xaxis defines the x axis of the viewer
  63361. * @param yaxis defines the y axis of the viewer
  63362. * @param zaxis defines the z axis of the viewer
  63363. */
  63364. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  63365. var scaleLines = this.scaleLines;
  63366. if (this._xmesh) {
  63367. this._xmesh.position.copyFrom(position);
  63368. }
  63369. if (this._ymesh) {
  63370. this._ymesh.position.copyFrom(position);
  63371. }
  63372. if (this._zmesh) {
  63373. this._zmesh.position.copyFrom(position);
  63374. }
  63375. var point2 = this._xline[1];
  63376. point2.x = xaxis.x * scaleLines;
  63377. point2.y = xaxis.y * scaleLines;
  63378. point2.z = xaxis.z * scaleLines;
  63379. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  63380. point2 = this._yline[1];
  63381. point2.x = yaxis.x * scaleLines;
  63382. point2.y = yaxis.y * scaleLines;
  63383. point2.z = yaxis.z * scaleLines;
  63384. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  63385. point2 = this._zline[1];
  63386. point2.x = zaxis.x * scaleLines;
  63387. point2.y = zaxis.y * scaleLines;
  63388. point2.z = zaxis.z * scaleLines;
  63389. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  63390. };
  63391. /** Releases resources */
  63392. AxesViewer.prototype.dispose = function () {
  63393. if (this._xmesh) {
  63394. this._xmesh.dispose();
  63395. }
  63396. if (this._ymesh) {
  63397. this._ymesh.dispose();
  63398. }
  63399. if (this._zmesh) {
  63400. this._zmesh.dispose();
  63401. }
  63402. this._xmesh = null;
  63403. this._ymesh = null;
  63404. this._zmesh = null;
  63405. this.scene = null;
  63406. };
  63407. return AxesViewer;
  63408. }());
  63409. Debug.AxesViewer = AxesViewer;
  63410. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63411. })(BABYLON || (BABYLON = {}));
  63412. //# sourceMappingURL=babylon.axesViewer.js.map
  63413. var BABYLON;
  63414. (function (BABYLON) {
  63415. var Debug;
  63416. (function (Debug) {
  63417. /**
  63418. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  63419. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  63420. */
  63421. var BoneAxesViewer = /** @class */ (function (_super) {
  63422. __extends(BoneAxesViewer, _super);
  63423. /**
  63424. * Creates a new BoneAxesViewer
  63425. * @param scene defines the hosting scene
  63426. * @param bone defines the target bone
  63427. * @param mesh defines the target mesh
  63428. * @param scaleLines defines a scaling factor for line length (1 by default)
  63429. */
  63430. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  63431. if (scaleLines === void 0) { scaleLines = 1; }
  63432. var _this = _super.call(this, scene, scaleLines) || this;
  63433. /** Gets current position */
  63434. _this.pos = BABYLON.Vector3.Zero();
  63435. /** Gets direction of X axis */
  63436. _this.xaxis = BABYLON.Vector3.Zero();
  63437. /** Gets direction of Y axis */
  63438. _this.yaxis = BABYLON.Vector3.Zero();
  63439. /** Gets direction of Z axis */
  63440. _this.zaxis = BABYLON.Vector3.Zero();
  63441. _this.mesh = mesh;
  63442. _this.bone = bone;
  63443. return _this;
  63444. }
  63445. /**
  63446. * Force the viewer to update
  63447. */
  63448. BoneAxesViewer.prototype.update = function () {
  63449. if (!this.mesh || !this.bone) {
  63450. return;
  63451. }
  63452. var bone = this.bone;
  63453. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  63454. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  63455. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  63456. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  63457. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  63458. };
  63459. /** Releases resources */
  63460. BoneAxesViewer.prototype.dispose = function () {
  63461. if (this.mesh) {
  63462. this.mesh = null;
  63463. this.bone = null;
  63464. _super.prototype.dispose.call(this);
  63465. }
  63466. };
  63467. return BoneAxesViewer;
  63468. }(Debug.AxesViewer));
  63469. Debug.BoneAxesViewer = BoneAxesViewer;
  63470. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63471. })(BABYLON || (BABYLON = {}));
  63472. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  63473. var BABYLON;
  63474. (function (BABYLON) {
  63475. /**
  63476. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  63477. * in order to better appreciate the issue one might have.
  63478. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  63479. */
  63480. var RayHelper = /** @class */ (function () {
  63481. /**
  63482. * Instantiate a new ray helper.
  63483. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  63484. * in order to better appreciate the issue one might have.
  63485. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  63486. * @param ray Defines the ray we are currently tryin to visualize
  63487. */
  63488. function RayHelper(ray) {
  63489. this.ray = ray;
  63490. }
  63491. /**
  63492. * Helper function to create a colored helper in a scene in one line.
  63493. * @param ray Defines the ray we are currently tryin to visualize
  63494. * @param scene Defines the scene the ray is used in
  63495. * @param color Defines the color we want to see the ray in
  63496. * @returns The newly created ray helper.
  63497. */
  63498. RayHelper.CreateAndShow = function (ray, scene, color) {
  63499. var helper = new RayHelper(ray);
  63500. helper.show(scene, color);
  63501. return helper;
  63502. };
  63503. /**
  63504. * Shows the ray we are willing to debug.
  63505. * @param scene Defines the scene the ray needs to be rendered in
  63506. * @param color Defines the color the ray needs to be rendered in
  63507. */
  63508. RayHelper.prototype.show = function (scene, color) {
  63509. if (!this._renderFunction && this.ray) {
  63510. var ray = this.ray;
  63511. this._renderFunction = this._render.bind(this);
  63512. this._scene = scene;
  63513. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  63514. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  63515. if (this._renderFunction) {
  63516. this._scene.registerBeforeRender(this._renderFunction);
  63517. }
  63518. }
  63519. if (color && this._renderLine) {
  63520. this._renderLine.color.copyFrom(color);
  63521. }
  63522. };
  63523. /**
  63524. * Hides the ray we are debugging.
  63525. */
  63526. RayHelper.prototype.hide = function () {
  63527. if (this._renderFunction && this._scene) {
  63528. this._scene.unregisterBeforeRender(this._renderFunction);
  63529. this._scene = null;
  63530. this._renderFunction = null;
  63531. if (this._renderLine) {
  63532. this._renderLine.dispose();
  63533. this._renderLine = null;
  63534. }
  63535. this._renderPoints = [];
  63536. }
  63537. };
  63538. RayHelper.prototype._render = function () {
  63539. var ray = this.ray;
  63540. if (!ray) {
  63541. return;
  63542. }
  63543. var point = this._renderPoints[1];
  63544. var len = Math.min(ray.length, 1000000);
  63545. point.copyFrom(ray.direction);
  63546. point.scaleInPlace(len);
  63547. point.addInPlace(ray.origin);
  63548. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  63549. };
  63550. /**
  63551. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  63552. * @param mesh Defines the mesh we want the helper attached to
  63553. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  63554. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  63555. * @param length Defines the length of the ray
  63556. */
  63557. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  63558. this._attachedToMesh = mesh;
  63559. var ray = this.ray;
  63560. if (!ray) {
  63561. return;
  63562. }
  63563. if (!ray.direction) {
  63564. ray.direction = BABYLON.Vector3.Zero();
  63565. }
  63566. if (!ray.origin) {
  63567. ray.origin = BABYLON.Vector3.Zero();
  63568. }
  63569. if (length) {
  63570. ray.length = length;
  63571. }
  63572. if (!meshSpaceOrigin) {
  63573. meshSpaceOrigin = BABYLON.Vector3.Zero();
  63574. }
  63575. if (!meshSpaceDirection) {
  63576. // -1 so that this will work with Mesh.lookAt
  63577. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  63578. }
  63579. if (!this._meshSpaceDirection) {
  63580. this._meshSpaceDirection = meshSpaceDirection.clone();
  63581. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  63582. }
  63583. else {
  63584. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  63585. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  63586. }
  63587. if (!this._updateToMeshFunction) {
  63588. this._updateToMeshFunction = this._updateToMesh.bind(this);
  63589. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  63590. }
  63591. this._updateToMesh();
  63592. };
  63593. /**
  63594. * Detach the ray helper from the mesh it has previously been attached to.
  63595. */
  63596. RayHelper.prototype.detachFromMesh = function () {
  63597. if (this._attachedToMesh) {
  63598. if (this._updateToMeshFunction) {
  63599. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  63600. }
  63601. this._attachedToMesh = null;
  63602. this._updateToMeshFunction = null;
  63603. }
  63604. };
  63605. RayHelper.prototype._updateToMesh = function () {
  63606. var ray = this.ray;
  63607. if (!this._attachedToMesh || !ray) {
  63608. return;
  63609. }
  63610. if (this._attachedToMesh._isDisposed) {
  63611. this.detachFromMesh();
  63612. return;
  63613. }
  63614. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  63615. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  63616. };
  63617. /**
  63618. * Dispose the helper and release its associated resources.
  63619. */
  63620. RayHelper.prototype.dispose = function () {
  63621. this.hide();
  63622. this.detachFromMesh();
  63623. this.ray = null;
  63624. };
  63625. return RayHelper;
  63626. }());
  63627. BABYLON.RayHelper = RayHelper;
  63628. })(BABYLON || (BABYLON = {}));
  63629. //# sourceMappingURL=babylon.rayHelper.js.map
  63630. var BABYLON;
  63631. (function (BABYLON) {
  63632. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  63633. get: function () {
  63634. if (!this._debugLayer) {
  63635. this._debugLayer = new DebugLayer(this);
  63636. }
  63637. return this._debugLayer;
  63638. },
  63639. enumerable: true,
  63640. configurable: true
  63641. });
  63642. /**
  63643. * The debug layer (aka Inspector) is the go to tool in order to better understand
  63644. * what is happening in your scene
  63645. * @see http://doc.babylonjs.com/features/playground_debuglayer
  63646. */
  63647. var DebugLayer = /** @class */ (function () {
  63648. /**
  63649. * Instantiates a new debug layer.
  63650. * The debug layer (aka Inspector) is the go to tool in order to better understand
  63651. * what is happening in your scene
  63652. * @see http://doc.babylonjs.com/features/playground_debuglayer
  63653. * @param scene Defines the scene to inspect
  63654. */
  63655. function DebugLayer(scene) {
  63656. var _this = this;
  63657. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  63658. /**
  63659. * Observable triggered when a property is changed through the inspector.
  63660. */
  63661. this.onPropertyChangedObservable = new BABYLON.Observable();
  63662. this._scene = scene;
  63663. this._scene.onDisposeObservable.add(function () {
  63664. // Debug layer
  63665. if (_this._scene._debugLayer) {
  63666. _this._scene._debugLayer.hide();
  63667. }
  63668. });
  63669. }
  63670. /** Creates the inspector window. */
  63671. DebugLayer.prototype._createInspector = function (config) {
  63672. if (config === void 0) { config = {}; }
  63673. var popup = config.popup || false;
  63674. var initialTab = config.initialTab || 0;
  63675. var parentElement = config.parentElement || null;
  63676. if (!this._inspector) {
  63677. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  63678. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  63679. } // else nothing to do as instance is already created
  63680. };
  63681. /**
  63682. * Get if the inspector is visible or not.
  63683. * @returns true if visible otherwise, false
  63684. */
  63685. DebugLayer.prototype.isVisible = function () {
  63686. if (!this._inspector) {
  63687. return false;
  63688. }
  63689. return true;
  63690. };
  63691. /**
  63692. * Hide the inspector and close its window.
  63693. */
  63694. DebugLayer.prototype.hide = function () {
  63695. if (this._inspector) {
  63696. try {
  63697. this._inspector.dispose();
  63698. }
  63699. catch (e) {
  63700. // If the inspector has been removed directly from the inspector tool
  63701. }
  63702. this.onPropertyChangedObservable.clear();
  63703. this._inspector = null;
  63704. }
  63705. };
  63706. /**
  63707. *
  63708. * Launch the debugLayer.
  63709. *
  63710. * initialTab:
  63711. * | Value | Tab Name |
  63712. * | --- | --- |
  63713. * | 0 | Scene |
  63714. * | 1 | Console |
  63715. * | 2 | Stats |
  63716. * | 3 | Textures |
  63717. * | 4 | Mesh |
  63718. * | 5 | Light |
  63719. * | 6 | Material |
  63720. * | 7 | GLTF |
  63721. * | 8 | GUI |
  63722. * | 9 | Physics |
  63723. * | 10 | Camera |
  63724. * | 11 | Audio |
  63725. *
  63726. * @param config Define the configuration of the inspector
  63727. */
  63728. DebugLayer.prototype.show = function (config) {
  63729. if (config === void 0) { config = {}; }
  63730. if (typeof this.BJSINSPECTOR == 'undefined') {
  63731. // Load inspector and add it to the DOM
  63732. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  63733. }
  63734. else {
  63735. // Otherwise creates the inspector
  63736. this._createInspector(config);
  63737. }
  63738. };
  63739. /**
  63740. * Gets the active tab
  63741. * @return the index of the active tab or -1 if the inspector is hidden
  63742. */
  63743. DebugLayer.prototype.getActiveTab = function () {
  63744. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  63745. };
  63746. /**
  63747. * Define the url to get the inspector script from.
  63748. * By default it uses the babylonjs CDN.
  63749. * @ignoreNaming
  63750. */
  63751. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  63752. return DebugLayer;
  63753. }());
  63754. BABYLON.DebugLayer = DebugLayer;
  63755. })(BABYLON || (BABYLON = {}));
  63756. //# sourceMappingURL=babylon.debugLayer.js.map
  63757. var BABYLON;
  63758. (function (BABYLON) {
  63759. var Debug;
  63760. (function (Debug) {
  63761. /**
  63762. * Used to show the physics impostor around the specific mesh
  63763. */
  63764. var PhysicsViewer = /** @class */ (function () {
  63765. /**
  63766. * Creates a new PhysicsViewer
  63767. * @param scene defines the hosting scene
  63768. */
  63769. function PhysicsViewer(scene) {
  63770. /** @hidden */
  63771. this._impostors = [];
  63772. /** @hidden */
  63773. this._meshes = [];
  63774. /** @hidden */
  63775. this._numMeshes = 0;
  63776. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63777. var physicEngine = this._scene.getPhysicsEngine();
  63778. if (physicEngine) {
  63779. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  63780. }
  63781. }
  63782. /** @hidden */
  63783. PhysicsViewer.prototype._updateDebugMeshes = function () {
  63784. var plugin = this._physicsEnginePlugin;
  63785. for (var i = 0; i < this._numMeshes; i++) {
  63786. var impostor = this._impostors[i];
  63787. if (!impostor) {
  63788. continue;
  63789. }
  63790. if (impostor.isDisposed) {
  63791. this.hideImpostor(this._impostors[i--]);
  63792. }
  63793. else {
  63794. var mesh = this._meshes[i];
  63795. if (mesh && plugin) {
  63796. plugin.syncMeshWithImpostor(mesh, impostor);
  63797. }
  63798. }
  63799. }
  63800. };
  63801. /**
  63802. * Renders a specified physic impostor
  63803. * @param impostor defines the impostor to render
  63804. */
  63805. PhysicsViewer.prototype.showImpostor = function (impostor) {
  63806. if (!this._scene) {
  63807. return;
  63808. }
  63809. for (var i = 0; i < this._numMeshes; i++) {
  63810. if (this._impostors[i] == impostor) {
  63811. return;
  63812. }
  63813. }
  63814. var debugMesh = this._getDebugMesh(impostor, this._scene);
  63815. if (debugMesh) {
  63816. this._impostors[this._numMeshes] = impostor;
  63817. this._meshes[this._numMeshes] = debugMesh;
  63818. if (this._numMeshes === 0) {
  63819. this._renderFunction = this._updateDebugMeshes.bind(this);
  63820. this._scene.registerBeforeRender(this._renderFunction);
  63821. }
  63822. this._numMeshes++;
  63823. }
  63824. };
  63825. /**
  63826. * Hides a specified physic impostor
  63827. * @param impostor defines the impostor to hide
  63828. */
  63829. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  63830. if (!impostor || !this._scene) {
  63831. return;
  63832. }
  63833. var removed = false;
  63834. for (var i = 0; i < this._numMeshes; i++) {
  63835. if (this._impostors[i] == impostor) {
  63836. var mesh = this._meshes[i];
  63837. if (!mesh) {
  63838. continue;
  63839. }
  63840. this._scene.removeMesh(mesh);
  63841. mesh.dispose();
  63842. this._numMeshes--;
  63843. if (this._numMeshes > 0) {
  63844. this._meshes[i] = this._meshes[this._numMeshes];
  63845. this._impostors[i] = this._impostors[this._numMeshes];
  63846. this._meshes[this._numMeshes] = null;
  63847. this._impostors[this._numMeshes] = null;
  63848. }
  63849. else {
  63850. this._meshes[0] = null;
  63851. this._impostors[0] = null;
  63852. }
  63853. removed = true;
  63854. break;
  63855. }
  63856. }
  63857. if (removed && this._numMeshes === 0) {
  63858. this._scene.unregisterBeforeRender(this._renderFunction);
  63859. }
  63860. };
  63861. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  63862. if (!this._debugMaterial) {
  63863. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  63864. this._debugMaterial.wireframe = true;
  63865. }
  63866. return this._debugMaterial;
  63867. };
  63868. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63869. if (!this._debugBoxMesh) {
  63870. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63871. this._debugBoxMesh.renderingGroupId = 1;
  63872. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63873. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63874. scene.removeMesh(this._debugBoxMesh);
  63875. }
  63876. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63877. };
  63878. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63879. if (!this._debugSphereMesh) {
  63880. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63881. this._debugSphereMesh.renderingGroupId = 1;
  63882. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63883. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63884. scene.removeMesh(this._debugSphereMesh);
  63885. }
  63886. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63887. };
  63888. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63889. var mesh = null;
  63890. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63891. mesh = this._getDebugBoxMesh(scene);
  63892. impostor.getBoxSizeToRef(mesh.scaling);
  63893. }
  63894. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63895. mesh = this._getDebugSphereMesh(scene);
  63896. var radius = impostor.getRadius();
  63897. mesh.scaling.x = radius * 2;
  63898. mesh.scaling.y = radius * 2;
  63899. mesh.scaling.z = radius * 2;
  63900. }
  63901. return mesh;
  63902. };
  63903. /** Releases all resources */
  63904. PhysicsViewer.prototype.dispose = function () {
  63905. for (var i = 0; i < this._numMeshes; i++) {
  63906. this.hideImpostor(this._impostors[i]);
  63907. }
  63908. if (this._debugBoxMesh) {
  63909. this._debugBoxMesh.dispose();
  63910. }
  63911. if (this._debugSphereMesh) {
  63912. this._debugSphereMesh.dispose();
  63913. }
  63914. if (this._debugMaterial) {
  63915. this._debugMaterial.dispose();
  63916. }
  63917. this._impostors.length = 0;
  63918. this._scene = null;
  63919. this._physicsEnginePlugin = null;
  63920. };
  63921. return PhysicsViewer;
  63922. }());
  63923. Debug.PhysicsViewer = PhysicsViewer;
  63924. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63925. })(BABYLON || (BABYLON = {}));
  63926. //# sourceMappingURL=babylon.physicsViewer.js.map
  63927. var BABYLON;
  63928. (function (BABYLON) {
  63929. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  63930. get: function () {
  63931. return this._forceShowBoundingBoxes || false;
  63932. },
  63933. set: function (value) {
  63934. this._forceShowBoundingBoxes = value;
  63935. // Lazyly creates a BB renderer if needed.
  63936. if (value) {
  63937. this.getBoundingBoxRenderer();
  63938. }
  63939. },
  63940. enumerable: true,
  63941. configurable: true
  63942. });
  63943. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  63944. if (!this._boundingBoxRenderer) {
  63945. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  63946. }
  63947. return this._boundingBoxRenderer;
  63948. };
  63949. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  63950. get: function () {
  63951. return this._showBoundingBox || false;
  63952. },
  63953. set: function (value) {
  63954. this._showBoundingBox = value;
  63955. // Lazyly creates a BB renderer if needed.
  63956. if (value) {
  63957. this.getScene().getBoundingBoxRenderer();
  63958. }
  63959. },
  63960. enumerable: true,
  63961. configurable: true
  63962. });
  63963. /**
  63964. * Component responsible of rendering the bounding box of the meshes in a scene.
  63965. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  63966. */
  63967. var BoundingBoxRenderer = /** @class */ (function () {
  63968. /**
  63969. * Instantiates a new bounding box renderer in a scene.
  63970. * @param scene the scene the renderer renders in
  63971. */
  63972. function BoundingBoxRenderer(scene) {
  63973. /**
  63974. * The component name helpfull to identify the component in the list of scene components.
  63975. */
  63976. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  63977. /**
  63978. * Color of the bounding box lines placed in front of an object
  63979. */
  63980. this.frontColor = new BABYLON.Color3(1, 1, 1);
  63981. /**
  63982. * Color of the bounding box lines placed behind an object
  63983. */
  63984. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  63985. /**
  63986. * Defines if the renderer should show the back lines or not
  63987. */
  63988. this.showBackLines = true;
  63989. /**
  63990. * @hidden
  63991. */
  63992. this.renderList = new BABYLON.SmartArray(32);
  63993. this._vertexBuffers = {};
  63994. this.scene = scene;
  63995. scene._addComponent(this);
  63996. }
  63997. /**
  63998. * Registers the component in a given scene
  63999. */
  64000. BoundingBoxRenderer.prototype.register = function () {
  64001. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  64002. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  64003. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  64004. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  64005. };
  64006. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  64007. if (mesh.showSubMeshesBoundingBox) {
  64008. var boundingInfo = subMesh.getBoundingInfo();
  64009. if (boundingInfo !== null && boundingInfo !== undefined) {
  64010. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64011. this.renderList.push(boundingInfo.boundingBox);
  64012. }
  64013. }
  64014. };
  64015. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  64016. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  64017. var boundingInfo = sourceMesh.getBoundingInfo();
  64018. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64019. this.renderList.push(boundingInfo.boundingBox);
  64020. }
  64021. };
  64022. BoundingBoxRenderer.prototype._prepareRessources = function () {
  64023. if (this._colorShader) {
  64024. return;
  64025. }
  64026. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  64027. attributes: [BABYLON.VertexBuffer.PositionKind],
  64028. uniforms: ["world", "viewProjection", "color"]
  64029. });
  64030. var engine = this.scene.getEngine();
  64031. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  64032. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  64033. this._createIndexBuffer();
  64034. };
  64035. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  64036. var engine = this.scene.getEngine();
  64037. 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]);
  64038. };
  64039. /**
  64040. * Rebuilds the elements related to this component in case of
  64041. * context lost for instance.
  64042. */
  64043. BoundingBoxRenderer.prototype.rebuild = function () {
  64044. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64045. if (vb) {
  64046. vb._rebuild();
  64047. }
  64048. this._createIndexBuffer();
  64049. };
  64050. /**
  64051. * @hidden
  64052. */
  64053. BoundingBoxRenderer.prototype.reset = function () {
  64054. this.renderList.reset();
  64055. };
  64056. /**
  64057. * Render the bounding boxes of a specific rendering group
  64058. * @param renderingGroupId defines the rendering group to render
  64059. */
  64060. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  64061. if (this.renderList.length === 0) {
  64062. return;
  64063. }
  64064. this._prepareRessources();
  64065. if (!this._colorShader.isReady()) {
  64066. return;
  64067. }
  64068. var engine = this.scene.getEngine();
  64069. engine.setDepthWrite(false);
  64070. this._colorShader._preBind();
  64071. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  64072. var boundingBox = this.renderList.data[boundingBoxIndex];
  64073. if (boundingBox._tag !== renderingGroupId) {
  64074. continue;
  64075. }
  64076. var min = boundingBox.minimum;
  64077. var max = boundingBox.maximum;
  64078. var diff = max.subtract(min);
  64079. var median = min.add(diff.scale(0.5));
  64080. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64081. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64082. .multiply(boundingBox.getWorldMatrix());
  64083. // VBOs
  64084. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64085. if (this.showBackLines) {
  64086. // Back
  64087. engine.setDepthFunctionToGreaterOrEqual();
  64088. this.scene.resetCachedMaterial();
  64089. this._colorShader.setColor4("color", this.backColor.toColor4());
  64090. this._colorShader.bind(worldMatrix);
  64091. // Draw order
  64092. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64093. }
  64094. // Front
  64095. engine.setDepthFunctionToLess();
  64096. this.scene.resetCachedMaterial();
  64097. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64098. this._colorShader.bind(worldMatrix);
  64099. // Draw order
  64100. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64101. }
  64102. this._colorShader.unbind();
  64103. engine.setDepthFunctionToLessOrEqual();
  64104. engine.setDepthWrite(true);
  64105. };
  64106. /**
  64107. * In case of occlusion queries, we can render the occlusion bounding box through this method
  64108. * @param mesh Define the mesh to render the occlusion bounding box for
  64109. */
  64110. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64111. this._prepareRessources();
  64112. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  64113. return;
  64114. }
  64115. var engine = this.scene.getEngine();
  64116. engine.setDepthWrite(false);
  64117. engine.setColorWrite(false);
  64118. this._colorShader._preBind();
  64119. var boundingBox = mesh._boundingInfo.boundingBox;
  64120. var min = boundingBox.minimum;
  64121. var max = boundingBox.maximum;
  64122. var diff = max.subtract(min);
  64123. var median = min.add(diff.scale(0.5));
  64124. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64125. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64126. .multiply(boundingBox.getWorldMatrix());
  64127. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64128. engine.setDepthFunctionToLess();
  64129. this.scene.resetCachedMaterial();
  64130. this._colorShader.bind(worldMatrix);
  64131. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64132. this._colorShader.unbind();
  64133. engine.setDepthFunctionToLessOrEqual();
  64134. engine.setDepthWrite(true);
  64135. engine.setColorWrite(true);
  64136. };
  64137. /**
  64138. * Dispose and release the resources attached to this renderer.
  64139. */
  64140. BoundingBoxRenderer.prototype.dispose = function () {
  64141. if (!this._colorShader) {
  64142. return;
  64143. }
  64144. this.renderList.dispose();
  64145. this._colorShader.dispose();
  64146. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64147. if (buffer) {
  64148. buffer.dispose();
  64149. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64150. }
  64151. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  64152. };
  64153. return BoundingBoxRenderer;
  64154. }());
  64155. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  64156. })(BABYLON || (BABYLON = {}));
  64157. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  64158. var BABYLON;
  64159. (function (BABYLON) {
  64160. BABYLON.Engine.prototype.createTransformFeedback = function () {
  64161. return this._gl.createTransformFeedback();
  64162. };
  64163. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  64164. this._gl.deleteTransformFeedback(value);
  64165. };
  64166. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  64167. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  64168. };
  64169. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  64170. if (usePoints === void 0) { usePoints = true; }
  64171. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  64172. };
  64173. BABYLON.Engine.prototype.endTransformFeedback = function () {
  64174. this._gl.endTransformFeedback();
  64175. };
  64176. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  64177. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  64178. };
  64179. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  64180. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  64181. };
  64182. })(BABYLON || (BABYLON = {}));
  64183. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  64184. var BABYLON;
  64185. (function (BABYLON) {
  64186. /**
  64187. * This represents a GPU particle system in Babylon
  64188. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  64189. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  64190. */
  64191. var GPUParticleSystem = /** @class */ (function (_super) {
  64192. __extends(GPUParticleSystem, _super);
  64193. /**
  64194. * Instantiates a GPU particle system.
  64195. * 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.
  64196. * @param name The name of the particle system
  64197. * @param options The options used to create the system
  64198. * @param scene The scene the particle system belongs to
  64199. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  64200. */
  64201. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  64202. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  64203. var _this = _super.call(this, name) || this;
  64204. /**
  64205. * The layer mask we are rendering the particles through.
  64206. */
  64207. _this.layerMask = 0x0FFFFFFF;
  64208. _this._accumulatedCount = 0;
  64209. _this._targetIndex = 0;
  64210. _this._currentRenderId = -1;
  64211. _this._started = false;
  64212. _this._stopped = false;
  64213. _this._timeDelta = 0;
  64214. _this._attributesStrideSize = 21;
  64215. _this._actualFrame = 0;
  64216. _this._rawTextureWidth = 256;
  64217. /**
  64218. * An event triggered when the system is disposed.
  64219. */
  64220. _this.onDisposeObservable = new BABYLON.Observable();
  64221. /**
  64222. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  64223. * to override the particles.
  64224. */
  64225. _this.forceDepthWrite = false;
  64226. _this._preWarmDone = false;
  64227. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64228. // Setup the default processing configuration to the scene.
  64229. _this._attachImageProcessingConfiguration(null);
  64230. _this._engine = _this._scene.getEngine();
  64231. if (!options.randomTextureSize) {
  64232. delete options.randomTextureSize;
  64233. }
  64234. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  64235. var optionsAsNumber = options;
  64236. if (isFinite(optionsAsNumber)) {
  64237. fullOptions.capacity = optionsAsNumber;
  64238. }
  64239. _this._capacity = fullOptions.capacity;
  64240. _this._activeCount = fullOptions.capacity;
  64241. _this._currentActiveCount = 0;
  64242. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  64243. _this._scene.particleSystems.push(_this);
  64244. _this._updateEffectOptions = {
  64245. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  64246. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  64247. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  64248. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  64249. uniformBuffersNames: [],
  64250. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  64251. defines: "",
  64252. fallbacks: null,
  64253. onCompiled: null,
  64254. onError: null,
  64255. indexParameters: null,
  64256. maxSimultaneousLights: 0,
  64257. transformFeedbackVaryings: []
  64258. };
  64259. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  64260. // Random data
  64261. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  64262. var d = [];
  64263. for (var i = 0; i < maxTextureSize; ++i) {
  64264. d.push(Math.random());
  64265. d.push(Math.random());
  64266. d.push(Math.random());
  64267. d.push(Math.random());
  64268. }
  64269. _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);
  64270. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64271. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64272. d = [];
  64273. for (var i = 0; i < maxTextureSize; ++i) {
  64274. d.push(Math.random());
  64275. d.push(Math.random());
  64276. d.push(Math.random());
  64277. d.push(Math.random());
  64278. }
  64279. _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);
  64280. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64281. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64282. _this._randomTextureSize = maxTextureSize;
  64283. return _this;
  64284. }
  64285. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  64286. /**
  64287. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  64288. */
  64289. get: function () {
  64290. if (!BABYLON.Engine.LastCreatedEngine) {
  64291. return false;
  64292. }
  64293. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  64294. },
  64295. enumerable: true,
  64296. configurable: true
  64297. });
  64298. /**
  64299. * Gets the maximum number of particles active at the same time.
  64300. * @returns The max number of active particles.
  64301. */
  64302. GPUParticleSystem.prototype.getCapacity = function () {
  64303. return this._capacity;
  64304. };
  64305. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  64306. /**
  64307. * Gets or set the number of active particles
  64308. */
  64309. get: function () {
  64310. return this._activeCount;
  64311. },
  64312. set: function (value) {
  64313. this._activeCount = Math.min(value, this._capacity);
  64314. },
  64315. enumerable: true,
  64316. configurable: true
  64317. });
  64318. /**
  64319. * Is this system ready to be used/rendered
  64320. * @return true if the system is ready
  64321. */
  64322. GPUParticleSystem.prototype.isReady = function () {
  64323. if (!this._updateEffect) {
  64324. this._recreateUpdateEffect();
  64325. this._recreateRenderEffect();
  64326. return false;
  64327. }
  64328. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  64329. return false;
  64330. }
  64331. return true;
  64332. };
  64333. /**
  64334. * Gets if the system has been started. (Note: this will still be true after stop is called)
  64335. * @returns True if it has been started, otherwise false.
  64336. */
  64337. GPUParticleSystem.prototype.isStarted = function () {
  64338. return this._started;
  64339. };
  64340. /**
  64341. * Starts the particle system and begins to emit
  64342. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  64343. */
  64344. GPUParticleSystem.prototype.start = function (delay) {
  64345. var _this = this;
  64346. if (delay === void 0) { delay = this.startDelay; }
  64347. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  64348. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  64349. }
  64350. if (delay) {
  64351. setTimeout(function () {
  64352. _this.start(0);
  64353. }, delay);
  64354. return;
  64355. }
  64356. this._started = true;
  64357. this._stopped = false;
  64358. this._preWarmDone = false;
  64359. // Animations
  64360. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  64361. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  64362. }
  64363. };
  64364. /**
  64365. * Stops the particle system.
  64366. */
  64367. GPUParticleSystem.prototype.stop = function () {
  64368. this._stopped = true;
  64369. };
  64370. /**
  64371. * Remove all active particles
  64372. */
  64373. GPUParticleSystem.prototype.reset = function () {
  64374. this._releaseBuffers();
  64375. this._releaseVAOs();
  64376. this._currentActiveCount = 0;
  64377. this._targetIndex = 0;
  64378. };
  64379. /**
  64380. * Returns the string "GPUParticleSystem"
  64381. * @returns a string containing the class name
  64382. */
  64383. GPUParticleSystem.prototype.getClassName = function () {
  64384. return "GPUParticleSystem";
  64385. };
  64386. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  64387. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  64388. this._releaseBuffers();
  64389. return this;
  64390. };
  64391. /**
  64392. * Adds a new color gradient
  64393. * @param gradient defines the gradient to use (between 0 and 1)
  64394. * @param color1 defines the color to affect to the specified gradient
  64395. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  64396. * @returns the current particle system
  64397. */
  64398. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  64399. if (!this._colorGradients) {
  64400. this._colorGradients = [];
  64401. }
  64402. var colorGradient = new BABYLON.ColorGradient();
  64403. colorGradient.gradient = gradient;
  64404. colorGradient.color1 = color1;
  64405. this._colorGradients.push(colorGradient);
  64406. this._colorGradients.sort(function (a, b) {
  64407. if (a.gradient < b.gradient) {
  64408. return -1;
  64409. }
  64410. else if (a.gradient > b.gradient) {
  64411. return 1;
  64412. }
  64413. return 0;
  64414. });
  64415. if (this._colorGradientsTexture) {
  64416. this._colorGradientsTexture.dispose();
  64417. this._colorGradientsTexture = null;
  64418. }
  64419. this._releaseBuffers();
  64420. return this;
  64421. };
  64422. /**
  64423. * Remove a specific color gradient
  64424. * @param gradient defines the gradient to remove
  64425. * @returns the current particle system
  64426. */
  64427. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  64428. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  64429. this._colorGradientsTexture = null;
  64430. return this;
  64431. };
  64432. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  64433. var valueGradient = new BABYLON.FactorGradient();
  64434. valueGradient.gradient = gradient;
  64435. valueGradient.factor1 = factor;
  64436. factorGradients.push(valueGradient);
  64437. factorGradients.sort(function (a, b) {
  64438. if (a.gradient < b.gradient) {
  64439. return -1;
  64440. }
  64441. else if (a.gradient > b.gradient) {
  64442. return 1;
  64443. }
  64444. return 0;
  64445. });
  64446. this._releaseBuffers();
  64447. };
  64448. /**
  64449. * Adds a new size gradient
  64450. * @param gradient defines the gradient to use (between 0 and 1)
  64451. * @param factor defines the size factor to affect to the specified gradient
  64452. * @returns the current particle system
  64453. */
  64454. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  64455. if (!this._sizeGradients) {
  64456. this._sizeGradients = [];
  64457. }
  64458. this._addFactorGradient(this._sizeGradients, gradient, factor);
  64459. if (this._sizeGradientsTexture) {
  64460. this._sizeGradientsTexture.dispose();
  64461. this._sizeGradientsTexture = null;
  64462. }
  64463. this._releaseBuffers();
  64464. return this;
  64465. };
  64466. /**
  64467. * Remove a specific size gradient
  64468. * @param gradient defines the gradient to remove
  64469. * @returns the current particle system
  64470. */
  64471. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  64472. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  64473. this._sizeGradientsTexture = null;
  64474. return this;
  64475. };
  64476. /**
  64477. * Adds a new angular speed gradient
  64478. * @param gradient defines the gradient to use (between 0 and 1)
  64479. * @param factor defines the angular speed to affect to the specified gradient
  64480. * @returns the current particle system
  64481. */
  64482. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  64483. if (!this._angularSpeedGradients) {
  64484. this._angularSpeedGradients = [];
  64485. }
  64486. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  64487. if (this._angularSpeedGradientsTexture) {
  64488. this._angularSpeedGradientsTexture.dispose();
  64489. this._angularSpeedGradientsTexture = null;
  64490. }
  64491. this._releaseBuffers();
  64492. return this;
  64493. };
  64494. /**
  64495. * Remove a specific angular speed gradient
  64496. * @param gradient defines the gradient to remove
  64497. * @returns the current particle system
  64498. */
  64499. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  64500. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  64501. this._angularSpeedGradientsTexture = null;
  64502. return this;
  64503. };
  64504. /**
  64505. * Adds a new velocity gradient
  64506. * @param gradient defines the gradient to use (between 0 and 1)
  64507. * @param factor defines the velocity to affect to the specified gradient
  64508. * @returns the current particle system
  64509. */
  64510. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  64511. if (!this._velocityGradients) {
  64512. this._velocityGradients = [];
  64513. }
  64514. this._addFactorGradient(this._velocityGradients, gradient, factor);
  64515. if (this._velocityGradientsTexture) {
  64516. this._velocityGradientsTexture.dispose();
  64517. this._velocityGradientsTexture = null;
  64518. }
  64519. this._releaseBuffers();
  64520. return this;
  64521. };
  64522. /**
  64523. * Remove a specific velocity gradient
  64524. * @param gradient defines the gradient to remove
  64525. * @returns the current particle system
  64526. */
  64527. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  64528. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  64529. this._velocityGradientsTexture = null;
  64530. return this;
  64531. };
  64532. /**
  64533. * Adds a new limit velocity gradient
  64534. * @param gradient defines the gradient to use (between 0 and 1)
  64535. * @param factor defines the limit velocity value to affect to the specified gradient
  64536. * @returns the current particle system
  64537. */
  64538. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  64539. if (!this._limitVelocityGradients) {
  64540. this._limitVelocityGradients = [];
  64541. }
  64542. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  64543. if (this._limitVelocityGradientsTexture) {
  64544. this._limitVelocityGradientsTexture.dispose();
  64545. this._limitVelocityGradientsTexture = null;
  64546. }
  64547. this._releaseBuffers();
  64548. return this;
  64549. };
  64550. /**
  64551. * Remove a specific limit velocity gradient
  64552. * @param gradient defines the gradient to remove
  64553. * @returns the current particle system
  64554. */
  64555. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  64556. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  64557. this._limitVelocityGradientsTexture = null;
  64558. return this;
  64559. };
  64560. /**
  64561. * Adds a new drag gradient
  64562. * @param gradient defines the gradient to use (between 0 and 1)
  64563. * @param factor defines the drag value to affect to the specified gradient
  64564. * @returns the current particle system
  64565. */
  64566. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  64567. if (!this._dragGradients) {
  64568. this._dragGradients = [];
  64569. }
  64570. this._addFactorGradient(this._dragGradients, gradient, factor);
  64571. if (this._dragGradientsTexture) {
  64572. this._dragGradientsTexture.dispose();
  64573. this._dragGradientsTexture = null;
  64574. }
  64575. this._releaseBuffers();
  64576. return this;
  64577. };
  64578. /**
  64579. * Remove a specific drag gradient
  64580. * @param gradient defines the gradient to remove
  64581. * @returns the current particle system
  64582. */
  64583. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  64584. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  64585. this._dragGradientsTexture = null;
  64586. return this;
  64587. };
  64588. /**
  64589. * Not supported by GPUParticleSystem
  64590. * @param gradient defines the gradient to use (between 0 and 1)
  64591. * @param factor defines the emit rate value to affect to the specified gradient
  64592. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64593. * @returns the current particle system
  64594. */
  64595. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  64596. // Do nothing as emit rate is not supported by GPUParticleSystem
  64597. return this;
  64598. };
  64599. /**
  64600. * Not supported by GPUParticleSystem
  64601. * @param gradient defines the gradient to remove
  64602. * @returns the current particle system
  64603. */
  64604. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  64605. // Do nothing as emit rate is not supported by GPUParticleSystem
  64606. return this;
  64607. };
  64608. /**
  64609. * Not supported by GPUParticleSystem
  64610. * @param gradient defines the gradient to use (between 0 and 1)
  64611. * @param factor defines the start size value to affect to the specified gradient
  64612. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64613. * @returns the current particle system
  64614. */
  64615. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  64616. // Do nothing as start size is not supported by GPUParticleSystem
  64617. return this;
  64618. };
  64619. /**
  64620. * Not supported by GPUParticleSystem
  64621. * @param gradient defines the gradient to remove
  64622. * @returns the current particle system
  64623. */
  64624. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  64625. // Do nothing as start size is not supported by GPUParticleSystem
  64626. return this;
  64627. };
  64628. /**
  64629. * Not supported by GPUParticleSystem
  64630. * @param gradient defines the gradient to use (between 0 and 1)
  64631. * @param min defines the color remap minimal range
  64632. * @param max defines the color remap maximal range
  64633. * @returns the current particle system
  64634. */
  64635. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  64636. // Do nothing as start size is not supported by GPUParticleSystem
  64637. return this;
  64638. };
  64639. /**
  64640. * Not supported by GPUParticleSystem
  64641. * @param gradient defines the gradient to remove
  64642. * @returns the current particle system
  64643. */
  64644. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  64645. // Do nothing as start size is not supported by GPUParticleSystem
  64646. return this;
  64647. };
  64648. /**
  64649. * Not supported by GPUParticleSystem
  64650. * @param gradient defines the gradient to use (between 0 and 1)
  64651. * @param min defines the alpha remap minimal range
  64652. * @param max defines the alpha remap maximal range
  64653. * @returns the current particle system
  64654. */
  64655. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  64656. // Do nothing as start size is not supported by GPUParticleSystem
  64657. return this;
  64658. };
  64659. /**
  64660. * Not supported by GPUParticleSystem
  64661. * @param gradient defines the gradient to remove
  64662. * @returns the current particle system
  64663. */
  64664. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  64665. // Do nothing as start size is not supported by GPUParticleSystem
  64666. return this;
  64667. };
  64668. /**
  64669. * Not supported by GPUParticleSystem
  64670. * @param gradient defines the gradient to use (between 0 and 1)
  64671. * @param color defines the color to affect to the specified gradient
  64672. * @returns the current particle system
  64673. */
  64674. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  64675. //Not supported by GPUParticleSystem
  64676. return this;
  64677. };
  64678. /**
  64679. * Not supported by GPUParticleSystem
  64680. * @param gradient defines the gradient to remove
  64681. * @returns the current particle system
  64682. */
  64683. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  64684. //Not supported by GPUParticleSystem
  64685. return this;
  64686. };
  64687. /**
  64688. * Not supported by GPUParticleSystem
  64689. * @returns the list of ramp gradients
  64690. */
  64691. GPUParticleSystem.prototype.getRampGradients = function () {
  64692. return null;
  64693. };
  64694. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  64695. /**
  64696. * Not supported by GPUParticleSystem
  64697. * Gets or sets a boolean indicating that ramp gradients must be used
  64698. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  64699. */
  64700. get: function () {
  64701. //Not supported by GPUParticleSystem
  64702. return false;
  64703. },
  64704. set: function (value) {
  64705. //Not supported by GPUParticleSystem
  64706. },
  64707. enumerable: true,
  64708. configurable: true
  64709. });
  64710. /**
  64711. * Not supported by GPUParticleSystem
  64712. * @param gradient defines the gradient to use (between 0 and 1)
  64713. * @param factor defines the life time factor to affect to the specified gradient
  64714. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64715. * @returns the current particle system
  64716. */
  64717. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  64718. //Not supported by GPUParticleSystem
  64719. return this;
  64720. };
  64721. /**
  64722. * Not supported by GPUParticleSystem
  64723. * @param gradient defines the gradient to remove
  64724. * @returns the current particle system
  64725. */
  64726. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  64727. //Not supported by GPUParticleSystem
  64728. return this;
  64729. };
  64730. GPUParticleSystem.prototype._reset = function () {
  64731. this._releaseBuffers();
  64732. };
  64733. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  64734. var updateVertexBuffers = {};
  64735. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  64736. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  64737. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  64738. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  64739. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  64740. var offset = 12;
  64741. if (!this._colorGradientsTexture) {
  64742. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  64743. offset += 4;
  64744. }
  64745. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  64746. offset += 3;
  64747. if (!this._isBillboardBased) {
  64748. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  64749. offset += 3;
  64750. }
  64751. if (this._angularSpeedGradientsTexture) {
  64752. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  64753. offset += 1;
  64754. }
  64755. else {
  64756. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  64757. offset += 2;
  64758. }
  64759. if (this._isAnimationSheetEnabled) {
  64760. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  64761. offset += 1;
  64762. if (this.spriteRandomStartCell) {
  64763. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  64764. offset += 1;
  64765. }
  64766. }
  64767. if (this.noiseTexture) {
  64768. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  64769. offset += 3;
  64770. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  64771. offset += 3;
  64772. }
  64773. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  64774. this._engine.bindArrayBuffer(null);
  64775. return vao;
  64776. };
  64777. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  64778. var renderVertexBuffers = {};
  64779. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  64780. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  64781. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  64782. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  64783. var offset = 12;
  64784. if (!this._colorGradientsTexture) {
  64785. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  64786. offset += 4;
  64787. }
  64788. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  64789. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  64790. }
  64791. offset += 3; // Direction
  64792. if (!this._isBillboardBased) {
  64793. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  64794. offset += 3;
  64795. }
  64796. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  64797. if (this._angularSpeedGradientsTexture) {
  64798. offset++;
  64799. }
  64800. else {
  64801. offset += 2;
  64802. }
  64803. if (this._isAnimationSheetEnabled) {
  64804. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  64805. offset += 1;
  64806. if (this.spriteRandomStartCell) {
  64807. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  64808. offset += 1;
  64809. }
  64810. }
  64811. if (this.noiseTexture) {
  64812. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  64813. offset += 3;
  64814. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  64815. offset += 3;
  64816. }
  64817. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  64818. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  64819. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  64820. this._engine.bindArrayBuffer(null);
  64821. return vao;
  64822. };
  64823. GPUParticleSystem.prototype._initialize = function (force) {
  64824. if (force === void 0) { force = false; }
  64825. if (this._buffer0 && !force) {
  64826. return;
  64827. }
  64828. var engine = this._scene.getEngine();
  64829. var data = new Array();
  64830. if (!this.isBillboardBased) {
  64831. this._attributesStrideSize += 3;
  64832. }
  64833. if (this._colorGradientsTexture) {
  64834. this._attributesStrideSize -= 4;
  64835. }
  64836. if (this._angularSpeedGradientsTexture) {
  64837. this._attributesStrideSize -= 1;
  64838. }
  64839. if (this._isAnimationSheetEnabled) {
  64840. this._attributesStrideSize += 1;
  64841. if (this.spriteRandomStartCell) {
  64842. this._attributesStrideSize += 1;
  64843. }
  64844. }
  64845. if (this.noiseTexture) {
  64846. this._attributesStrideSize += 6;
  64847. }
  64848. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  64849. // position
  64850. data.push(0.0);
  64851. data.push(0.0);
  64852. data.push(0.0);
  64853. // Age and life
  64854. data.push(0.0); // create the particle as a dead one to create a new one at start
  64855. data.push(0.0);
  64856. // Seed
  64857. data.push(Math.random());
  64858. data.push(Math.random());
  64859. data.push(Math.random());
  64860. data.push(Math.random());
  64861. // Size
  64862. data.push(0.0);
  64863. data.push(0.0);
  64864. data.push(0.0);
  64865. if (!this._colorGradientsTexture) {
  64866. // color
  64867. data.push(0.0);
  64868. data.push(0.0);
  64869. data.push(0.0);
  64870. data.push(0.0);
  64871. }
  64872. // direction
  64873. data.push(0.0);
  64874. data.push(0.0);
  64875. data.push(0.0);
  64876. if (!this.isBillboardBased) {
  64877. // initialDirection
  64878. data.push(0.0);
  64879. data.push(0.0);
  64880. data.push(0.0);
  64881. }
  64882. // angle
  64883. data.push(0.0);
  64884. if (!this._angularSpeedGradientsTexture) {
  64885. data.push(0.0);
  64886. }
  64887. if (this._isAnimationSheetEnabled) {
  64888. data.push(0.0);
  64889. if (this.spriteRandomStartCell) {
  64890. data.push(0.0);
  64891. }
  64892. }
  64893. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  64894. data.push(Math.random());
  64895. data.push(Math.random());
  64896. data.push(Math.random());
  64897. data.push(Math.random());
  64898. data.push(Math.random());
  64899. data.push(Math.random());
  64900. }
  64901. }
  64902. // Sprite data
  64903. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  64904. -0.5, 0.5, 0, 1,
  64905. -0.5, -0.5, 0, 0,
  64906. 0.5, -0.5, 1, 0]);
  64907. // Buffers
  64908. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64909. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64910. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  64911. // Update VAO
  64912. this._updateVAO = [];
  64913. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  64914. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  64915. // Render VAO
  64916. this._renderVAO = [];
  64917. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  64918. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  64919. // Links
  64920. this._sourceBuffer = this._buffer0;
  64921. this._targetBuffer = this._buffer1;
  64922. };
  64923. /** @hidden */
  64924. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  64925. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  64926. if (this._isBillboardBased) {
  64927. defines += "\n#define BILLBOARD";
  64928. }
  64929. if (this._colorGradientsTexture) {
  64930. defines += "\n#define COLORGRADIENTS";
  64931. }
  64932. if (this._sizeGradientsTexture) {
  64933. defines += "\n#define SIZEGRADIENTS";
  64934. }
  64935. if (this._angularSpeedGradientsTexture) {
  64936. defines += "\n#define ANGULARSPEEDGRADIENTS";
  64937. }
  64938. if (this._velocityGradientsTexture) {
  64939. defines += "\n#define VELOCITYGRADIENTS";
  64940. }
  64941. if (this._limitVelocityGradientsTexture) {
  64942. defines += "\n#define LIMITVELOCITYGRADIENTS";
  64943. }
  64944. if (this._dragGradientsTexture) {
  64945. defines += "\n#define DRAGGRADIENTS";
  64946. }
  64947. if (this.isAnimationSheetEnabled) {
  64948. defines += "\n#define ANIMATESHEET";
  64949. if (this.spriteRandomStartCell) {
  64950. defines += "\n#define ANIMATESHEETRANDOMSTART";
  64951. }
  64952. }
  64953. if (this.noiseTexture) {
  64954. defines += "\n#define NOISE";
  64955. }
  64956. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  64957. return;
  64958. }
  64959. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  64960. if (!this._colorGradientsTexture) {
  64961. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  64962. }
  64963. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  64964. if (!this._isBillboardBased) {
  64965. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  64966. }
  64967. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  64968. if (this.isAnimationSheetEnabled) {
  64969. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  64970. if (this.spriteRandomStartCell) {
  64971. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  64972. }
  64973. }
  64974. if (this.noiseTexture) {
  64975. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  64976. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  64977. }
  64978. this._updateEffectOptions.defines = defines;
  64979. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  64980. };
  64981. /** @hidden */
  64982. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  64983. var defines = "";
  64984. if (this._scene.clipPlane) {
  64985. defines = "\n#define CLIPPLANE";
  64986. }
  64987. if (this._scene.clipPlane2) {
  64988. defines = "\n#define CLIPPLANE2";
  64989. }
  64990. if (this._scene.clipPlane3) {
  64991. defines = "\n#define CLIPPLANE3";
  64992. }
  64993. if (this._scene.clipPlane4) {
  64994. defines = "\n#define CLIPPLANE4";
  64995. }
  64996. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  64997. defines = "\n#define BLENDMULTIPLYMODE";
  64998. }
  64999. if (this._isBillboardBased) {
  65000. defines += "\n#define BILLBOARD";
  65001. switch (this.billboardMode) {
  65002. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  65003. defines += "\n#define BILLBOARDY";
  65004. break;
  65005. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  65006. defines += "\n#define BILLBOARDSTRETCHED";
  65007. break;
  65008. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  65009. default:
  65010. break;
  65011. }
  65012. }
  65013. if (this._colorGradientsTexture) {
  65014. defines += "\n#define COLORGRADIENTS";
  65015. }
  65016. if (this.isAnimationSheetEnabled) {
  65017. defines += "\n#define ANIMATESHEET";
  65018. }
  65019. if (this._imageProcessingConfiguration) {
  65020. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  65021. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  65022. }
  65023. if (this._renderEffect && this._renderEffect.defines === defines) {
  65024. return;
  65025. }
  65026. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  65027. var samplers = ["textureSampler", "colorGradientSampler"];
  65028. if (BABYLON.ImageProcessingConfiguration) {
  65029. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  65030. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  65031. }
  65032. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  65033. };
  65034. /**
  65035. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  65036. * @param preWarm defines if we are in the pre-warmimg phase
  65037. */
  65038. GPUParticleSystem.prototype.animate = function (preWarm) {
  65039. if (preWarm === void 0) { preWarm = false; }
  65040. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  65041. this._actualFrame += this._timeDelta;
  65042. if (!this._stopped) {
  65043. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  65044. this.stop();
  65045. }
  65046. }
  65047. };
  65048. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  65049. var texture = this[textureName];
  65050. if (!factorGradients || !factorGradients.length || texture) {
  65051. return;
  65052. }
  65053. var data = new Float32Array(this._rawTextureWidth);
  65054. for (var x = 0; x < this._rawTextureWidth; x++) {
  65055. var ratio = x / this._rawTextureWidth;
  65056. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  65057. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  65058. });
  65059. }
  65060. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65061. };
  65062. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  65063. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  65064. };
  65065. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  65066. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  65067. };
  65068. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  65069. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  65070. };
  65071. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  65072. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  65073. };
  65074. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  65075. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  65076. };
  65077. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  65078. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  65079. return;
  65080. }
  65081. var data = new Uint8Array(this._rawTextureWidth * 4);
  65082. var tmpColor = BABYLON.Tmp.Color4[0];
  65083. for (var x = 0; x < this._rawTextureWidth; x++) {
  65084. var ratio = x / this._rawTextureWidth;
  65085. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  65086. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  65087. data[x * 4] = tmpColor.r * 255;
  65088. data[x * 4 + 1] = tmpColor.g * 255;
  65089. data[x * 4 + 2] = tmpColor.b * 255;
  65090. data[x * 4 + 3] = tmpColor.a * 255;
  65091. });
  65092. }
  65093. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65094. };
  65095. /**
  65096. * Renders the particle system in its current state
  65097. * @param preWarm defines if the system should only update the particles but not render them
  65098. * @returns the current number of particles
  65099. */
  65100. GPUParticleSystem.prototype.render = function (preWarm) {
  65101. if (preWarm === void 0) { preWarm = false; }
  65102. if (!this._started) {
  65103. return 0;
  65104. }
  65105. this._createColorGradientTexture();
  65106. this._createSizeGradientTexture();
  65107. this._createAngularSpeedGradientTexture();
  65108. this._createVelocityGradientTexture();
  65109. this._createLimitVelocityGradientTexture();
  65110. this._createDragGradientTexture();
  65111. this._recreateUpdateEffect();
  65112. this._recreateRenderEffect();
  65113. if (!this.isReady()) {
  65114. return 0;
  65115. }
  65116. if (!preWarm) {
  65117. if (!this._preWarmDone && this.preWarmCycles) {
  65118. for (var index = 0; index < this.preWarmCycles; index++) {
  65119. this.animate(true);
  65120. this.render(true);
  65121. }
  65122. this._preWarmDone = true;
  65123. }
  65124. if (this._currentRenderId === this._scene.getRenderId()) {
  65125. return 0;
  65126. }
  65127. this._currentRenderId = this._scene.getRenderId();
  65128. }
  65129. // Get everything ready to render
  65130. this._initialize();
  65131. this._accumulatedCount += this.emitRate * this._timeDelta;
  65132. if (this._accumulatedCount > 1) {
  65133. var intPart = this._accumulatedCount | 0;
  65134. this._accumulatedCount -= intPart;
  65135. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  65136. }
  65137. if (!this._currentActiveCount) {
  65138. return 0;
  65139. }
  65140. // Enable update effect
  65141. this._engine.enableEffect(this._updateEffect);
  65142. this._engine.setState(false);
  65143. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  65144. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  65145. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  65146. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  65147. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  65148. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  65149. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  65150. if (!this._colorGradientsTexture) {
  65151. this._updateEffect.setDirectColor4("color1", this.color1);
  65152. this._updateEffect.setDirectColor4("color2", this.color2);
  65153. }
  65154. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  65155. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  65156. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  65157. this._updateEffect.setVector3("gravity", this.gravity);
  65158. if (this._sizeGradientsTexture) {
  65159. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  65160. }
  65161. if (this._angularSpeedGradientsTexture) {
  65162. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  65163. }
  65164. if (this._velocityGradientsTexture) {
  65165. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  65166. }
  65167. if (this._limitVelocityGradientsTexture) {
  65168. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  65169. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  65170. }
  65171. if (this._dragGradientsTexture) {
  65172. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  65173. }
  65174. if (this.particleEmitterType) {
  65175. this.particleEmitterType.applyToShader(this._updateEffect);
  65176. }
  65177. if (this._isAnimationSheetEnabled) {
  65178. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  65179. }
  65180. if (this.noiseTexture) {
  65181. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  65182. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  65183. }
  65184. var emitterWM;
  65185. if (this.emitter.position) {
  65186. var emitterMesh = this.emitter;
  65187. emitterWM = emitterMesh.getWorldMatrix();
  65188. }
  65189. else {
  65190. var emitterPosition = this.emitter;
  65191. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  65192. }
  65193. this._updateEffect.setMatrix("emitterWM", emitterWM);
  65194. // Bind source VAO
  65195. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  65196. // Update
  65197. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  65198. this._engine.setRasterizerState(false);
  65199. this._engine.beginTransformFeedback(true);
  65200. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  65201. this._engine.endTransformFeedback();
  65202. this._engine.setRasterizerState(true);
  65203. this._engine.bindTransformFeedbackBuffer(null);
  65204. if (!preWarm) {
  65205. // Enable render effect
  65206. this._engine.enableEffect(this._renderEffect);
  65207. var viewMatrix = this._scene.getViewMatrix();
  65208. this._renderEffect.setMatrix("view", viewMatrix);
  65209. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  65210. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  65211. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  65212. if (this._colorGradientsTexture) {
  65213. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  65214. }
  65215. else {
  65216. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  65217. }
  65218. if (this._isAnimationSheetEnabled && this.particleTexture) {
  65219. var baseSize = this.particleTexture.getBaseSize();
  65220. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  65221. }
  65222. if (this._isBillboardBased) {
  65223. var camera = this._scene.activeCamera;
  65224. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  65225. }
  65226. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  65227. var invView = viewMatrix.clone();
  65228. invView.invert();
  65229. this._renderEffect.setMatrix("invView", invView);
  65230. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  65231. }
  65232. // image processing
  65233. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  65234. this._imageProcessingConfiguration.bind(this._renderEffect);
  65235. }
  65236. // Draw order
  65237. switch (this.blendMode) {
  65238. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  65239. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  65240. break;
  65241. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  65242. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  65243. break;
  65244. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  65245. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65246. break;
  65247. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  65248. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  65249. break;
  65250. }
  65251. if (this.forceDepthWrite) {
  65252. this._engine.setDepthWrite(true);
  65253. }
  65254. // Bind source VAO
  65255. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  65256. // Render
  65257. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  65258. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65259. }
  65260. // Switch VAOs
  65261. this._targetIndex++;
  65262. if (this._targetIndex === 2) {
  65263. this._targetIndex = 0;
  65264. }
  65265. // Switch buffers
  65266. var tmpBuffer = this._sourceBuffer;
  65267. this._sourceBuffer = this._targetBuffer;
  65268. this._targetBuffer = tmpBuffer;
  65269. return this._currentActiveCount;
  65270. };
  65271. /**
  65272. * Rebuilds the particle system
  65273. */
  65274. GPUParticleSystem.prototype.rebuild = function () {
  65275. this._initialize(true);
  65276. };
  65277. GPUParticleSystem.prototype._releaseBuffers = function () {
  65278. if (this._buffer0) {
  65279. this._buffer0.dispose();
  65280. this._buffer0 = null;
  65281. }
  65282. if (this._buffer1) {
  65283. this._buffer1.dispose();
  65284. this._buffer1 = null;
  65285. }
  65286. if (this._spriteBuffer) {
  65287. this._spriteBuffer.dispose();
  65288. this._spriteBuffer = null;
  65289. }
  65290. };
  65291. GPUParticleSystem.prototype._releaseVAOs = function () {
  65292. if (!this._updateVAO) {
  65293. return;
  65294. }
  65295. for (var index = 0; index < this._updateVAO.length; index++) {
  65296. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  65297. }
  65298. this._updateVAO = [];
  65299. for (var index = 0; index < this._renderVAO.length; index++) {
  65300. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  65301. }
  65302. this._renderVAO = [];
  65303. };
  65304. /**
  65305. * Disposes the particle system and free the associated resources
  65306. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  65307. */
  65308. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  65309. if (disposeTexture === void 0) { disposeTexture = true; }
  65310. var index = this._scene.particleSystems.indexOf(this);
  65311. if (index > -1) {
  65312. this._scene.particleSystems.splice(index, 1);
  65313. }
  65314. this._releaseBuffers();
  65315. this._releaseVAOs();
  65316. if (this._colorGradientsTexture) {
  65317. this._colorGradientsTexture.dispose();
  65318. this._colorGradientsTexture = null;
  65319. }
  65320. if (this._sizeGradientsTexture) {
  65321. this._sizeGradientsTexture.dispose();
  65322. this._sizeGradientsTexture = null;
  65323. }
  65324. if (this._angularSpeedGradientsTexture) {
  65325. this._angularSpeedGradientsTexture.dispose();
  65326. this._angularSpeedGradientsTexture = null;
  65327. }
  65328. if (this._velocityGradientsTexture) {
  65329. this._velocityGradientsTexture.dispose();
  65330. this._velocityGradientsTexture = null;
  65331. }
  65332. if (this._limitVelocityGradientsTexture) {
  65333. this._limitVelocityGradientsTexture.dispose();
  65334. this._limitVelocityGradientsTexture = null;
  65335. }
  65336. if (this._dragGradientsTexture) {
  65337. this._dragGradientsTexture.dispose();
  65338. this._dragGradientsTexture = null;
  65339. }
  65340. if (this._randomTexture) {
  65341. this._randomTexture.dispose();
  65342. this._randomTexture = null;
  65343. }
  65344. if (this._randomTexture2) {
  65345. this._randomTexture2.dispose();
  65346. this._randomTexture2 = null;
  65347. }
  65348. if (disposeTexture && this.particleTexture) {
  65349. this.particleTexture.dispose();
  65350. this.particleTexture = null;
  65351. }
  65352. if (disposeTexture && this.noiseTexture) {
  65353. this.noiseTexture.dispose();
  65354. this.noiseTexture = null;
  65355. }
  65356. // Callback
  65357. this.onDisposeObservable.notifyObservers(this);
  65358. this.onDisposeObservable.clear();
  65359. };
  65360. /**
  65361. * Clones the particle system.
  65362. * @param name The name of the cloned object
  65363. * @param newEmitter The new emitter to use
  65364. * @returns the cloned particle system
  65365. */
  65366. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  65367. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  65368. BABYLON.Tools.DeepCopy(this, result);
  65369. if (newEmitter === undefined) {
  65370. newEmitter = this.emitter;
  65371. }
  65372. result.emitter = newEmitter;
  65373. if (this.particleTexture) {
  65374. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  65375. }
  65376. return result;
  65377. };
  65378. /**
  65379. * Serializes the particle system to a JSON object.
  65380. * @returns the JSON object
  65381. */
  65382. GPUParticleSystem.prototype.serialize = function () {
  65383. var serializationObject = {};
  65384. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  65385. serializationObject.activeParticleCount = this.activeParticleCount;
  65386. return serializationObject;
  65387. };
  65388. /**
  65389. * Parses a JSON object to create a GPU particle system.
  65390. * @param parsedParticleSystem The JSON object to parse
  65391. * @param scene The scene to create the particle system in
  65392. * @param rootUrl The root url to use to load external dependencies like texture
  65393. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  65394. * @returns the parsed GPU particle system
  65395. */
  65396. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  65397. if (doNotStart === void 0) { doNotStart = false; }
  65398. var name = parsedParticleSystem.name;
  65399. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  65400. if (parsedParticleSystem.activeParticleCount) {
  65401. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  65402. }
  65403. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  65404. // Auto start
  65405. if (parsedParticleSystem.preventAutoStart) {
  65406. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  65407. }
  65408. if (!doNotStart && !particleSystem.preventAutoStart) {
  65409. particleSystem.start();
  65410. }
  65411. return particleSystem;
  65412. };
  65413. return GPUParticleSystem;
  65414. }(BABYLON.BaseParticleSystem));
  65415. BABYLON.GPUParticleSystem = GPUParticleSystem;
  65416. })(BABYLON || (BABYLON = {}));
  65417. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  65418. var BABYLON;
  65419. (function (BABYLON) {
  65420. /**
  65421. * Represents one particle of a solid particle system.
  65422. */
  65423. var SolidParticle = /** @class */ (function () {
  65424. /**
  65425. * Creates a Solid Particle object.
  65426. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  65427. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  65428. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  65429. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  65430. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  65431. * @param shapeId (integer) is the model shape identifier in the SPS.
  65432. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  65433. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  65434. */
  65435. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  65436. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  65437. /**
  65438. * particle global index
  65439. */
  65440. this.idx = 0;
  65441. /**
  65442. * The color of the particle
  65443. */
  65444. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65445. /**
  65446. * The world space position of the particle.
  65447. */
  65448. this.position = BABYLON.Vector3.Zero();
  65449. /**
  65450. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  65451. */
  65452. this.rotation = BABYLON.Vector3.Zero();
  65453. /**
  65454. * The scaling of the particle.
  65455. */
  65456. this.scaling = BABYLON.Vector3.One();
  65457. /**
  65458. * The uvs of the particle.
  65459. */
  65460. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  65461. /**
  65462. * The current speed of the particle.
  65463. */
  65464. this.velocity = BABYLON.Vector3.Zero();
  65465. /**
  65466. * The pivot point in the particle local space.
  65467. */
  65468. this.pivot = BABYLON.Vector3.Zero();
  65469. /**
  65470. * Must the particle be translated from its pivot point in its local space ?
  65471. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  65472. * Default : false
  65473. */
  65474. this.translateFromPivot = false;
  65475. /**
  65476. * Is the particle active or not ?
  65477. */
  65478. this.alive = true;
  65479. /**
  65480. * Is the particle visible or not ?
  65481. */
  65482. this.isVisible = true;
  65483. /**
  65484. * Index of this particle in the global "positions" array (Internal use)
  65485. * @hidden
  65486. */
  65487. this._pos = 0;
  65488. /**
  65489. * @hidden Index of this particle in the global "indices" array (Internal use)
  65490. */
  65491. this._ind = 0;
  65492. /**
  65493. * ModelShape id of this particle
  65494. */
  65495. this.shapeId = 0;
  65496. /**
  65497. * Index of the particle in its shape id (Internal use)
  65498. */
  65499. this.idxInShape = 0;
  65500. /**
  65501. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  65502. */
  65503. this._stillInvisible = false;
  65504. /**
  65505. * @hidden Last computed particle rotation matrix
  65506. */
  65507. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  65508. /**
  65509. * Parent particle Id, if any.
  65510. * Default null.
  65511. */
  65512. this.parentId = null;
  65513. /**
  65514. * @hidden Internal global position in the SPS.
  65515. */
  65516. this._globalPosition = BABYLON.Vector3.Zero();
  65517. this.idx = particleIndex;
  65518. this._pos = positionIndex;
  65519. this._ind = indiceIndex;
  65520. this._model = model;
  65521. this.shapeId = shapeId;
  65522. this.idxInShape = idxInShape;
  65523. this._sps = sps;
  65524. if (modelBoundingInfo) {
  65525. this._modelBoundingInfo = modelBoundingInfo;
  65526. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  65527. }
  65528. }
  65529. Object.defineProperty(SolidParticle.prototype, "scale", {
  65530. /**
  65531. * Legacy support, changed scale to scaling
  65532. */
  65533. get: function () {
  65534. return this.scaling;
  65535. },
  65536. /**
  65537. * Legacy support, changed scale to scaling
  65538. */
  65539. set: function (scale) {
  65540. this.scaling = scale;
  65541. },
  65542. enumerable: true,
  65543. configurable: true
  65544. });
  65545. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  65546. /**
  65547. * Legacy support, changed quaternion to rotationQuaternion
  65548. */
  65549. get: function () {
  65550. return this.rotationQuaternion;
  65551. },
  65552. /**
  65553. * Legacy support, changed quaternion to rotationQuaternion
  65554. */
  65555. set: function (q) {
  65556. this.rotationQuaternion = q;
  65557. },
  65558. enumerable: true,
  65559. configurable: true
  65560. });
  65561. /**
  65562. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  65563. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  65564. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  65565. * @returns true if it intersects
  65566. */
  65567. SolidParticle.prototype.intersectsMesh = function (target) {
  65568. if (!this._boundingInfo || !target._boundingInfo) {
  65569. return false;
  65570. }
  65571. if (this._sps._bSphereOnly) {
  65572. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  65573. }
  65574. return this._boundingInfo.intersects(target._boundingInfo, false);
  65575. };
  65576. return SolidParticle;
  65577. }());
  65578. BABYLON.SolidParticle = SolidParticle;
  65579. /**
  65580. * Represents the shape of the model used by one particle of a solid particle system.
  65581. * SPS internal tool, don't use it manually.
  65582. */
  65583. var ModelShape = /** @class */ (function () {
  65584. /**
  65585. * 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.
  65586. * SPS internal tool, don't use it manually.
  65587. * @hidden
  65588. */
  65589. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  65590. /**
  65591. * length of the shape in the model indices array (internal use)
  65592. * @hidden
  65593. */
  65594. this._indicesLength = 0;
  65595. this.shapeID = id;
  65596. this._shape = shape;
  65597. this._indicesLength = indicesLength;
  65598. this._shapeUV = shapeUV;
  65599. this._positionFunction = posFunction;
  65600. this._vertexFunction = vtxFunction;
  65601. }
  65602. return ModelShape;
  65603. }());
  65604. BABYLON.ModelShape = ModelShape;
  65605. /**
  65606. * Represents a Depth Sorted Particle in the solid particle system.
  65607. */
  65608. var DepthSortedParticle = /** @class */ (function () {
  65609. function DepthSortedParticle() {
  65610. /**
  65611. * Index of the particle in the "indices" array
  65612. */
  65613. this.ind = 0;
  65614. /**
  65615. * Length of the particle shape in the "indices" array
  65616. */
  65617. this.indicesLength = 0;
  65618. /**
  65619. * Squared distance from the particle to the camera
  65620. */
  65621. this.sqDistance = 0.0;
  65622. }
  65623. return DepthSortedParticle;
  65624. }());
  65625. BABYLON.DepthSortedParticle = DepthSortedParticle;
  65626. })(BABYLON || (BABYLON = {}));
  65627. //# sourceMappingURL=babylon.solidParticle.js.map
  65628. var BABYLON;
  65629. (function (BABYLON) {
  65630. /**
  65631. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  65632. *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.
  65633. * The SPS is also a particle system. It provides some methods to manage the particles.
  65634. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  65635. *
  65636. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  65637. */
  65638. var SolidParticleSystem = /** @class */ (function () {
  65639. /**
  65640. * Creates a SPS (Solid Particle System) object.
  65641. * @param name (String) is the SPS name, this will be the underlying mesh name.
  65642. * @param scene (Scene) is the scene in which the SPS is added.
  65643. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  65644. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  65645. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  65646. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  65647. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  65648. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  65649. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  65650. */
  65651. function SolidParticleSystem(name, scene, options) {
  65652. /**
  65653. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  65654. * Example : var p = SPS.particles[i];
  65655. */
  65656. this.particles = new Array();
  65657. /**
  65658. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  65659. */
  65660. this.nbParticles = 0;
  65661. /**
  65662. * If the particles must ever face the camera (default false). Useful for planar particles.
  65663. */
  65664. this.billboard = false;
  65665. /**
  65666. * Recompute normals when adding a shape
  65667. */
  65668. this.recomputeNormals = true;
  65669. /**
  65670. * This a counter ofr your own usage. It's not set by any SPS functions.
  65671. */
  65672. this.counter = 0;
  65673. /**
  65674. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  65675. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  65676. */
  65677. this.vars = {};
  65678. /**
  65679. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  65680. * @hidden
  65681. */
  65682. this._bSphereOnly = false;
  65683. /**
  65684. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  65685. * @hidden
  65686. */
  65687. this._bSphereRadiusFactor = 1.0;
  65688. this._positions = new Array();
  65689. this._indices = new Array();
  65690. this._normals = new Array();
  65691. this._colors = new Array();
  65692. this._uvs = new Array();
  65693. this._index = 0; // indices index
  65694. this._updatable = true;
  65695. this._pickable = false;
  65696. this._isVisibilityBoxLocked = false;
  65697. this._alwaysVisible = false;
  65698. this._depthSort = false;
  65699. this._shapeCounter = 0;
  65700. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  65701. this._color = new BABYLON.Color4(0, 0, 0, 0);
  65702. this._computeParticleColor = true;
  65703. this._computeParticleTexture = true;
  65704. this._computeParticleRotation = true;
  65705. this._computeParticleVertex = false;
  65706. this._computeBoundingBox = false;
  65707. this._depthSortParticles = true;
  65708. this._cam_axisZ = BABYLON.Vector3.Zero();
  65709. this._cam_axisY = BABYLON.Vector3.Zero();
  65710. this._cam_axisX = BABYLON.Vector3.Zero();
  65711. this._axisZ = BABYLON.Axis.Z;
  65712. this._camDir = BABYLON.Vector3.Zero();
  65713. this._camInvertedPosition = BABYLON.Vector3.Zero();
  65714. this._rotMatrix = new BABYLON.Matrix();
  65715. this._invertMatrix = new BABYLON.Matrix();
  65716. this._rotated = BABYLON.Vector3.Zero();
  65717. this._quaternion = new BABYLON.Quaternion();
  65718. this._vertex = BABYLON.Vector3.Zero();
  65719. this._normal = BABYLON.Vector3.Zero();
  65720. this._yaw = 0.0;
  65721. this._pitch = 0.0;
  65722. this._roll = 0.0;
  65723. this._halfroll = 0.0;
  65724. this._halfpitch = 0.0;
  65725. this._halfyaw = 0.0;
  65726. this._sinRoll = 0.0;
  65727. this._cosRoll = 0.0;
  65728. this._sinPitch = 0.0;
  65729. this._cosPitch = 0.0;
  65730. this._sinYaw = 0.0;
  65731. this._cosYaw = 0.0;
  65732. this._mustUnrotateFixedNormals = false;
  65733. this._minimum = BABYLON.Vector3.Zero();
  65734. this._maximum = BABYLON.Vector3.Zero();
  65735. this._minBbox = BABYLON.Vector3.Zero();
  65736. this._maxBbox = BABYLON.Vector3.Zero();
  65737. this._particlesIntersect = false;
  65738. this._depthSortFunction = function (p1, p2) {
  65739. return (p2.sqDistance - p1.sqDistance);
  65740. };
  65741. this._needs32Bits = false;
  65742. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  65743. this._scaledPivot = BABYLON.Vector3.Zero();
  65744. this._particleHasParent = false;
  65745. this.name = name;
  65746. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65747. this._camera = scene.activeCamera;
  65748. this._pickable = options ? options.isPickable : false;
  65749. this._depthSort = options ? options.enableDepthSort : false;
  65750. this._particlesIntersect = options ? options.particleIntersection : false;
  65751. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  65752. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  65753. if (options && options.updatable !== undefined) {
  65754. this._updatable = options.updatable;
  65755. }
  65756. else {
  65757. this._updatable = true;
  65758. }
  65759. if (this._pickable) {
  65760. this.pickedParticles = [];
  65761. }
  65762. if (this._depthSort) {
  65763. this.depthSortedParticles = [];
  65764. }
  65765. }
  65766. /**
  65767. * Builds the SPS underlying mesh. Returns a standard Mesh.
  65768. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  65769. * @returns the created mesh
  65770. */
  65771. SolidParticleSystem.prototype.buildMesh = function () {
  65772. if (this.nbParticles === 0) {
  65773. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  65774. this.addShape(triangle, 1);
  65775. triangle.dispose();
  65776. }
  65777. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  65778. this._positions32 = new Float32Array(this._positions);
  65779. this._uvs32 = new Float32Array(this._uvs);
  65780. this._colors32 = new Float32Array(this._colors);
  65781. if (this.recomputeNormals) {
  65782. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  65783. }
  65784. this._normals32 = new Float32Array(this._normals);
  65785. this._fixedNormal32 = new Float32Array(this._normals);
  65786. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  65787. this._unrotateFixedNormals();
  65788. }
  65789. var vertexData = new BABYLON.VertexData();
  65790. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  65791. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  65792. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  65793. if (this._uvs32.length > 0) {
  65794. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  65795. }
  65796. if (this._colors32.length > 0) {
  65797. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  65798. }
  65799. var mesh = new BABYLON.Mesh(this.name, this._scene);
  65800. vertexData.applyToMesh(mesh, this._updatable);
  65801. this.mesh = mesh;
  65802. this.mesh.isPickable = this._pickable;
  65803. // free memory
  65804. if (!this._depthSort) {
  65805. this._indices = null;
  65806. }
  65807. this._positions = null;
  65808. this._normals = null;
  65809. this._uvs = null;
  65810. this._colors = null;
  65811. if (!this._updatable) {
  65812. this.particles.length = 0;
  65813. }
  65814. return mesh;
  65815. };
  65816. /**
  65817. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  65818. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  65819. * Thus the particles generated from `digest()` have their property `position` set yet.
  65820. * @param mesh ( Mesh ) is the mesh to be digested
  65821. * @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
  65822. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  65823. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  65824. * @returns the current SPS
  65825. */
  65826. SolidParticleSystem.prototype.digest = function (mesh, options) {
  65827. var size = (options && options.facetNb) || 1;
  65828. var number = (options && options.number) || 0;
  65829. var delta = (options && options.delta) || 0;
  65830. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65831. var meshInd = mesh.getIndices();
  65832. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65833. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65834. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65835. var f = 0; // facet counter
  65836. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  65837. // compute size from number
  65838. if (number) {
  65839. number = (number > totalFacets) ? totalFacets : number;
  65840. size = Math.round(totalFacets / number);
  65841. delta = 0;
  65842. }
  65843. else {
  65844. size = (size > totalFacets) ? totalFacets : size;
  65845. }
  65846. var facetPos = []; // submesh positions
  65847. var facetInd = []; // submesh indices
  65848. var facetUV = []; // submesh UV
  65849. var facetCol = []; // submesh colors
  65850. var barycenter = BABYLON.Vector3.Zero();
  65851. var sizeO = size;
  65852. while (f < totalFacets) {
  65853. size = sizeO + Math.floor((1 + delta) * Math.random());
  65854. if (f > totalFacets - size) {
  65855. size = totalFacets - f;
  65856. }
  65857. // reset temp arrays
  65858. facetPos.length = 0;
  65859. facetInd.length = 0;
  65860. facetUV.length = 0;
  65861. facetCol.length = 0;
  65862. // iterate over "size" facets
  65863. var fi = 0;
  65864. for (var j = f * 3; j < (f + size) * 3; j++) {
  65865. facetInd.push(fi);
  65866. var i = meshInd[j];
  65867. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  65868. if (meshUV) {
  65869. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  65870. }
  65871. if (meshCol) {
  65872. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  65873. }
  65874. fi++;
  65875. }
  65876. // create a model shape for each single particle
  65877. var idx = this.nbParticles;
  65878. var shape = this._posToShape(facetPos);
  65879. var shapeUV = this._uvsToShapeUV(facetUV);
  65880. // compute the barycenter of the shape
  65881. var v;
  65882. for (v = 0; v < shape.length; v++) {
  65883. barycenter.addInPlace(shape[v]);
  65884. }
  65885. barycenter.scaleInPlace(1 / shape.length);
  65886. // shift the shape from its barycenter to the origin
  65887. for (v = 0; v < shape.length; v++) {
  65888. shape[v].subtractInPlace(barycenter);
  65889. }
  65890. var bInfo;
  65891. if (this._particlesIntersect) {
  65892. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  65893. }
  65894. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  65895. // add the particle in the SPS
  65896. var currentPos = this._positions.length;
  65897. var currentInd = this._indices.length;
  65898. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  65899. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  65900. // initialize the particle position
  65901. this.particles[this.nbParticles].position.addInPlace(barycenter);
  65902. this._index += shape.length;
  65903. idx++;
  65904. this.nbParticles++;
  65905. this._shapeCounter++;
  65906. f += size;
  65907. }
  65908. return this;
  65909. };
  65910. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  65911. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  65912. var index = 0;
  65913. var idx = 0;
  65914. for (var p = 0; p < this.particles.length; p++) {
  65915. this._particle = this.particles[p];
  65916. this._shape = this._particle._model._shape;
  65917. if (this._particle.rotationQuaternion) {
  65918. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65919. }
  65920. else {
  65921. this._yaw = this._particle.rotation.y;
  65922. this._pitch = this._particle.rotation.x;
  65923. this._roll = this._particle.rotation.z;
  65924. this._quaternionRotationYPR();
  65925. }
  65926. this._quaternionToRotationMatrix();
  65927. this._rotMatrix.invertToRef(this._invertMatrix);
  65928. for (var pt = 0; pt < this._shape.length; pt++) {
  65929. idx = index + pt * 3;
  65930. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  65931. this._fixedNormal32[idx] = this._normal.x;
  65932. this._fixedNormal32[idx + 1] = this._normal.y;
  65933. this._fixedNormal32[idx + 2] = this._normal.z;
  65934. }
  65935. index = idx + 3;
  65936. }
  65937. };
  65938. //reset copy
  65939. SolidParticleSystem.prototype._resetCopy = function () {
  65940. this._copy.position.x = 0;
  65941. this._copy.position.y = 0;
  65942. this._copy.position.z = 0;
  65943. this._copy.rotation.x = 0;
  65944. this._copy.rotation.y = 0;
  65945. this._copy.rotation.z = 0;
  65946. this._copy.rotationQuaternion = null;
  65947. this._copy.scaling.x = 1.0;
  65948. this._copy.scaling.y = 1.0;
  65949. this._copy.scaling.z = 1.0;
  65950. this._copy.uvs.x = 0;
  65951. this._copy.uvs.y = 0;
  65952. this._copy.uvs.z = 1.0;
  65953. this._copy.uvs.w = 1.0;
  65954. this._copy.color = null;
  65955. this._copy.translateFromPivot = false;
  65956. };
  65957. // _meshBuilder : inserts the shape model in the global SPS mesh
  65958. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  65959. var i;
  65960. var u = 0;
  65961. var c = 0;
  65962. var n = 0;
  65963. this._resetCopy();
  65964. if (options && options.positionFunction) { // call to custom positionFunction
  65965. options.positionFunction(this._copy, idx, idxInShape);
  65966. this._mustUnrotateFixedNormals = true;
  65967. }
  65968. if (this._copy.rotationQuaternion) {
  65969. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65970. }
  65971. else {
  65972. this._yaw = this._copy.rotation.y;
  65973. this._pitch = this._copy.rotation.x;
  65974. this._roll = this._copy.rotation.z;
  65975. this._quaternionRotationYPR();
  65976. }
  65977. this._quaternionToRotationMatrix();
  65978. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  65979. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  65980. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  65981. if (this._copy.translateFromPivot) {
  65982. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65983. }
  65984. else {
  65985. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65986. }
  65987. for (i = 0; i < shape.length; i++) {
  65988. this._vertex.x = shape[i].x;
  65989. this._vertex.y = shape[i].y;
  65990. this._vertex.z = shape[i].z;
  65991. if (options && options.vertexFunction) {
  65992. options.vertexFunction(this._copy, this._vertex, i);
  65993. }
  65994. this._vertex.x *= this._copy.scaling.x;
  65995. this._vertex.y *= this._copy.scaling.y;
  65996. this._vertex.z *= this._copy.scaling.z;
  65997. this._vertex.x -= this._scaledPivot.x;
  65998. this._vertex.y -= this._scaledPivot.y;
  65999. this._vertex.z -= this._scaledPivot.z;
  66000. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66001. this._rotated.addInPlace(this._pivotBackTranslation);
  66002. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  66003. if (meshUV) {
  66004. 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);
  66005. u += 2;
  66006. }
  66007. if (this._copy.color) {
  66008. this._color = this._copy.color;
  66009. }
  66010. else if (meshCol && meshCol[c] !== undefined) {
  66011. this._color.r = meshCol[c];
  66012. this._color.g = meshCol[c + 1];
  66013. this._color.b = meshCol[c + 2];
  66014. this._color.a = meshCol[c + 3];
  66015. }
  66016. else {
  66017. this._color.r = 1.0;
  66018. this._color.g = 1.0;
  66019. this._color.b = 1.0;
  66020. this._color.a = 1.0;
  66021. }
  66022. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  66023. c += 4;
  66024. if (!this.recomputeNormals && meshNor) {
  66025. this._normal.x = meshNor[n];
  66026. this._normal.y = meshNor[n + 1];
  66027. this._normal.z = meshNor[n + 2];
  66028. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  66029. normals.push(this._normal.x, this._normal.y, this._normal.z);
  66030. n += 3;
  66031. }
  66032. }
  66033. for (i = 0; i < meshInd.length; i++) {
  66034. var current_ind = p + meshInd[i];
  66035. indices.push(current_ind);
  66036. if (current_ind > 65535) {
  66037. this._needs32Bits = true;
  66038. }
  66039. }
  66040. if (this._pickable) {
  66041. var nbfaces = meshInd.length / 3;
  66042. for (i = 0; i < nbfaces; i++) {
  66043. this.pickedParticles.push({ idx: idx, faceId: i });
  66044. }
  66045. }
  66046. if (this._depthSort) {
  66047. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  66048. }
  66049. return this._copy;
  66050. };
  66051. // returns a shape array from positions array
  66052. SolidParticleSystem.prototype._posToShape = function (positions) {
  66053. var shape = [];
  66054. for (var i = 0; i < positions.length; i += 3) {
  66055. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  66056. }
  66057. return shape;
  66058. };
  66059. // returns a shapeUV array from a Vector4 uvs
  66060. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  66061. var shapeUV = [];
  66062. if (uvs) {
  66063. for (var i = 0; i < uvs.length; i++)
  66064. shapeUV.push(uvs[i]);
  66065. }
  66066. return shapeUV;
  66067. };
  66068. // adds a new particle object in the particles array
  66069. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  66070. if (bInfo === void 0) { bInfo = null; }
  66071. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  66072. this.particles.push(sp);
  66073. return sp;
  66074. };
  66075. /**
  66076. * Adds some particles to the SPS from the model shape. Returns the shape id.
  66077. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  66078. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  66079. * @param nb (positive integer) the number of particles to be created from this model
  66080. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  66081. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  66082. * @returns the number of shapes in the system
  66083. */
  66084. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  66085. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66086. var meshInd = mesh.getIndices();
  66087. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66088. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66089. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66090. var bbInfo;
  66091. if (this._particlesIntersect) {
  66092. bbInfo = mesh.getBoundingInfo();
  66093. }
  66094. var shape = this._posToShape(meshPos);
  66095. var shapeUV = this._uvsToShapeUV(meshUV);
  66096. var posfunc = options ? options.positionFunction : null;
  66097. var vtxfunc = options ? options.vertexFunction : null;
  66098. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  66099. // particles
  66100. var sp;
  66101. var currentCopy;
  66102. var idx = this.nbParticles;
  66103. for (var i = 0; i < nb; i++) {
  66104. var currentPos = this._positions.length;
  66105. var currentInd = this._indices.length;
  66106. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  66107. if (this._updatable) {
  66108. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  66109. sp.position.copyFrom(currentCopy.position);
  66110. sp.rotation.copyFrom(currentCopy.rotation);
  66111. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  66112. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  66113. }
  66114. if (currentCopy.color && sp.color) {
  66115. sp.color.copyFrom(currentCopy.color);
  66116. }
  66117. sp.scaling.copyFrom(currentCopy.scaling);
  66118. sp.uvs.copyFrom(currentCopy.uvs);
  66119. }
  66120. this._index += shape.length;
  66121. idx++;
  66122. }
  66123. this.nbParticles += nb;
  66124. this._shapeCounter++;
  66125. return this._shapeCounter - 1;
  66126. };
  66127. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  66128. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  66129. this._resetCopy();
  66130. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  66131. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  66132. }
  66133. if (this._copy.rotationQuaternion) {
  66134. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66135. }
  66136. else {
  66137. this._yaw = this._copy.rotation.y;
  66138. this._pitch = this._copy.rotation.x;
  66139. this._roll = this._copy.rotation.z;
  66140. this._quaternionRotationYPR();
  66141. }
  66142. this._quaternionToRotationMatrix();
  66143. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66144. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66145. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66146. if (this._copy.translateFromPivot) {
  66147. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66148. }
  66149. else {
  66150. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66151. }
  66152. this._shape = particle._model._shape;
  66153. for (var pt = 0; pt < this._shape.length; pt++) {
  66154. this._vertex.x = this._shape[pt].x;
  66155. this._vertex.y = this._shape[pt].y;
  66156. this._vertex.z = this._shape[pt].z;
  66157. if (particle._model._vertexFunction) {
  66158. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  66159. }
  66160. this._vertex.x *= this._copy.scaling.x;
  66161. this._vertex.y *= this._copy.scaling.y;
  66162. this._vertex.z *= this._copy.scaling.z;
  66163. this._vertex.x -= this._scaledPivot.x;
  66164. this._vertex.y -= this._scaledPivot.y;
  66165. this._vertex.z -= this._scaledPivot.z;
  66166. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66167. this._rotated.addInPlace(this._pivotBackTranslation);
  66168. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  66169. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  66170. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  66171. }
  66172. particle.position.x = 0.0;
  66173. particle.position.y = 0.0;
  66174. particle.position.z = 0.0;
  66175. particle.rotation.x = 0.0;
  66176. particle.rotation.y = 0.0;
  66177. particle.rotation.z = 0.0;
  66178. particle.rotationQuaternion = null;
  66179. particle.scaling.x = 1.0;
  66180. particle.scaling.y = 1.0;
  66181. particle.scaling.z = 1.0;
  66182. particle.uvs.x = 0.0;
  66183. particle.uvs.y = 0.0;
  66184. particle.uvs.z = 1.0;
  66185. particle.uvs.w = 1.0;
  66186. particle.pivot.x = 0.0;
  66187. particle.pivot.y = 0.0;
  66188. particle.pivot.z = 0.0;
  66189. particle.translateFromPivot = false;
  66190. particle.parentId = null;
  66191. };
  66192. /**
  66193. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  66194. * @returns the SPS.
  66195. */
  66196. SolidParticleSystem.prototype.rebuildMesh = function () {
  66197. for (var p = 0; p < this.particles.length; p++) {
  66198. this._rebuildParticle(this.particles[p]);
  66199. }
  66200. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66201. return this;
  66202. };
  66203. /**
  66204. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  66205. * This method calls `updateParticle()` for each particle of the SPS.
  66206. * For an animated SPS, it is usually called within the render loop.
  66207. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  66208. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  66209. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  66210. * @returns the SPS.
  66211. */
  66212. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  66213. if (start === void 0) { start = 0; }
  66214. if (end === void 0) { end = this.nbParticles - 1; }
  66215. if (update === void 0) { update = true; }
  66216. if (!this._updatable) {
  66217. return this;
  66218. }
  66219. // custom beforeUpdate
  66220. this.beforeUpdateParticles(start, end, update);
  66221. this._cam_axisX.x = 1.0;
  66222. this._cam_axisX.y = 0.0;
  66223. this._cam_axisX.z = 0.0;
  66224. this._cam_axisY.x = 0.0;
  66225. this._cam_axisY.y = 1.0;
  66226. this._cam_axisY.z = 0.0;
  66227. this._cam_axisZ.x = 0.0;
  66228. this._cam_axisZ.y = 0.0;
  66229. this._cam_axisZ.z = 1.0;
  66230. // cases when the World Matrix is to be computed first
  66231. if (this.billboard || this._depthSort) {
  66232. this.mesh.computeWorldMatrix(true);
  66233. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  66234. }
  66235. // if the particles will always face the camera
  66236. if (this.billboard) {
  66237. // compute the camera position and un-rotate it by the current mesh rotation
  66238. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  66239. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  66240. this._cam_axisZ.normalize();
  66241. // same for camera up vector extracted from the cam view matrix
  66242. var view = this._camera.getViewMatrix(true);
  66243. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  66244. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  66245. this._cam_axisY.normalize();
  66246. this._cam_axisX.normalize();
  66247. }
  66248. // if depthSort, compute the camera global position in the mesh local system
  66249. if (this._depthSort) {
  66250. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  66251. }
  66252. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  66253. var idx = 0; // current position index in the global array positions32
  66254. var index = 0; // position start index in the global array positions32 of the current particle
  66255. var colidx = 0; // current color index in the global array colors32
  66256. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  66257. var uvidx = 0; // current uv index in the global array uvs32
  66258. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  66259. var pt = 0; // current index in the particle model shape
  66260. if (this.mesh.isFacetDataEnabled) {
  66261. this._computeBoundingBox = true;
  66262. }
  66263. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  66264. if (this._computeBoundingBox) {
  66265. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  66266. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  66267. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  66268. }
  66269. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  66270. if (this.mesh._boundingInfo) {
  66271. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  66272. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  66273. }
  66274. }
  66275. }
  66276. // particle loop
  66277. index = this.particles[start]._pos;
  66278. var vpos = (index / 3) | 0;
  66279. colorIndex = vpos * 4;
  66280. uvIndex = vpos * 2;
  66281. for (var p = start; p <= end; p++) {
  66282. this._particle = this.particles[p];
  66283. this._shape = this._particle._model._shape;
  66284. this._shapeUV = this._particle._model._shapeUV;
  66285. // call to custom user function to update the particle properties
  66286. this.updateParticle(this._particle);
  66287. // camera-particle distance for depth sorting
  66288. if (this._depthSort && this._depthSortParticles) {
  66289. var dsp = this.depthSortedParticles[p];
  66290. dsp.ind = this._particle._ind;
  66291. dsp.indicesLength = this._particle._model._indicesLength;
  66292. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  66293. }
  66294. // skip the computations for inactive or already invisible particles
  66295. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  66296. // increment indexes for the next particle
  66297. pt = this._shape.length;
  66298. index += pt * 3;
  66299. colorIndex += pt * 4;
  66300. uvIndex += pt * 2;
  66301. continue;
  66302. }
  66303. if (this._particle.isVisible) {
  66304. this._particle._stillInvisible = false; // un-mark permanent invisibility
  66305. this._particleHasParent = (this._particle.parentId !== null);
  66306. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66307. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66308. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66309. // particle rotation matrix
  66310. if (this.billboard) {
  66311. this._particle.rotation.x = 0.0;
  66312. this._particle.rotation.y = 0.0;
  66313. }
  66314. if (this._computeParticleRotation || this.billboard) {
  66315. if (this._particle.rotationQuaternion) {
  66316. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66317. }
  66318. else {
  66319. this._yaw = this._particle.rotation.y;
  66320. this._pitch = this._particle.rotation.x;
  66321. this._roll = this._particle.rotation.z;
  66322. this._quaternionRotationYPR();
  66323. }
  66324. this._quaternionToRotationMatrix();
  66325. }
  66326. if (this._particleHasParent) {
  66327. this._parent = this.particles[this._particle.parentId];
  66328. 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];
  66329. 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];
  66330. 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];
  66331. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  66332. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  66333. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  66334. if (this._computeParticleRotation || this.billboard) {
  66335. 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];
  66336. 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];
  66337. 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];
  66338. 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];
  66339. 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];
  66340. 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];
  66341. 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];
  66342. 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];
  66343. 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];
  66344. }
  66345. }
  66346. else {
  66347. this._particle._globalPosition.x = this._particle.position.x;
  66348. this._particle._globalPosition.y = this._particle.position.y;
  66349. this._particle._globalPosition.z = this._particle.position.z;
  66350. if (this._computeParticleRotation || this.billboard) {
  66351. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  66352. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  66353. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  66354. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  66355. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  66356. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  66357. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  66358. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  66359. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  66360. }
  66361. }
  66362. if (this._particle.translateFromPivot) {
  66363. this._pivotBackTranslation.x = 0.0;
  66364. this._pivotBackTranslation.y = 0.0;
  66365. this._pivotBackTranslation.z = 0.0;
  66366. }
  66367. else {
  66368. this._pivotBackTranslation.x = this._scaledPivot.x;
  66369. this._pivotBackTranslation.y = this._scaledPivot.y;
  66370. this._pivotBackTranslation.z = this._scaledPivot.z;
  66371. }
  66372. // particle vertex loop
  66373. for (pt = 0; pt < this._shape.length; pt++) {
  66374. idx = index + pt * 3;
  66375. colidx = colorIndex + pt * 4;
  66376. uvidx = uvIndex + pt * 2;
  66377. this._vertex.x = this._shape[pt].x;
  66378. this._vertex.y = this._shape[pt].y;
  66379. this._vertex.z = this._shape[pt].z;
  66380. if (this._computeParticleVertex) {
  66381. this.updateParticleVertex(this._particle, this._vertex, pt);
  66382. }
  66383. // positions
  66384. this._vertex.x *= this._particle.scaling.x;
  66385. this._vertex.y *= this._particle.scaling.y;
  66386. this._vertex.z *= this._particle.scaling.z;
  66387. this._vertex.x -= this._scaledPivot.x;
  66388. this._vertex.y -= this._scaledPivot.y;
  66389. this._vertex.z -= this._scaledPivot.z;
  66390. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  66391. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  66392. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  66393. this._rotated.x += this._pivotBackTranslation.x;
  66394. this._rotated.y += this._pivotBackTranslation.y;
  66395. this._rotated.z += this._pivotBackTranslation.z;
  66396. 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;
  66397. 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;
  66398. 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;
  66399. if (this._computeBoundingBox) {
  66400. if (this._positions32[idx] < this._minimum.x) {
  66401. this._minimum.x = this._positions32[idx];
  66402. }
  66403. if (this._positions32[idx] > this._maximum.x) {
  66404. this._maximum.x = this._positions32[idx];
  66405. }
  66406. if (this._positions32[idx + 1] < this._minimum.y) {
  66407. this._minimum.y = this._positions32[idx + 1];
  66408. }
  66409. if (this._positions32[idx + 1] > this._maximum.y) {
  66410. this._maximum.y = this._positions32[idx + 1];
  66411. }
  66412. if (this._positions32[idx + 2] < this._minimum.z) {
  66413. this._minimum.z = this._positions32[idx + 2];
  66414. }
  66415. if (this._positions32[idx + 2] > this._maximum.z) {
  66416. this._maximum.z = this._positions32[idx + 2];
  66417. }
  66418. }
  66419. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  66420. if (!this._computeParticleVertex) {
  66421. this._normal.x = this._fixedNormal32[idx];
  66422. this._normal.y = this._fixedNormal32[idx + 1];
  66423. this._normal.z = this._fixedNormal32[idx + 2];
  66424. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  66425. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  66426. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  66427. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  66428. 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;
  66429. 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;
  66430. }
  66431. if (this._computeParticleColor && this._particle.color) {
  66432. this._colors32[colidx] = this._particle.color.r;
  66433. this._colors32[colidx + 1] = this._particle.color.g;
  66434. this._colors32[colidx + 2] = this._particle.color.b;
  66435. this._colors32[colidx + 3] = this._particle.color.a;
  66436. }
  66437. if (this._computeParticleTexture) {
  66438. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  66439. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  66440. }
  66441. }
  66442. }
  66443. // particle just set invisible : scaled to zero and positioned at the origin
  66444. else {
  66445. this._particle._stillInvisible = true; // mark the particle as invisible
  66446. for (pt = 0; pt < this._shape.length; pt++) {
  66447. idx = index + pt * 3;
  66448. colidx = colorIndex + pt * 4;
  66449. uvidx = uvIndex + pt * 2;
  66450. this._positions32[idx] = 0.0;
  66451. this._positions32[idx + 1] = 0.0;
  66452. this._positions32[idx + 2] = 0.0;
  66453. this._normals32[idx] = 0.0;
  66454. this._normals32[idx + 1] = 0.0;
  66455. this._normals32[idx + 2] = 0.0;
  66456. if (this._computeParticleColor && this._particle.color) {
  66457. this._colors32[colidx] = this._particle.color.r;
  66458. this._colors32[colidx + 1] = this._particle.color.g;
  66459. this._colors32[colidx + 2] = this._particle.color.b;
  66460. this._colors32[colidx + 3] = this._particle.color.a;
  66461. }
  66462. if (this._computeParticleTexture) {
  66463. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  66464. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  66465. }
  66466. }
  66467. }
  66468. // if the particle intersections must be computed : update the bbInfo
  66469. if (this._particlesIntersect) {
  66470. var bInfo = this._particle._boundingInfo;
  66471. var bBox = bInfo.boundingBox;
  66472. var bSphere = bInfo.boundingSphere;
  66473. if (!this._bSphereOnly) {
  66474. // place, scale and rotate the particle bbox within the SPS local system, then update it
  66475. for (var b = 0; b < bBox.vectors.length; b++) {
  66476. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  66477. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  66478. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  66479. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  66480. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  66481. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  66482. 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;
  66483. 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;
  66484. 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;
  66485. }
  66486. bBox._update(this.mesh._worldMatrix);
  66487. }
  66488. // place and scale the particle bouding sphere in the SPS local system, then update it
  66489. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  66490. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  66491. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  66492. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  66493. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  66494. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  66495. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  66496. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  66497. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  66498. 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));
  66499. bSphere._update(this.mesh._worldMatrix);
  66500. }
  66501. // increment indexes for the next particle
  66502. index = idx + 3;
  66503. colorIndex = colidx + 4;
  66504. uvIndex = uvidx + 2;
  66505. }
  66506. // if the VBO must be updated
  66507. if (update) {
  66508. if (this._computeParticleColor) {
  66509. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  66510. }
  66511. if (this._computeParticleTexture) {
  66512. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  66513. }
  66514. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66515. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  66516. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  66517. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  66518. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  66519. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  66520. for (var i = 0; i < this._normals32.length; i++) {
  66521. this._fixedNormal32[i] = this._normals32[i];
  66522. }
  66523. }
  66524. if (!this.mesh.areNormalsFrozen) {
  66525. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  66526. }
  66527. }
  66528. if (this._depthSort && this._depthSortParticles) {
  66529. this.depthSortedParticles.sort(this._depthSortFunction);
  66530. var dspl = this.depthSortedParticles.length;
  66531. var sorted = 0;
  66532. var lind = 0;
  66533. var sind = 0;
  66534. var sid = 0;
  66535. for (sorted = 0; sorted < dspl; sorted++) {
  66536. lind = this.depthSortedParticles[sorted].indicesLength;
  66537. sind = this.depthSortedParticles[sorted].ind;
  66538. for (var i = 0; i < lind; i++) {
  66539. this._indices32[sid] = this._indices[sind + i];
  66540. sid++;
  66541. }
  66542. }
  66543. this.mesh.updateIndices(this._indices32);
  66544. }
  66545. }
  66546. if (this._computeBoundingBox) {
  66547. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  66548. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  66549. }
  66550. this.afterUpdateParticles(start, end, update);
  66551. return this;
  66552. };
  66553. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  66554. this._halfroll = this._roll * 0.5;
  66555. this._halfpitch = this._pitch * 0.5;
  66556. this._halfyaw = this._yaw * 0.5;
  66557. this._sinRoll = Math.sin(this._halfroll);
  66558. this._cosRoll = Math.cos(this._halfroll);
  66559. this._sinPitch = Math.sin(this._halfpitch);
  66560. this._cosPitch = Math.cos(this._halfpitch);
  66561. this._sinYaw = Math.sin(this._halfyaw);
  66562. this._cosYaw = Math.cos(this._halfyaw);
  66563. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  66564. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  66565. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  66566. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  66567. };
  66568. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  66569. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  66570. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  66571. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  66572. this._rotMatrix.m[3] = 0;
  66573. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  66574. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  66575. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  66576. this._rotMatrix.m[7] = 0;
  66577. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  66578. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  66579. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  66580. this._rotMatrix.m[11] = 0;
  66581. this._rotMatrix.m[12] = 0;
  66582. this._rotMatrix.m[13] = 0;
  66583. this._rotMatrix.m[14] = 0;
  66584. this._rotMatrix.m[15] = 1.0;
  66585. };
  66586. /**
  66587. * Disposes the SPS.
  66588. */
  66589. SolidParticleSystem.prototype.dispose = function () {
  66590. this.mesh.dispose();
  66591. this.vars = null;
  66592. // drop references to internal big arrays for the GC
  66593. this._positions = null;
  66594. this._indices = null;
  66595. this._normals = null;
  66596. this._uvs = null;
  66597. this._colors = null;
  66598. this._indices32 = null;
  66599. this._positions32 = null;
  66600. this._normals32 = null;
  66601. this._fixedNormal32 = null;
  66602. this._uvs32 = null;
  66603. this._colors32 = null;
  66604. this.pickedParticles = null;
  66605. };
  66606. /**
  66607. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  66608. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66609. * @returns the SPS.
  66610. */
  66611. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  66612. if (!this._isVisibilityBoxLocked) {
  66613. this.mesh.refreshBoundingInfo();
  66614. }
  66615. return this;
  66616. };
  66617. /**
  66618. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  66619. * @param size the size (float) of the visibility box
  66620. * note : this doesn't lock the SPS mesh bounding box.
  66621. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66622. */
  66623. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  66624. var vis = size / 2;
  66625. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  66626. };
  66627. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  66628. /**
  66629. * Gets whether the SPS as always visible or not
  66630. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66631. */
  66632. get: function () {
  66633. return this._alwaysVisible;
  66634. },
  66635. /**
  66636. * Sets the SPS as always visible or not
  66637. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66638. */
  66639. set: function (val) {
  66640. this._alwaysVisible = val;
  66641. this.mesh.alwaysSelectAsActiveMesh = val;
  66642. },
  66643. enumerable: true,
  66644. configurable: true
  66645. });
  66646. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  66647. /**
  66648. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  66649. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66650. */
  66651. get: function () {
  66652. return this._isVisibilityBoxLocked;
  66653. },
  66654. /**
  66655. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  66656. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66657. */
  66658. set: function (val) {
  66659. this._isVisibilityBoxLocked = val;
  66660. var boundingInfo = this.mesh.getBoundingInfo();
  66661. boundingInfo.isLocked = val;
  66662. },
  66663. enumerable: true,
  66664. configurable: true
  66665. });
  66666. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  66667. /**
  66668. * Gets if `setParticles()` computes the particle rotations or not.
  66669. * Default value : true. The SPS is faster when it's set to false.
  66670. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  66671. */
  66672. get: function () {
  66673. return this._computeParticleRotation;
  66674. },
  66675. /**
  66676. * Tells to `setParticles()` to compute the particle rotations or not.
  66677. * Default value : true. The SPS is faster when it's set to false.
  66678. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  66679. */
  66680. set: function (val) {
  66681. this._computeParticleRotation = val;
  66682. },
  66683. enumerable: true,
  66684. configurable: true
  66685. });
  66686. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  66687. /**
  66688. * Gets if `setParticles()` computes the particle colors or not.
  66689. * Default value : true. The SPS is faster when it's set to false.
  66690. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  66691. */
  66692. get: function () {
  66693. return this._computeParticleColor;
  66694. },
  66695. /**
  66696. * Tells to `setParticles()` to compute the particle colors or not.
  66697. * Default value : true. The SPS is faster when it's set to false.
  66698. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  66699. */
  66700. set: function (val) {
  66701. this._computeParticleColor = val;
  66702. },
  66703. enumerable: true,
  66704. configurable: true
  66705. });
  66706. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  66707. /**
  66708. * Gets if `setParticles()` computes the particle textures or not.
  66709. * Default value : true. The SPS is faster when it's set to false.
  66710. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  66711. */
  66712. get: function () {
  66713. return this._computeParticleTexture;
  66714. },
  66715. set: function (val) {
  66716. this._computeParticleTexture = val;
  66717. },
  66718. enumerable: true,
  66719. configurable: true
  66720. });
  66721. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  66722. /**
  66723. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  66724. * Default value : false. The SPS is faster when it's set to false.
  66725. * Note : the particle custom vertex positions aren't stored values.
  66726. */
  66727. get: function () {
  66728. return this._computeParticleVertex;
  66729. },
  66730. /**
  66731. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  66732. * Default value : false. The SPS is faster when it's set to false.
  66733. * Note : the particle custom vertex positions aren't stored values.
  66734. */
  66735. set: function (val) {
  66736. this._computeParticleVertex = val;
  66737. },
  66738. enumerable: true,
  66739. configurable: true
  66740. });
  66741. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  66742. /**
  66743. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  66744. */
  66745. get: function () {
  66746. return this._computeBoundingBox;
  66747. },
  66748. /**
  66749. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  66750. */
  66751. set: function (val) {
  66752. this._computeBoundingBox = val;
  66753. },
  66754. enumerable: true,
  66755. configurable: true
  66756. });
  66757. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  66758. /**
  66759. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  66760. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  66761. * Default : `true`
  66762. */
  66763. get: function () {
  66764. return this._depthSortParticles;
  66765. },
  66766. /**
  66767. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  66768. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  66769. * Default : `true`
  66770. */
  66771. set: function (val) {
  66772. this._depthSortParticles = val;
  66773. },
  66774. enumerable: true,
  66775. configurable: true
  66776. });
  66777. // =======================================================================
  66778. // Particle behavior logic
  66779. // these following methods may be overwritten by the user to fit his needs
  66780. /**
  66781. * This function does nothing. It may be overwritten to set all the particle first values.
  66782. * The SPS doesn't call this function, you may have to call it by your own.
  66783. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66784. */
  66785. SolidParticleSystem.prototype.initParticles = function () {
  66786. };
  66787. /**
  66788. * This function does nothing. It may be overwritten to recycle a particle.
  66789. * The SPS doesn't call this function, you may have to call it by your own.
  66790. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66791. * @param particle The particle to recycle
  66792. * @returns the recycled particle
  66793. */
  66794. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  66795. return particle;
  66796. };
  66797. /**
  66798. * Updates a particle : this function should be overwritten by the user.
  66799. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  66800. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66801. * @example : just set a particle position or velocity and recycle conditions
  66802. * @param particle The particle to update
  66803. * @returns the updated particle
  66804. */
  66805. SolidParticleSystem.prototype.updateParticle = function (particle) {
  66806. return particle;
  66807. };
  66808. /**
  66809. * Updates a vertex of a particle : it can be overwritten by the user.
  66810. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  66811. * @param particle the current particle
  66812. * @param vertex the current index of the current particle
  66813. * @param pt the index of the current vertex in the particle shape
  66814. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  66815. * @example : just set a vertex particle position
  66816. * @returns the updated vertex
  66817. */
  66818. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  66819. return vertex;
  66820. };
  66821. /**
  66822. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  66823. * This does nothing and may be overwritten by the user.
  66824. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66825. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66826. * @param update the boolean update value actually passed to setParticles()
  66827. */
  66828. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  66829. };
  66830. /**
  66831. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  66832. * This will be passed three parameters.
  66833. * This does nothing and may be overwritten by the user.
  66834. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66835. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66836. * @param update the boolean update value actually passed to setParticles()
  66837. */
  66838. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  66839. };
  66840. return SolidParticleSystem;
  66841. }());
  66842. BABYLON.SolidParticleSystem = SolidParticleSystem;
  66843. })(BABYLON || (BABYLON = {}));
  66844. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  66845. var BABYLON;
  66846. (function (BABYLON) {
  66847. /**
  66848. * Class containing static functions to help procedurally build meshes
  66849. */
  66850. var MeshBuilder = /** @class */ (function () {
  66851. function MeshBuilder() {
  66852. }
  66853. MeshBuilder.updateSideOrientation = function (orientation) {
  66854. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  66855. return BABYLON.Mesh.DOUBLESIDE;
  66856. }
  66857. if (orientation === undefined || orientation === null) {
  66858. return BABYLON.Mesh.FRONTSIDE;
  66859. }
  66860. return orientation;
  66861. };
  66862. /**
  66863. * Creates a box mesh
  66864. * * The parameter `size` sets the size (float) of each box side (default 1)
  66865. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  66866. * * 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)
  66867. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66868. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66869. * * 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
  66870. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66871. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  66872. * @param name defines the name of the mesh
  66873. * @param options defines the options used to create the mesh
  66874. * @param scene defines the hosting scene
  66875. * @returns the box mesh
  66876. */
  66877. MeshBuilder.CreateBox = function (name, options, scene) {
  66878. if (scene === void 0) { scene = null; }
  66879. var box = new BABYLON.Mesh(name, scene);
  66880. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66881. box._originalBuilderSideOrientation = options.sideOrientation;
  66882. var vertexData = BABYLON.VertexData.CreateBox(options);
  66883. vertexData.applyToMesh(box, options.updatable);
  66884. return box;
  66885. };
  66886. /**
  66887. * Creates a sphere mesh
  66888. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  66889. * * 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 of `diameter`)
  66890. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  66891. * * 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
  66892. * * 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)
  66893. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66894. * * 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
  66895. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66896. * @param name defines the name of the mesh
  66897. * @param options defines the options used to create the mesh
  66898. * @param scene defines the hosting scene
  66899. * @returns the sphere mesh
  66900. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  66901. */
  66902. MeshBuilder.CreateSphere = function (name, options, scene) {
  66903. var sphere = new BABYLON.Mesh(name, scene);
  66904. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66905. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66906. var vertexData = BABYLON.VertexData.CreateSphere(options);
  66907. vertexData.applyToMesh(sphere, options.updatable);
  66908. return sphere;
  66909. };
  66910. /**
  66911. * Creates a plane polygonal mesh. By default, this is a disc
  66912. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  66913. * * 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
  66914. * * 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
  66915. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66916. * * 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
  66917. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66918. * @param name defines the name of the mesh
  66919. * @param options defines the options used to create the mesh
  66920. * @param scene defines the hosting scene
  66921. * @returns the plane polygonal mesh
  66922. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  66923. */
  66924. MeshBuilder.CreateDisc = function (name, options, scene) {
  66925. if (scene === void 0) { scene = null; }
  66926. var disc = new BABYLON.Mesh(name, scene);
  66927. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66928. disc._originalBuilderSideOrientation = options.sideOrientation;
  66929. var vertexData = BABYLON.VertexData.CreateDisc(options);
  66930. vertexData.applyToMesh(disc, options.updatable);
  66931. return disc;
  66932. };
  66933. /**
  66934. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  66935. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  66936. * * 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 of `radius`)
  66937. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  66938. * * 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
  66939. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66940. * * 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
  66941. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66942. * @param name defines the name of the mesh
  66943. * @param options defines the options used to create the mesh
  66944. * @param scene defines the hosting scene
  66945. * @returns the icosahedron mesh
  66946. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  66947. */
  66948. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  66949. var sphere = new BABYLON.Mesh(name, scene);
  66950. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66951. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66952. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  66953. vertexData.applyToMesh(sphere, options.updatable);
  66954. return sphere;
  66955. };
  66956. ;
  66957. /**
  66958. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66959. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  66960. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  66961. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  66962. * * 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
  66963. * * 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
  66964. * * 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
  66965. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66966. * * 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
  66967. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66968. * * 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
  66969. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  66970. * * 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
  66971. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  66972. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66973. * @param name defines the name of the mesh
  66974. * @param options defines the options used to create the mesh
  66975. * @param scene defines the hosting scene
  66976. * @returns the ribbon mesh
  66977. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  66978. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66979. */
  66980. MeshBuilder.CreateRibbon = function (name, options, scene) {
  66981. if (scene === void 0) { scene = null; }
  66982. var pathArray = options.pathArray;
  66983. var closeArray = options.closeArray;
  66984. var closePath = options.closePath;
  66985. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66986. var instance = options.instance;
  66987. var updatable = options.updatable;
  66988. if (instance) { // existing ribbon instance update
  66989. // positionFunction : ribbon case
  66990. // only pathArray and sideOrientation parameters are taken into account for positions update
  66991. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  66992. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  66993. var positionFunction = function (positions) {
  66994. var minlg = pathArray[0].length;
  66995. var mesh = instance;
  66996. var i = 0;
  66997. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  66998. for (var si = 1; si <= ns; si++) {
  66999. for (var p = 0; p < pathArray.length; p++) {
  67000. var path = pathArray[p];
  67001. var l = path.length;
  67002. minlg = (minlg < l) ? minlg : l;
  67003. var j = 0;
  67004. while (j < minlg) {
  67005. positions[i] = path[j].x;
  67006. positions[i + 1] = path[j].y;
  67007. positions[i + 2] = path[j].z;
  67008. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  67009. BABYLON.Tmp.Vector3[0].x = path[j].x;
  67010. }
  67011. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  67012. BABYLON.Tmp.Vector3[1].x = path[j].x;
  67013. }
  67014. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  67015. BABYLON.Tmp.Vector3[0].y = path[j].y;
  67016. }
  67017. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  67018. BABYLON.Tmp.Vector3[1].y = path[j].y;
  67019. }
  67020. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  67021. BABYLON.Tmp.Vector3[0].z = path[j].z;
  67022. }
  67023. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  67024. BABYLON.Tmp.Vector3[1].z = path[j].z;
  67025. }
  67026. j++;
  67027. i += 3;
  67028. }
  67029. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  67030. positions[i] = path[0].x;
  67031. positions[i + 1] = path[0].y;
  67032. positions[i + 2] = path[0].z;
  67033. i += 3;
  67034. }
  67035. }
  67036. }
  67037. };
  67038. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67039. positionFunction(positions);
  67040. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  67041. instance._boundingInfo.update(instance._worldMatrix);
  67042. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67043. if (options.colors) {
  67044. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67045. for (var c = 0; c < options.colors.length; c++) {
  67046. colors[c * 4] = options.colors[c].r;
  67047. colors[c * 4 + 1] = options.colors[c].g;
  67048. colors[c * 4 + 2] = options.colors[c].b;
  67049. colors[c * 4 + 3] = options.colors[c].a;
  67050. }
  67051. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  67052. }
  67053. if (options.uvs) {
  67054. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67055. for (var i = 0; i < options.uvs.length; i++) {
  67056. uvs[i * 2] = options.uvs[i].x;
  67057. uvs[i * 2 + 1] = options.uvs[i].y;
  67058. }
  67059. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  67060. }
  67061. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  67062. var indices = instance.getIndices();
  67063. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67064. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  67065. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  67066. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  67067. var indexFirst = 0;
  67068. var indexLast = 0;
  67069. for (var p = 0; p < pathArray.length; p++) {
  67070. indexFirst = instance._creationDataStorage.idx[p] * 3;
  67071. if (p + 1 < pathArray.length) {
  67072. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  67073. }
  67074. else {
  67075. indexLast = normals.length - 3;
  67076. }
  67077. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  67078. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  67079. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  67080. normals[indexLast] = normals[indexFirst];
  67081. normals[indexLast + 1] = normals[indexFirst + 1];
  67082. normals[indexLast + 2] = normals[indexFirst + 2];
  67083. }
  67084. }
  67085. if (!(instance.areNormalsFrozen)) {
  67086. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  67087. }
  67088. }
  67089. return instance;
  67090. }
  67091. else { // new ribbon creation
  67092. var ribbon = new BABYLON.Mesh(name, scene);
  67093. ribbon._originalBuilderSideOrientation = sideOrientation;
  67094. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  67095. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  67096. if (closePath) {
  67097. ribbon._creationDataStorage.idx = vertexData._idx;
  67098. }
  67099. ribbon._creationDataStorage.closePath = closePath;
  67100. ribbon._closeArray = closeArray;
  67101. vertexData.applyToMesh(ribbon, updatable);
  67102. return ribbon;
  67103. }
  67104. };
  67105. /**
  67106. * Creates a cylinder or a cone mesh
  67107. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  67108. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  67109. * * 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.
  67110. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  67111. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  67112. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  67113. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  67114. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  67115. * * 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).
  67116. * * 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
  67117. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  67118. * * 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
  67119. * * 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.
  67120. * * If `enclose` is false, a ring surface is one element.
  67121. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  67122. * * 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
  67123. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67124. * * 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
  67125. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67126. * @param name defines the name of the mesh
  67127. * @param options defines the options used to create the mesh
  67128. * @param scene defines the hosting scene
  67129. * @returns the cylinder mesh
  67130. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  67131. */
  67132. MeshBuilder.CreateCylinder = function (name, options, scene) {
  67133. var cylinder = new BABYLON.Mesh(name, scene);
  67134. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67135. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  67136. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  67137. vertexData.applyToMesh(cylinder, options.updatable);
  67138. return cylinder;
  67139. };
  67140. /**
  67141. * Creates a torus mesh
  67142. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  67143. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  67144. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  67145. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67146. * * 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
  67147. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67148. * @param name defines the name of the mesh
  67149. * @param options defines the options used to create the mesh
  67150. * @param scene defines the hosting scene
  67151. * @returns the torus mesh
  67152. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  67153. */
  67154. MeshBuilder.CreateTorus = function (name, options, scene) {
  67155. var torus = new BABYLON.Mesh(name, scene);
  67156. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67157. torus._originalBuilderSideOrientation = options.sideOrientation;
  67158. var vertexData = BABYLON.VertexData.CreateTorus(options);
  67159. vertexData.applyToMesh(torus, options.updatable);
  67160. return torus;
  67161. };
  67162. /**
  67163. * Creates a torus knot mesh
  67164. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  67165. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  67166. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  67167. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  67168. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67169. * * 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
  67170. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67171. * @param name defines the name of the mesh
  67172. * @param options defines the options used to create the mesh
  67173. * @param scene defines the hosting scene
  67174. * @returns the torus knot mesh
  67175. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  67176. */
  67177. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  67178. var torusKnot = new BABYLON.Mesh(name, scene);
  67179. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67180. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  67181. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  67182. vertexData.applyToMesh(torusKnot, options.updatable);
  67183. return torusKnot;
  67184. };
  67185. /**
  67186. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  67187. * * 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
  67188. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  67189. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  67190. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  67191. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  67192. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  67193. * * 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
  67194. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  67195. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67196. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  67197. * @param name defines the name of the new line system
  67198. * @param options defines the options used to create the line system
  67199. * @param scene defines the hosting scene
  67200. * @returns a new line system mesh
  67201. */
  67202. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  67203. var instance = options.instance;
  67204. var lines = options.lines;
  67205. var colors = options.colors;
  67206. if (instance) { // lines update
  67207. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67208. var vertexColor;
  67209. var lineColors;
  67210. if (colors) {
  67211. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67212. }
  67213. var i = 0;
  67214. var c = 0;
  67215. for (var l = 0; l < lines.length; l++) {
  67216. var points = lines[l];
  67217. for (var p = 0; p < points.length; p++) {
  67218. positions[i] = points[p].x;
  67219. positions[i + 1] = points[p].y;
  67220. positions[i + 2] = points[p].z;
  67221. if (colors && vertexColor) {
  67222. lineColors = colors[l];
  67223. vertexColor[c] = lineColors[p].r;
  67224. vertexColor[c + 1] = lineColors[p].g;
  67225. vertexColor[c + 2] = lineColors[p].b;
  67226. vertexColor[c + 3] = lineColors[p].a;
  67227. c += 4;
  67228. }
  67229. i += 3;
  67230. }
  67231. }
  67232. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67233. if (colors && vertexColor) {
  67234. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  67235. }
  67236. return instance;
  67237. }
  67238. // line system creation
  67239. var useVertexColor = (colors) ? true : false;
  67240. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  67241. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  67242. vertexData.applyToMesh(lineSystem, options.updatable);
  67243. return lineSystem;
  67244. };
  67245. /**
  67246. * Creates a line mesh
  67247. * 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
  67248. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67249. * * The parameter `points` is an array successive Vector3
  67250. * * 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
  67251. * * The optional parameter `colors` is an array of successive Color4, one per line point
  67252. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  67253. * * When updating an instance, remember that only point positions can change, not the number of points
  67254. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67255. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  67256. * @param name defines the name of the new line system
  67257. * @param options defines the options used to create the line system
  67258. * @param scene defines the hosting scene
  67259. * @returns a new line mesh
  67260. */
  67261. MeshBuilder.CreateLines = function (name, options, scene) {
  67262. if (scene === void 0) { scene = null; }
  67263. var colors = (options.colors) ? [options.colors] : null;
  67264. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  67265. return lines;
  67266. };
  67267. /**
  67268. * Creates a dashed line mesh
  67269. * * 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
  67270. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67271. * * The parameter `points` is an array successive Vector3
  67272. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  67273. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  67274. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  67275. * * 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
  67276. * * When updating an instance, remember that only point positions can change, not the number of points
  67277. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67278. * @param name defines the name of the mesh
  67279. * @param options defines the options used to create the mesh
  67280. * @param scene defines the hosting scene
  67281. * @returns the dashed line mesh
  67282. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  67283. */
  67284. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  67285. if (scene === void 0) { scene = null; }
  67286. var points = options.points;
  67287. var instance = options.instance;
  67288. var gapSize = options.gapSize || 1;
  67289. var dashSize = options.dashSize || 3;
  67290. if (instance) { // dashed lines update
  67291. var positionFunction = function (positions) {
  67292. var curvect = BABYLON.Vector3.Zero();
  67293. var nbSeg = positions.length / 6;
  67294. var lg = 0;
  67295. var nb = 0;
  67296. var shft = 0;
  67297. var dashshft = 0;
  67298. var curshft = 0;
  67299. var p = 0;
  67300. var i = 0;
  67301. var j = 0;
  67302. for (i = 0; i < points.length - 1; i++) {
  67303. points[i + 1].subtractToRef(points[i], curvect);
  67304. lg += curvect.length();
  67305. }
  67306. shft = lg / nbSeg;
  67307. var dashSize = instance._creationDataStorage.dashSize;
  67308. var gapSize = instance._creationDataStorage.gapSize;
  67309. dashshft = dashSize * shft / (dashSize + gapSize);
  67310. for (i = 0; i < points.length - 1; i++) {
  67311. points[i + 1].subtractToRef(points[i], curvect);
  67312. nb = Math.floor(curvect.length() / shft);
  67313. curvect.normalize();
  67314. j = 0;
  67315. while (j < nb && p < positions.length) {
  67316. curshft = shft * j;
  67317. positions[p] = points[i].x + curshft * curvect.x;
  67318. positions[p + 1] = points[i].y + curshft * curvect.y;
  67319. positions[p + 2] = points[i].z + curshft * curvect.z;
  67320. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  67321. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  67322. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  67323. p += 6;
  67324. j++;
  67325. }
  67326. }
  67327. while (p < positions.length) {
  67328. positions[p] = points[i].x;
  67329. positions[p + 1] = points[i].y;
  67330. positions[p + 2] = points[i].z;
  67331. p += 3;
  67332. }
  67333. };
  67334. instance.updateMeshPositions(positionFunction, false);
  67335. return instance;
  67336. }
  67337. // dashed lines creation
  67338. var dashedLines = new BABYLON.LinesMesh(name, scene);
  67339. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  67340. vertexData.applyToMesh(dashedLines, options.updatable);
  67341. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  67342. dashedLines._creationDataStorage.dashSize = dashSize;
  67343. dashedLines._creationDataStorage.gapSize = gapSize;
  67344. return dashedLines;
  67345. };
  67346. /**
  67347. * 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.
  67348. * * 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.
  67349. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  67350. * * 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.
  67351. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  67352. * * 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
  67353. * * 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
  67354. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  67355. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67356. * * 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
  67357. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  67358. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67359. * @param name defines the name of the mesh
  67360. * @param options defines the options used to create the mesh
  67361. * @param scene defines the hosting scene
  67362. * @returns the extruded shape mesh
  67363. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67364. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67365. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67366. */
  67367. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  67368. if (scene === void 0) { scene = null; }
  67369. var path = options.path;
  67370. var shape = options.shape;
  67371. var scale = options.scale || 1;
  67372. var rotation = options.rotation || 0;
  67373. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  67374. var updatable = options.updatable;
  67375. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67376. var instance = options.instance || null;
  67377. var invertUV = options.invertUV || false;
  67378. 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);
  67379. };
  67380. /**
  67381. * Creates an custom extruded shape mesh.
  67382. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  67383. * * 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.
  67384. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  67385. * * 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
  67386. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  67387. * * 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
  67388. * * It must returns a float value that will be the scale value applied to the shape on each path point
  67389. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  67390. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  67391. * * 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
  67392. * * 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
  67393. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  67394. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67395. * * 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
  67396. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67397. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67398. * @param name defines the name of the mesh
  67399. * @param options defines the options used to create the mesh
  67400. * @param scene defines the hosting scene
  67401. * @returns the custom extruded shape mesh
  67402. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  67403. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67404. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67405. */
  67406. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  67407. var path = options.path;
  67408. var shape = options.shape;
  67409. var scaleFunction = options.scaleFunction || (function () { return 1; });
  67410. var rotationFunction = options.rotationFunction || (function () { return 0; });
  67411. var ribbonCloseArray = options.ribbonCloseArray || false;
  67412. var ribbonClosePath = options.ribbonClosePath || false;
  67413. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  67414. var updatable = options.updatable;
  67415. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67416. var instance = options.instance;
  67417. var invertUV = options.invertUV || false;
  67418. 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);
  67419. };
  67420. /**
  67421. * Creates lathe mesh.
  67422. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  67423. * * 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
  67424. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  67425. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  67426. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  67427. * * 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
  67428. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  67429. * * 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
  67430. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67431. * * 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
  67432. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67433. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67434. * @param name defines the name of the mesh
  67435. * @param options defines the options used to create the mesh
  67436. * @param scene defines the hosting scene
  67437. * @returns the lathe mesh
  67438. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  67439. */
  67440. MeshBuilder.CreateLathe = function (name, options, scene) {
  67441. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  67442. var closed = (options.closed === undefined) ? true : options.closed;
  67443. var shape = options.shape;
  67444. var radius = options.radius || 1;
  67445. var tessellation = options.tessellation || 64;
  67446. var clip = options.clip || 0;
  67447. var updatable = options.updatable;
  67448. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67449. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  67450. var pi2 = Math.PI * 2;
  67451. var paths = new Array();
  67452. var invertUV = options.invertUV || false;
  67453. var i = 0;
  67454. var p = 0;
  67455. var step = pi2 / tessellation * arc;
  67456. var rotated;
  67457. var path = new Array();
  67458. for (i = 0; i <= tessellation - clip; i++) {
  67459. var path = [];
  67460. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  67461. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  67462. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  67463. }
  67464. for (p = 0; p < shape.length; p++) {
  67465. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  67466. path.push(rotated);
  67467. }
  67468. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  67469. 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));
  67470. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  67471. }
  67472. paths.push(path);
  67473. }
  67474. // lathe ribbon
  67475. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  67476. return lathe;
  67477. };
  67478. /**
  67479. * Creates a plane mesh
  67480. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  67481. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  67482. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  67483. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67484. * * 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
  67485. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67486. * @param name defines the name of the mesh
  67487. * @param options defines the options used to create the mesh
  67488. * @param scene defines the hosting scene
  67489. * @returns the plane mesh
  67490. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  67491. */
  67492. MeshBuilder.CreatePlane = function (name, options, scene) {
  67493. var plane = new BABYLON.Mesh(name, scene);
  67494. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67495. plane._originalBuilderSideOrientation = options.sideOrientation;
  67496. var vertexData = BABYLON.VertexData.CreatePlane(options);
  67497. vertexData.applyToMesh(plane, options.updatable);
  67498. if (options.sourcePlane) {
  67499. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  67500. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  67501. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  67502. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  67503. plane.rotate(vectorProduct, product);
  67504. }
  67505. }
  67506. return plane;
  67507. };
  67508. /**
  67509. * Creates a ground mesh
  67510. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  67511. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  67512. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67513. * @param name defines the name of the mesh
  67514. * @param options defines the options used to create the mesh
  67515. * @param scene defines the hosting scene
  67516. * @returns the ground mesh
  67517. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  67518. */
  67519. MeshBuilder.CreateGround = function (name, options, scene) {
  67520. var ground = new BABYLON.GroundMesh(name, scene);
  67521. ground._setReady(false);
  67522. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  67523. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  67524. ground._width = options.width || 1;
  67525. ground._height = options.height || 1;
  67526. ground._maxX = ground._width / 2;
  67527. ground._maxZ = ground._height / 2;
  67528. ground._minX = -ground._maxX;
  67529. ground._minZ = -ground._maxZ;
  67530. var vertexData = BABYLON.VertexData.CreateGround(options);
  67531. vertexData.applyToMesh(ground, options.updatable);
  67532. ground._setReady(true);
  67533. return ground;
  67534. };
  67535. /**
  67536. * Creates a tiled ground mesh
  67537. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  67538. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  67539. * * 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
  67540. * * 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
  67541. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67542. * @param name defines the name of the mesh
  67543. * @param options defines the options used to create the mesh
  67544. * @param scene defines the hosting scene
  67545. * @returns the tiled ground mesh
  67546. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  67547. */
  67548. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  67549. var tiledGround = new BABYLON.Mesh(name, scene);
  67550. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  67551. vertexData.applyToMesh(tiledGround, options.updatable);
  67552. return tiledGround;
  67553. };
  67554. /**
  67555. * Creates a ground mesh from a height map
  67556. * * The parameter `url` sets the URL of the height map image resource.
  67557. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  67558. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  67559. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  67560. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  67561. * * 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.
  67562. * * 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).
  67563. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  67564. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67565. * @param name defines the name of the mesh
  67566. * @param url defines the url to the height map
  67567. * @param options defines the options used to create the mesh
  67568. * @param scene defines the hosting scene
  67569. * @returns the ground mesh
  67570. * @see http://doc.babylonjs.com/babylon101/height_map
  67571. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  67572. */
  67573. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  67574. var width = options.width || 10.0;
  67575. var height = options.height || 10.0;
  67576. var subdivisions = options.subdivisions || 1 | 0;
  67577. var minHeight = options.minHeight || 0.0;
  67578. var maxHeight = options.maxHeight || 1.0;
  67579. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  67580. var alphaFilter = options.alphaFilter || 0.0;
  67581. var updatable = options.updatable;
  67582. var onReady = options.onReady;
  67583. var ground = new BABYLON.GroundMesh(name, scene);
  67584. ground._subdivisionsX = subdivisions;
  67585. ground._subdivisionsY = subdivisions;
  67586. ground._width = width;
  67587. ground._height = height;
  67588. ground._maxX = ground._width / 2.0;
  67589. ground._maxZ = ground._height / 2.0;
  67590. ground._minX = -ground._maxX;
  67591. ground._minZ = -ground._maxZ;
  67592. ground._setReady(false);
  67593. var onload = function (img) {
  67594. // Getting height map data
  67595. var canvas = document.createElement("canvas");
  67596. var context = canvas.getContext("2d");
  67597. if (!context) {
  67598. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  67599. }
  67600. if (scene.isDisposed) {
  67601. return;
  67602. }
  67603. var bufferWidth = img.width;
  67604. var bufferHeight = img.height;
  67605. canvas.width = bufferWidth;
  67606. canvas.height = bufferHeight;
  67607. context.drawImage(img, 0, 0);
  67608. // Create VertexData from map data
  67609. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  67610. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  67611. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  67612. width: width, height: height,
  67613. subdivisions: subdivisions,
  67614. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  67615. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  67616. alphaFilter: alphaFilter
  67617. });
  67618. vertexData.applyToMesh(ground, updatable);
  67619. //execute ready callback, if set
  67620. if (onReady) {
  67621. onReady(ground);
  67622. }
  67623. ground._setReady(true);
  67624. };
  67625. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  67626. return ground;
  67627. };
  67628. /**
  67629. * Creates a polygon mesh
  67630. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  67631. * * 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
  67632. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67633. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67634. * * 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)
  67635. * * Remember you can only change the shape positions, not their number when updating a polygon
  67636. * @param name defines the name of the mesh
  67637. * @param options defines the options used to create the mesh
  67638. * @param scene defines the hosting scene
  67639. * @returns the polygon mesh
  67640. */
  67641. MeshBuilder.CreatePolygon = function (name, options, scene) {
  67642. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67643. var shape = options.shape;
  67644. var holes = options.holes || [];
  67645. var depth = options.depth || 0;
  67646. var contours = [];
  67647. var hole = [];
  67648. for (var i = 0; i < shape.length; i++) {
  67649. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  67650. }
  67651. var epsilon = 0.00000001;
  67652. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  67653. contours.pop();
  67654. }
  67655. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  67656. for (var hNb = 0; hNb < holes.length; hNb++) {
  67657. hole = [];
  67658. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  67659. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  67660. }
  67661. polygonTriangulation.addHole(hole);
  67662. }
  67663. var polygon = polygonTriangulation.build(options.updatable, depth);
  67664. polygon._originalBuilderSideOrientation = options.sideOrientation;
  67665. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  67666. vertexData.applyToMesh(polygon, options.updatable);
  67667. return polygon;
  67668. };
  67669. ;
  67670. /**
  67671. * Creates an extruded polygon mesh, with depth in the Y direction.
  67672. * * 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)
  67673. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67674. * @param name defines the name of the mesh
  67675. * @param options defines the options used to create the mesh
  67676. * @param scene defines the hosting scene
  67677. * @returns the polygon mesh
  67678. */
  67679. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  67680. return MeshBuilder.CreatePolygon(name, options, scene);
  67681. };
  67682. ;
  67683. /**
  67684. * Creates a tube mesh.
  67685. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67686. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  67687. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  67688. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  67689. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  67690. * * 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)
  67691. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  67692. * * 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
  67693. * * 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
  67694. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67695. * * 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
  67696. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67697. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67698. * @param name defines the name of the mesh
  67699. * @param options defines the options used to create the mesh
  67700. * @param scene defines the hosting scene
  67701. * @returns the tube mesh
  67702. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67703. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  67704. */
  67705. MeshBuilder.CreateTube = function (name, options, scene) {
  67706. var path = options.path;
  67707. var instance = options.instance;
  67708. var radius = 1.0;
  67709. if (options.radius !== undefined) {
  67710. radius = options.radius;
  67711. }
  67712. else if (instance) {
  67713. radius = instance._creationDataStorage.radius;
  67714. }
  67715. var tessellation = options.tessellation || 64 | 0;
  67716. var radiusFunction = options.radiusFunction || null;
  67717. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  67718. var invertUV = options.invertUV || false;
  67719. var updatable = options.updatable;
  67720. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67721. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  67722. // tube geometry
  67723. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  67724. var tangents = path3D.getTangents();
  67725. var normals = path3D.getNormals();
  67726. var distances = path3D.getDistances();
  67727. var pi2 = Math.PI * 2;
  67728. var step = pi2 / tessellation * arc;
  67729. var returnRadius = function () { return radius; };
  67730. var radiusFunctionFinal = radiusFunction || returnRadius;
  67731. var circlePath;
  67732. var rad;
  67733. var normal;
  67734. var rotated;
  67735. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  67736. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  67737. for (var i = 0; i < path.length; i++) {
  67738. rad = radiusFunctionFinal(i, distances[i]); // current radius
  67739. circlePath = Array(); // current circle array
  67740. normal = normals[i]; // current normal
  67741. for (var t = 0; t < tessellation; t++) {
  67742. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  67743. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  67744. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  67745. rotated.scaleInPlace(rad).addInPlace(path[i]);
  67746. circlePath[t] = rotated;
  67747. }
  67748. circlePaths[index] = circlePath;
  67749. index++;
  67750. }
  67751. // cap
  67752. var capPath = function (nbPoints, pathIndex) {
  67753. var pointCap = Array();
  67754. for (var i = 0; i < nbPoints; i++) {
  67755. pointCap.push(path[pathIndex]);
  67756. }
  67757. return pointCap;
  67758. };
  67759. switch (cap) {
  67760. case BABYLON.Mesh.NO_CAP:
  67761. break;
  67762. case BABYLON.Mesh.CAP_START:
  67763. circlePaths[0] = capPath(tessellation, 0);
  67764. circlePaths[1] = circlePaths[2].slice(0);
  67765. break;
  67766. case BABYLON.Mesh.CAP_END:
  67767. circlePaths[index] = circlePaths[index - 1].slice(0);
  67768. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  67769. break;
  67770. case BABYLON.Mesh.CAP_ALL:
  67771. circlePaths[0] = capPath(tessellation, 0);
  67772. circlePaths[1] = circlePaths[2].slice(0);
  67773. circlePaths[index] = circlePaths[index - 1].slice(0);
  67774. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  67775. break;
  67776. default:
  67777. break;
  67778. }
  67779. return circlePaths;
  67780. };
  67781. var path3D;
  67782. var pathArray;
  67783. if (instance) { // tube update
  67784. var arc = options.arc || instance.arc;
  67785. var storage = instance._creationDataStorage;
  67786. path3D = storage.path3D.update(path);
  67787. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  67788. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  67789. // Update mode, no need to recreate the storage.
  67790. storage.path3D = path3D;
  67791. storage.pathArray = pathArray;
  67792. storage.arc = arc;
  67793. storage.radius = radius;
  67794. return instance;
  67795. }
  67796. // tube creation
  67797. path3D = new BABYLON.Path3D(path);
  67798. var newPathArray = new Array();
  67799. cap = (cap < 0 || cap > 3) ? 0 : cap;
  67800. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  67801. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  67802. tube._creationDataStorage = new BABYLON._CreationDataStorage();
  67803. tube._creationDataStorage.pathArray = pathArray;
  67804. tube._creationDataStorage.path3D = path3D;
  67805. tube._creationDataStorage.tessellation = tessellation;
  67806. tube._creationDataStorage.cap = cap;
  67807. tube._creationDataStorage.arc = options.arc;
  67808. tube._creationDataStorage.radius = radius;
  67809. return tube;
  67810. };
  67811. /**
  67812. * Creates a polyhedron mesh
  67813. * * 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
  67814. * * The parameter `size` (positive float, default 1) sets the polygon size
  67815. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  67816. * * 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`
  67817. * * 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
  67818. * * 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)`)
  67819. * * 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
  67820. * * 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
  67821. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67822. * * 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
  67823. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67824. * @param name defines the name of the mesh
  67825. * @param options defines the options used to create the mesh
  67826. * @param scene defines the hosting scene
  67827. * @returns the polyhedron mesh
  67828. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  67829. */
  67830. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  67831. var polyhedron = new BABYLON.Mesh(name, scene);
  67832. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67833. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  67834. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  67835. vertexData.applyToMesh(polyhedron, options.updatable);
  67836. return polyhedron;
  67837. };
  67838. /**
  67839. * Creates a decal mesh.
  67840. * 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
  67841. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  67842. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  67843. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  67844. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  67845. * @param name defines the name of the mesh
  67846. * @param sourceMesh defines the mesh where the decal must be applied
  67847. * @param options defines the options used to create the mesh
  67848. * @param scene defines the hosting scene
  67849. * @returns the decal mesh
  67850. * @see http://doc.babylonjs.com/how_to/decals
  67851. */
  67852. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  67853. var indices = sourceMesh.getIndices();
  67854. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67855. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67856. var position = options.position || BABYLON.Vector3.Zero();
  67857. var normal = options.normal || BABYLON.Vector3.Up();
  67858. var size = options.size || BABYLON.Vector3.One();
  67859. var angle = options.angle || 0;
  67860. // Getting correct rotation
  67861. if (!normal) {
  67862. var target = new BABYLON.Vector3(0, 0, 1);
  67863. var camera = sourceMesh.getScene().activeCamera;
  67864. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  67865. normal = camera.globalPosition.subtract(cameraWorldTarget);
  67866. }
  67867. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  67868. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  67869. var pitch = Math.atan2(normal.y, len);
  67870. // Matrix
  67871. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  67872. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  67873. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  67874. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  67875. var vertexData = new BABYLON.VertexData();
  67876. vertexData.indices = [];
  67877. vertexData.positions = [];
  67878. vertexData.normals = [];
  67879. vertexData.uvs = [];
  67880. var currentVertexDataIndex = 0;
  67881. var extractDecalVector3 = function (indexId) {
  67882. var result = new BABYLON.PositionNormalVertex();
  67883. if (!indices || !positions || !normals) {
  67884. return result;
  67885. }
  67886. var vertexId = indices[indexId];
  67887. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  67888. // Send vector to decal local world
  67889. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  67890. // Get normal
  67891. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  67892. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  67893. return result;
  67894. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  67895. var clip = function (vertices, axis) {
  67896. if (vertices.length === 0) {
  67897. return vertices;
  67898. }
  67899. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  67900. var clipVertices = function (v0, v1) {
  67901. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  67902. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  67903. };
  67904. var result = new Array();
  67905. for (var index = 0; index < vertices.length; index += 3) {
  67906. var v1Out;
  67907. var v2Out;
  67908. var v3Out;
  67909. var total = 0;
  67910. var nV1 = null;
  67911. var nV2 = null;
  67912. var nV3 = null;
  67913. var nV4 = null;
  67914. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  67915. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  67916. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  67917. v1Out = d1 > 0;
  67918. v2Out = d2 > 0;
  67919. v3Out = d3 > 0;
  67920. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  67921. switch (total) {
  67922. case 0:
  67923. result.push(vertices[index]);
  67924. result.push(vertices[index + 1]);
  67925. result.push(vertices[index + 2]);
  67926. break;
  67927. case 1:
  67928. if (v1Out) {
  67929. nV1 = vertices[index + 1];
  67930. nV2 = vertices[index + 2];
  67931. nV3 = clipVertices(vertices[index], nV1);
  67932. nV4 = clipVertices(vertices[index], nV2);
  67933. }
  67934. if (v2Out) {
  67935. nV1 = vertices[index];
  67936. nV2 = vertices[index + 2];
  67937. nV3 = clipVertices(vertices[index + 1], nV1);
  67938. nV4 = clipVertices(vertices[index + 1], nV2);
  67939. result.push(nV3);
  67940. result.push(nV2.clone());
  67941. result.push(nV1.clone());
  67942. result.push(nV2.clone());
  67943. result.push(nV3.clone());
  67944. result.push(nV4);
  67945. break;
  67946. }
  67947. if (v3Out) {
  67948. nV1 = vertices[index];
  67949. nV2 = vertices[index + 1];
  67950. nV3 = clipVertices(vertices[index + 2], nV1);
  67951. nV4 = clipVertices(vertices[index + 2], nV2);
  67952. }
  67953. if (nV1 && nV2 && nV3 && nV4) {
  67954. result.push(nV1.clone());
  67955. result.push(nV2.clone());
  67956. result.push(nV3);
  67957. result.push(nV4);
  67958. result.push(nV3.clone());
  67959. result.push(nV2.clone());
  67960. }
  67961. break;
  67962. case 2:
  67963. if (!v1Out) {
  67964. nV1 = vertices[index].clone();
  67965. nV2 = clipVertices(nV1, vertices[index + 1]);
  67966. nV3 = clipVertices(nV1, vertices[index + 2]);
  67967. result.push(nV1);
  67968. result.push(nV2);
  67969. result.push(nV3);
  67970. }
  67971. if (!v2Out) {
  67972. nV1 = vertices[index + 1].clone();
  67973. nV2 = clipVertices(nV1, vertices[index + 2]);
  67974. nV3 = clipVertices(nV1, vertices[index]);
  67975. result.push(nV1);
  67976. result.push(nV2);
  67977. result.push(nV3);
  67978. }
  67979. if (!v3Out) {
  67980. nV1 = vertices[index + 2].clone();
  67981. nV2 = clipVertices(nV1, vertices[index]);
  67982. nV3 = clipVertices(nV1, vertices[index + 1]);
  67983. result.push(nV1);
  67984. result.push(nV2);
  67985. result.push(nV3);
  67986. }
  67987. break;
  67988. case 3:
  67989. break;
  67990. }
  67991. }
  67992. return result;
  67993. };
  67994. for (var index = 0; index < indices.length; index += 3) {
  67995. var faceVertices = new Array();
  67996. faceVertices.push(extractDecalVector3(index));
  67997. faceVertices.push(extractDecalVector3(index + 1));
  67998. faceVertices.push(extractDecalVector3(index + 2));
  67999. // Clip
  68000. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  68001. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  68002. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  68003. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  68004. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  68005. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  68006. if (faceVertices.length === 0) {
  68007. continue;
  68008. }
  68009. // Add UVs and get back to world
  68010. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  68011. var vertex = faceVertices[vIndex];
  68012. //TODO check for Int32Array | Uint32Array | Uint16Array
  68013. vertexData.indices.push(currentVertexDataIndex);
  68014. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  68015. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  68016. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  68017. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  68018. currentVertexDataIndex++;
  68019. }
  68020. }
  68021. // Return mesh
  68022. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  68023. vertexData.applyToMesh(decal);
  68024. decal.position = position.clone();
  68025. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  68026. return decal;
  68027. };
  68028. // Privates
  68029. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  68030. // extrusion geometry
  68031. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  68032. var tangents = path3D.getTangents();
  68033. var normals = path3D.getNormals();
  68034. var binormals = path3D.getBinormals();
  68035. var distances = path3D.getDistances();
  68036. var angle = 0;
  68037. var returnScale = function () { return scale !== null ? scale : 1; };
  68038. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  68039. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  68040. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  68041. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68042. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68043. for (var i = 0; i < curve.length; i++) {
  68044. var shapePath = new Array();
  68045. var angleStep = rotate(i, distances[i]);
  68046. var scaleRatio = scl(i, distances[i]);
  68047. for (var p = 0; p < shape.length; p++) {
  68048. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  68049. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  68050. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  68051. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  68052. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  68053. shapePath[p] = rotated;
  68054. }
  68055. shapePaths[index] = shapePath;
  68056. angle += angleStep;
  68057. index++;
  68058. }
  68059. // cap
  68060. var capPath = function (shapePath) {
  68061. var pointCap = Array();
  68062. var barycenter = BABYLON.Vector3.Zero();
  68063. var i;
  68064. for (i = 0; i < shapePath.length; i++) {
  68065. barycenter.addInPlace(shapePath[i]);
  68066. }
  68067. barycenter.scaleInPlace(1.0 / shapePath.length);
  68068. for (i = 0; i < shapePath.length; i++) {
  68069. pointCap.push(barycenter);
  68070. }
  68071. return pointCap;
  68072. };
  68073. switch (cap) {
  68074. case BABYLON.Mesh.NO_CAP:
  68075. break;
  68076. case BABYLON.Mesh.CAP_START:
  68077. shapePaths[0] = capPath(shapePaths[2]);
  68078. shapePaths[1] = shapePaths[2];
  68079. break;
  68080. case BABYLON.Mesh.CAP_END:
  68081. shapePaths[index] = shapePaths[index - 1];
  68082. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68083. break;
  68084. case BABYLON.Mesh.CAP_ALL:
  68085. shapePaths[0] = capPath(shapePaths[2]);
  68086. shapePaths[1] = shapePaths[2];
  68087. shapePaths[index] = shapePaths[index - 1];
  68088. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68089. break;
  68090. default:
  68091. break;
  68092. }
  68093. return shapePaths;
  68094. };
  68095. var path3D;
  68096. var pathArray;
  68097. if (instance) { // instance update
  68098. var storage = instance._creationDataStorage;
  68099. path3D = storage.path3D.update(curve);
  68100. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  68101. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  68102. return instance;
  68103. }
  68104. // extruded shape creation
  68105. path3D = new BABYLON.Path3D(curve);
  68106. var newShapePaths = new Array();
  68107. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68108. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  68109. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  68110. extrudedGeneric._creationDataStorage = new BABYLON._CreationDataStorage();
  68111. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  68112. extrudedGeneric._creationDataStorage.path3D = path3D;
  68113. extrudedGeneric._creationDataStorage.cap = cap;
  68114. return extrudedGeneric;
  68115. };
  68116. return MeshBuilder;
  68117. }());
  68118. BABYLON.MeshBuilder = MeshBuilder;
  68119. })(BABYLON || (BABYLON = {}));
  68120. //# sourceMappingURL=babylon.meshBuilder.js.map
  68121. var BABYLON;
  68122. (function (BABYLON) {
  68123. /**
  68124. * Draco compression (https://google.github.io/draco/)
  68125. *
  68126. * This class wraps the Draco module.
  68127. *
  68128. * **Encoder**
  68129. *
  68130. * The encoder is not currently implemented.
  68131. *
  68132. * **Decoder**
  68133. *
  68134. * 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.
  68135. *
  68136. * To update the configuration, use the following code:
  68137. * ```javascript
  68138. * BABYLON.DracoCompression.Configuration = {
  68139. * decoder: {
  68140. * wasmUrl: "<url to the WebAssembly library>",
  68141. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  68142. * fallbackUrl: "<url to the fallback JavaScript library>",
  68143. * }
  68144. * };
  68145. * ```
  68146. *
  68147. * 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.
  68148. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  68149. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  68150. *
  68151. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  68152. * ```javascript
  68153. * var dracoCompression = new BABYLON.DracoCompression();
  68154. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  68155. * [BABYLON.VertexBuffer.PositionKind]: 0
  68156. * });
  68157. * ```
  68158. *
  68159. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  68160. */
  68161. var DracoCompression = /** @class */ (function () {
  68162. /**
  68163. * Constructor
  68164. */
  68165. function DracoCompression() {
  68166. }
  68167. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  68168. /**
  68169. * Returns true if the decoder is available.
  68170. */
  68171. get: function () {
  68172. if (typeof DracoDecoderModule !== "undefined") {
  68173. return true;
  68174. }
  68175. var decoder = DracoCompression.Configuration.decoder;
  68176. if (decoder) {
  68177. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68178. return true;
  68179. }
  68180. if (decoder.fallbackUrl) {
  68181. return true;
  68182. }
  68183. }
  68184. return false;
  68185. },
  68186. enumerable: true,
  68187. configurable: true
  68188. });
  68189. /**
  68190. * Stop all async operations and release resources.
  68191. */
  68192. DracoCompression.prototype.dispose = function () {
  68193. };
  68194. /**
  68195. * Decode Draco compressed mesh data to vertex data.
  68196. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  68197. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  68198. * @returns A promise that resolves with the decoded vertex data
  68199. */
  68200. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  68201. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  68202. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  68203. var module = wrappedModule.module;
  68204. var vertexData = new BABYLON.VertexData();
  68205. var buffer = new module.DecoderBuffer();
  68206. buffer.Init(dataView, dataView.byteLength);
  68207. var decoder = new module.Decoder();
  68208. var geometry;
  68209. var status;
  68210. try {
  68211. var type = decoder.GetEncodedGeometryType(buffer);
  68212. switch (type) {
  68213. case module.TRIANGULAR_MESH:
  68214. geometry = new module.Mesh();
  68215. status = decoder.DecodeBufferToMesh(buffer, geometry);
  68216. break;
  68217. case module.POINT_CLOUD:
  68218. geometry = new module.PointCloud();
  68219. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  68220. break;
  68221. default:
  68222. throw new Error("Invalid geometry type " + type);
  68223. }
  68224. if (!status.ok() || !geometry.ptr) {
  68225. throw new Error(status.error_msg());
  68226. }
  68227. var numPoints = geometry.num_points();
  68228. if (type === module.TRIANGULAR_MESH) {
  68229. var numFaces = geometry.num_faces();
  68230. var faceIndices = new module.DracoInt32Array();
  68231. try {
  68232. var indices = new Uint32Array(numFaces * 3);
  68233. for (var i = 0; i < numFaces; i++) {
  68234. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  68235. var offset = i * 3;
  68236. indices[offset + 0] = faceIndices.GetValue(0);
  68237. indices[offset + 1] = faceIndices.GetValue(1);
  68238. indices[offset + 2] = faceIndices.GetValue(2);
  68239. }
  68240. vertexData.indices = indices;
  68241. }
  68242. finally {
  68243. module.destroy(faceIndices);
  68244. }
  68245. }
  68246. for (var kind in attributes) {
  68247. var uniqueId = attributes[kind];
  68248. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  68249. var dracoData = new module.DracoFloat32Array();
  68250. try {
  68251. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  68252. var babylonData = new Float32Array(numPoints * attribute.num_components());
  68253. for (var i = 0; i < babylonData.length; i++) {
  68254. babylonData[i] = dracoData.GetValue(i);
  68255. }
  68256. vertexData.set(babylonData, kind);
  68257. }
  68258. finally {
  68259. module.destroy(dracoData);
  68260. }
  68261. }
  68262. }
  68263. finally {
  68264. if (geometry) {
  68265. module.destroy(geometry);
  68266. }
  68267. module.destroy(decoder);
  68268. module.destroy(buffer);
  68269. }
  68270. return vertexData;
  68271. });
  68272. };
  68273. DracoCompression._GetDecoderModule = function () {
  68274. if (!DracoCompression._DecoderModulePromise) {
  68275. var promise = null;
  68276. var config_1 = {};
  68277. if (typeof DracoDecoderModule !== "undefined") {
  68278. promise = Promise.resolve();
  68279. }
  68280. else {
  68281. var decoder = DracoCompression.Configuration.decoder;
  68282. if (decoder) {
  68283. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68284. promise = Promise.all([
  68285. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  68286. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  68287. config_1.wasmBinary = data;
  68288. })
  68289. ]);
  68290. }
  68291. else if (decoder.fallbackUrl) {
  68292. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  68293. }
  68294. }
  68295. }
  68296. if (!promise) {
  68297. throw new Error("Draco decoder module is not available");
  68298. }
  68299. DracoCompression._DecoderModulePromise = promise.then(function () {
  68300. return new Promise(function (resolve) {
  68301. config_1.onModuleLoaded = function (decoderModule) {
  68302. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  68303. resolve({ module: decoderModule });
  68304. };
  68305. DracoDecoderModule(config_1);
  68306. });
  68307. });
  68308. }
  68309. return DracoCompression._DecoderModulePromise;
  68310. };
  68311. DracoCompression._LoadScriptAsync = function (url) {
  68312. return new Promise(function (resolve, reject) {
  68313. BABYLON.Tools.LoadScript(url, function () {
  68314. resolve();
  68315. }, function (message) {
  68316. reject(new Error(message));
  68317. });
  68318. });
  68319. };
  68320. DracoCompression._LoadFileAsync = function (url) {
  68321. return new Promise(function (resolve, reject) {
  68322. BABYLON.Tools.LoadFile(url, function (data) {
  68323. resolve(data);
  68324. }, undefined, undefined, true, function (request, exception) {
  68325. reject(exception);
  68326. });
  68327. });
  68328. };
  68329. /**
  68330. * The configuration. Defaults to the following urls:
  68331. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  68332. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  68333. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  68334. */
  68335. DracoCompression.Configuration = {
  68336. decoder: {
  68337. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  68338. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  68339. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  68340. }
  68341. };
  68342. return DracoCompression;
  68343. }());
  68344. BABYLON.DracoCompression = DracoCompression;
  68345. })(BABYLON || (BABYLON = {}));
  68346. //# sourceMappingURL=babylon.dracoCompression.js.map
  68347. var BABYLON;
  68348. (function (BABYLON) {
  68349. // Sets the default audio engine to Babylon JS.
  68350. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  68351. /**
  68352. * This represents the default audio engine used in babylon.
  68353. * It is responsible to play, synchronize and analyse sounds throughout the application.
  68354. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68355. */
  68356. var AudioEngine = /** @class */ (function () {
  68357. /**
  68358. * Instantiates a new audio engine.
  68359. *
  68360. * There should be only one per page as some browsers restrict the number
  68361. * of audio contexts you can create.
  68362. * @param engine defines the hosting engine
  68363. */
  68364. function AudioEngine(engine) {
  68365. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  68366. var _this = this;
  68367. this._audioContext = null;
  68368. this._audioContextInitialized = false;
  68369. this._muteButton = null;
  68370. /**
  68371. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  68372. */
  68373. this.canUseWebAudio = false;
  68374. /**
  68375. * Defines if Babylon should emit a warning if WebAudio is not supported.
  68376. * @ignoreNaming
  68377. */
  68378. this.WarnedWebAudioUnsupported = false;
  68379. /**
  68380. * Gets whether or not mp3 are supported by your browser.
  68381. */
  68382. this.isMP3supported = false;
  68383. /**
  68384. * Gets whether or not ogg are supported by your browser.
  68385. */
  68386. this.isOGGsupported = false;
  68387. /**
  68388. * Gets whether audio has been unlocked on the device.
  68389. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  68390. * a user interaction has happened.
  68391. */
  68392. this.unlocked = true;
  68393. /**
  68394. * Defines if the audio engine relies on a custom unlocked button.
  68395. * In this case, the embedded button will not be displayed.
  68396. */
  68397. this.useCustomUnlockedButton = false;
  68398. /**
  68399. * Event raised when audio has been unlocked on the browser.
  68400. */
  68401. this.onAudioUnlockedObservable = new BABYLON.Observable();
  68402. /**
  68403. * Event raised when audio has been locked on the browser.
  68404. */
  68405. this.onAudioLockedObservable = new BABYLON.Observable();
  68406. this._tryToRun = false;
  68407. this._onResize = function () {
  68408. _this._moveButtonToTopLeft();
  68409. };
  68410. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  68411. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  68412. this.canUseWebAudio = true;
  68413. }
  68414. var audioElem = document.createElement('audio');
  68415. this._engine = engine;
  68416. try {
  68417. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  68418. this.isMP3supported = true;
  68419. }
  68420. }
  68421. catch (e) {
  68422. // protect error during capability check.
  68423. }
  68424. try {
  68425. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  68426. this.isOGGsupported = true;
  68427. }
  68428. }
  68429. catch (e) {
  68430. // protect error during capability check.
  68431. }
  68432. }
  68433. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  68434. /**
  68435. * Gets the current AudioContext if available.
  68436. */
  68437. get: function () {
  68438. if (!this._audioContextInitialized) {
  68439. this._initializeAudioContext();
  68440. }
  68441. else {
  68442. if (!this.unlocked && !this._muteButton) {
  68443. this._displayMuteButton();
  68444. }
  68445. }
  68446. return this._audioContext;
  68447. },
  68448. enumerable: true,
  68449. configurable: true
  68450. });
  68451. /**
  68452. * Flags the audio engine in Locked state.
  68453. * This happens due to new browser policies preventing audio to autoplay.
  68454. */
  68455. AudioEngine.prototype.lock = function () {
  68456. this._triggerSuspendedState();
  68457. };
  68458. /**
  68459. * Unlocks the audio engine once a user action has been done on the dom.
  68460. * This is helpful to resume play once browser policies have been satisfied.
  68461. */
  68462. AudioEngine.prototype.unlock = function () {
  68463. this._triggerRunningState();
  68464. };
  68465. AudioEngine.prototype._resumeAudioContext = function () {
  68466. var result;
  68467. if (this._audioContext.resume) {
  68468. result = this._audioContext.resume();
  68469. }
  68470. return result || Promise.resolve();
  68471. };
  68472. AudioEngine.prototype._initializeAudioContext = function () {
  68473. var _this = this;
  68474. try {
  68475. if (this.canUseWebAudio) {
  68476. this._audioContext = new AudioContext();
  68477. // create a global volume gain node
  68478. this.masterGain = this._audioContext.createGain();
  68479. this.masterGain.gain.value = 1;
  68480. this.masterGain.connect(this._audioContext.destination);
  68481. this._audioContextInitialized = true;
  68482. if (this._audioContext.state === "running") {
  68483. // Do not wait for the promise to unlock.
  68484. this._triggerRunningState();
  68485. }
  68486. else {
  68487. if (this._audioContext && this._audioContext.resume) {
  68488. this._resumeAudioContext().then(function () {
  68489. _this._triggerRunningState();
  68490. }).catch(function () {
  68491. // Can not resume automatically
  68492. // Needs user action
  68493. _this.lock();
  68494. });
  68495. }
  68496. }
  68497. }
  68498. }
  68499. catch (e) {
  68500. this.canUseWebAudio = false;
  68501. BABYLON.Tools.Error("Web Audio: " + e.message);
  68502. }
  68503. };
  68504. AudioEngine.prototype._triggerRunningState = function () {
  68505. var _this = this;
  68506. if (this._tryToRun) {
  68507. return;
  68508. }
  68509. this._tryToRun = true;
  68510. this._resumeAudioContext()
  68511. .then(function () {
  68512. _this._tryToRun = false;
  68513. _this.unlocked = true;
  68514. if (_this._muteButton) {
  68515. _this._hideMuteButton();
  68516. }
  68517. // Notify users that the audio stack is unlocked/unmuted
  68518. _this.onAudioUnlockedObservable.notifyObservers(_this);
  68519. }).catch(function () {
  68520. _this._tryToRun = false;
  68521. _this.unlocked = false;
  68522. });
  68523. };
  68524. AudioEngine.prototype._triggerSuspendedState = function () {
  68525. this.unlocked = false;
  68526. this.onAudioLockedObservable.notifyObservers(this);
  68527. this._displayMuteButton();
  68528. };
  68529. AudioEngine.prototype._displayMuteButton = function () {
  68530. var _this = this;
  68531. if (this.useCustomUnlockedButton) {
  68532. return;
  68533. }
  68534. this._canvas = this._engine.getRenderingCanvas();
  68535. this._muteButton = document.createElement("BUTTON");
  68536. this._muteButton.className = "babylonUnmuteIcon";
  68537. this._muteButton.id = "babylonUnmuteIconBtn";
  68538. this._muteButton.title = "Unmute";
  68539. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; 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: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  68540. var style = document.createElement('style');
  68541. style.appendChild(document.createTextNode(css));
  68542. document.getElementsByTagName('head')[0].appendChild(style);
  68543. document.body.appendChild(this._muteButton);
  68544. this._moveButtonToTopLeft();
  68545. this._muteButton.addEventListener('mousedown', function () {
  68546. _this._triggerRunningState();
  68547. }, true);
  68548. this._muteButton.addEventListener('touchend', function () {
  68549. _this._triggerRunningState();
  68550. }, true);
  68551. this._muteButton.addEventListener('click', function () {
  68552. _this._triggerRunningState();
  68553. }, true);
  68554. window.addEventListener("resize", this._onResize);
  68555. };
  68556. AudioEngine.prototype._moveButtonToTopLeft = function () {
  68557. if (this._canvas && this._muteButton) {
  68558. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  68559. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  68560. }
  68561. };
  68562. AudioEngine.prototype._hideMuteButton = function () {
  68563. if (this._muteButton) {
  68564. document.body.removeChild(this._muteButton);
  68565. this._muteButton = null;
  68566. }
  68567. };
  68568. /**
  68569. * Destroy and release the resources associated with the audio ccontext.
  68570. */
  68571. AudioEngine.prototype.dispose = function () {
  68572. if (this.canUseWebAudio && this._audioContextInitialized) {
  68573. if (this._connectedAnalyser && this._audioContext) {
  68574. this._connectedAnalyser.stopDebugCanvas();
  68575. this._connectedAnalyser.dispose();
  68576. this.masterGain.disconnect();
  68577. this.masterGain.connect(this._audioContext.destination);
  68578. this._connectedAnalyser = null;
  68579. }
  68580. this.masterGain.gain.value = 1;
  68581. }
  68582. this.WarnedWebAudioUnsupported = false;
  68583. this._hideMuteButton();
  68584. window.removeEventListener("resize", this._onResize);
  68585. this.onAudioUnlockedObservable.clear();
  68586. this.onAudioLockedObservable.clear();
  68587. };
  68588. /**
  68589. * Gets the global volume sets on the master gain.
  68590. * @returns the global volume if set or -1 otherwise
  68591. */
  68592. AudioEngine.prototype.getGlobalVolume = function () {
  68593. if (this.canUseWebAudio && this._audioContextInitialized) {
  68594. return this.masterGain.gain.value;
  68595. }
  68596. else {
  68597. return -1;
  68598. }
  68599. };
  68600. /**
  68601. * Sets the global volume of your experience (sets on the master gain).
  68602. * @param newVolume Defines the new global volume of the application
  68603. */
  68604. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  68605. if (this.canUseWebAudio && this._audioContextInitialized) {
  68606. this.masterGain.gain.value = newVolume;
  68607. }
  68608. };
  68609. /**
  68610. * Connect the audio engine to an audio analyser allowing some amazing
  68611. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68612. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68613. * @param analyser The analyser to connect to the engine
  68614. */
  68615. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  68616. if (this._connectedAnalyser) {
  68617. this._connectedAnalyser.stopDebugCanvas();
  68618. }
  68619. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  68620. this._connectedAnalyser = analyser;
  68621. this.masterGain.disconnect();
  68622. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  68623. }
  68624. };
  68625. return AudioEngine;
  68626. }());
  68627. BABYLON.AudioEngine = AudioEngine;
  68628. })(BABYLON || (BABYLON = {}));
  68629. //# sourceMappingURL=babylon.audioEngine.js.map
  68630. var BABYLON;
  68631. (function (BABYLON) {
  68632. /**
  68633. * Defines a sound that can be played in the application.
  68634. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  68635. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68636. */
  68637. var Sound = /** @class */ (function () {
  68638. /**
  68639. * Create a sound and attach it to a scene
  68640. * @param name Name of your sound
  68641. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  68642. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  68643. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  68644. */
  68645. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  68646. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  68647. var _this = this;
  68648. /**
  68649. * Does the sound autoplay once loaded.
  68650. */
  68651. this.autoplay = false;
  68652. /**
  68653. * Does the sound loop after it finishes playing once.
  68654. */
  68655. this.loop = false;
  68656. /**
  68657. * Does the sound use a custom attenuation curve to simulate the falloff
  68658. * happening when the source gets further away from the camera.
  68659. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68660. */
  68661. this.useCustomAttenuation = false;
  68662. /**
  68663. * Is this sound currently played.
  68664. */
  68665. this.isPlaying = false;
  68666. /**
  68667. * Is this sound currently paused.
  68668. */
  68669. this.isPaused = false;
  68670. /**
  68671. * Does this sound enables spatial sound.
  68672. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68673. */
  68674. this.spatialSound = false;
  68675. /**
  68676. * Define the reference distance the sound should be heard perfectly.
  68677. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68678. */
  68679. this.refDistance = 1;
  68680. /**
  68681. * Define the roll off factor of spatial sounds.
  68682. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68683. */
  68684. this.rolloffFactor = 1;
  68685. /**
  68686. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  68687. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68688. */
  68689. this.maxDistance = 100;
  68690. /**
  68691. * Define the distance attenuation model the sound will follow.
  68692. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68693. */
  68694. this.distanceModel = "linear";
  68695. /**
  68696. * Observable event when the current playing sound finishes.
  68697. */
  68698. this.onEndedObservable = new BABYLON.Observable();
  68699. this._panningModel = "equalpower";
  68700. this._playbackRate = 1;
  68701. this._streaming = false;
  68702. this._startTime = 0;
  68703. this._startOffset = 0;
  68704. this._position = BABYLON.Vector3.Zero();
  68705. /** @hidden */
  68706. this._positionInEmitterSpace = false;
  68707. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  68708. this._volume = 1;
  68709. this._isReadyToPlay = false;
  68710. this._isDirectional = false;
  68711. // Used if you'd like to create a directional sound.
  68712. // If not set, the sound will be omnidirectional
  68713. this._coneInnerAngle = 360;
  68714. this._coneOuterAngle = 360;
  68715. this._coneOuterGain = 0;
  68716. this._isOutputConnected = false;
  68717. this._urlType = "Unknown";
  68718. this.name = name;
  68719. this._scene = scene;
  68720. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68721. if (!compo) {
  68722. compo = new BABYLON.AudioSceneComponent(scene);
  68723. scene._addComponent(compo);
  68724. }
  68725. this._readyToPlayCallback = readyToPlayCallback;
  68726. // Default custom attenuation function is a linear attenuation
  68727. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  68728. if (currentDistance < maxDistance) {
  68729. return currentVolume * (1 - currentDistance / maxDistance);
  68730. }
  68731. else {
  68732. return 0;
  68733. }
  68734. };
  68735. if (options) {
  68736. this.autoplay = options.autoplay || false;
  68737. this.loop = options.loop || false;
  68738. // if volume === 0, we need another way to check this option
  68739. if (options.volume !== undefined) {
  68740. this._volume = options.volume;
  68741. }
  68742. this.spatialSound = options.spatialSound || false;
  68743. this.maxDistance = options.maxDistance || 100;
  68744. this.useCustomAttenuation = options.useCustomAttenuation || false;
  68745. this.rolloffFactor = options.rolloffFactor || 1;
  68746. this.refDistance = options.refDistance || 1;
  68747. this.distanceModel = options.distanceModel || "linear";
  68748. this._playbackRate = options.playbackRate || 1;
  68749. this._streaming = options.streaming || false;
  68750. }
  68751. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68752. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  68753. this._soundGain.gain.value = this._volume;
  68754. this._inputAudioNode = this._soundGain;
  68755. this._outputAudioNode = this._soundGain;
  68756. if (this.spatialSound) {
  68757. this._createSpatialParameters();
  68758. }
  68759. this._scene.mainSoundTrack.AddSound(this);
  68760. var validParameter = true;
  68761. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  68762. if (urlOrArrayBuffer) {
  68763. try {
  68764. if (typeof (urlOrArrayBuffer) === "string") {
  68765. this._urlType = "String";
  68766. }
  68767. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  68768. this._urlType = "ArrayBuffer";
  68769. }
  68770. else if (urlOrArrayBuffer instanceof MediaStream) {
  68771. this._urlType = "MediaStream";
  68772. }
  68773. else if (Array.isArray(urlOrArrayBuffer)) {
  68774. this._urlType = "Array";
  68775. }
  68776. var urls = [];
  68777. var codecSupportedFound = false;
  68778. switch (this._urlType) {
  68779. case "MediaStream":
  68780. this._streaming = true;
  68781. this._isReadyToPlay = true;
  68782. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  68783. if (this.autoplay) {
  68784. this.play();
  68785. }
  68786. if (this._readyToPlayCallback) {
  68787. this._readyToPlayCallback();
  68788. }
  68789. break;
  68790. case "ArrayBuffer":
  68791. if (urlOrArrayBuffer.byteLength > 0) {
  68792. codecSupportedFound = true;
  68793. this._soundLoaded(urlOrArrayBuffer);
  68794. }
  68795. break;
  68796. case "String":
  68797. urls.push(urlOrArrayBuffer);
  68798. case "Array":
  68799. if (urls.length === 0)
  68800. urls = urlOrArrayBuffer;
  68801. // If we found a supported format, we load it immediately and stop the loop
  68802. for (var i = 0; i < urls.length; i++) {
  68803. var url = urls[i];
  68804. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  68805. codecSupportedFound = true;
  68806. }
  68807. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  68808. codecSupportedFound = true;
  68809. }
  68810. if (url.indexOf(".wav", url.length - 4) !== -1) {
  68811. codecSupportedFound = true;
  68812. }
  68813. if (url.indexOf("blob:") !== -1) {
  68814. codecSupportedFound = true;
  68815. }
  68816. if (codecSupportedFound) {
  68817. // Loading sound using XHR2
  68818. if (!this._streaming) {
  68819. this._scene._loadFile(url, function (data) {
  68820. _this._soundLoaded(data);
  68821. }, undefined, true, true, function (exception) {
  68822. if (exception) {
  68823. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  68824. }
  68825. BABYLON.Tools.Error("Sound creation aborted.");
  68826. _this._scene.mainSoundTrack.RemoveSound(_this);
  68827. });
  68828. }
  68829. // Streaming sound using HTML5 Audio tag
  68830. else {
  68831. this._htmlAudioElement = new Audio(url);
  68832. this._htmlAudioElement.controls = false;
  68833. this._htmlAudioElement.loop = this.loop;
  68834. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  68835. this._htmlAudioElement.preload = "auto";
  68836. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  68837. _this._isReadyToPlay = true;
  68838. if (_this.autoplay) {
  68839. _this.play();
  68840. }
  68841. if (_this._readyToPlayCallback) {
  68842. _this._readyToPlayCallback();
  68843. }
  68844. });
  68845. document.body.appendChild(this._htmlAudioElement);
  68846. this._htmlAudioElement.load();
  68847. }
  68848. break;
  68849. }
  68850. }
  68851. break;
  68852. default:
  68853. validParameter = false;
  68854. break;
  68855. }
  68856. if (!validParameter) {
  68857. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  68858. }
  68859. else {
  68860. if (!codecSupportedFound) {
  68861. this._isReadyToPlay = true;
  68862. // Simulating a ready to play event to avoid breaking code path
  68863. if (this._readyToPlayCallback) {
  68864. window.setTimeout(function () {
  68865. if (_this._readyToPlayCallback) {
  68866. _this._readyToPlayCallback();
  68867. }
  68868. }, 1000);
  68869. }
  68870. }
  68871. }
  68872. }
  68873. catch (ex) {
  68874. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  68875. this._scene.mainSoundTrack.RemoveSound(this);
  68876. }
  68877. }
  68878. }
  68879. else {
  68880. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  68881. this._scene.mainSoundTrack.AddSound(this);
  68882. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  68883. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  68884. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  68885. }
  68886. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  68887. if (this._readyToPlayCallback) {
  68888. window.setTimeout(function () {
  68889. if (_this._readyToPlayCallback) {
  68890. _this._readyToPlayCallback();
  68891. }
  68892. }, 1000);
  68893. }
  68894. }
  68895. }
  68896. /**
  68897. * Release the sound and its associated resources
  68898. */
  68899. Sound.prototype.dispose = function () {
  68900. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68901. if (this.isPlaying) {
  68902. this.stop();
  68903. }
  68904. this._isReadyToPlay = false;
  68905. if (this.soundTrackId === -1) {
  68906. this._scene.mainSoundTrack.RemoveSound(this);
  68907. }
  68908. else if (this._scene.soundTracks) {
  68909. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  68910. }
  68911. if (this._soundGain) {
  68912. this._soundGain.disconnect();
  68913. this._soundGain = null;
  68914. }
  68915. if (this._soundPanner) {
  68916. this._soundPanner.disconnect();
  68917. this._soundPanner = null;
  68918. }
  68919. if (this._soundSource) {
  68920. this._soundSource.disconnect();
  68921. this._soundSource = null;
  68922. }
  68923. this._audioBuffer = null;
  68924. if (this._htmlAudioElement) {
  68925. this._htmlAudioElement.pause();
  68926. this._htmlAudioElement.src = "";
  68927. document.body.removeChild(this._htmlAudioElement);
  68928. }
  68929. if (this._streamingSource) {
  68930. this._streamingSource.disconnect();
  68931. }
  68932. if (this._connectedMesh && this._registerFunc) {
  68933. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68934. this._connectedMesh = null;
  68935. }
  68936. }
  68937. };
  68938. /**
  68939. * Gets if the sounds is ready to be played or not.
  68940. * @returns true if ready, otherwise false
  68941. */
  68942. Sound.prototype.isReady = function () {
  68943. return this._isReadyToPlay;
  68944. };
  68945. Sound.prototype._soundLoaded = function (audioData) {
  68946. var _this = this;
  68947. if (!BABYLON.Engine.audioEngine.audioContext) {
  68948. return;
  68949. }
  68950. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  68951. _this._audioBuffer = buffer;
  68952. _this._isReadyToPlay = true;
  68953. if (_this.autoplay) {
  68954. _this.play();
  68955. }
  68956. if (_this._readyToPlayCallback) {
  68957. _this._readyToPlayCallback();
  68958. }
  68959. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  68960. };
  68961. /**
  68962. * Sets the data of the sound from an audiobuffer
  68963. * @param audioBuffer The audioBuffer containing the data
  68964. */
  68965. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  68966. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68967. this._audioBuffer = audioBuffer;
  68968. this._isReadyToPlay = true;
  68969. }
  68970. };
  68971. /**
  68972. * Updates the current sounds options such as maxdistance, loop...
  68973. * @param options A JSON object containing values named as the object properties
  68974. */
  68975. Sound.prototype.updateOptions = function (options) {
  68976. if (options) {
  68977. this.loop = options.loop || this.loop;
  68978. this.maxDistance = options.maxDistance || this.maxDistance;
  68979. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  68980. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  68981. this.refDistance = options.refDistance || this.refDistance;
  68982. this.distanceModel = options.distanceModel || this.distanceModel;
  68983. this._playbackRate = options.playbackRate || this._playbackRate;
  68984. this._updateSpatialParameters();
  68985. if (this.isPlaying) {
  68986. if (this._streaming && this._htmlAudioElement) {
  68987. this._htmlAudioElement.playbackRate = this._playbackRate;
  68988. }
  68989. else {
  68990. if (this._soundSource) {
  68991. this._soundSource.playbackRate.value = this._playbackRate;
  68992. }
  68993. }
  68994. }
  68995. }
  68996. };
  68997. Sound.prototype._createSpatialParameters = function () {
  68998. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68999. if (this._scene.headphone) {
  69000. this._panningModel = "HRTF";
  69001. }
  69002. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  69003. this._updateSpatialParameters();
  69004. this._soundPanner.connect(this._outputAudioNode);
  69005. this._inputAudioNode = this._soundPanner;
  69006. }
  69007. };
  69008. Sound.prototype._updateSpatialParameters = function () {
  69009. if (this.spatialSound && this._soundPanner) {
  69010. if (this.useCustomAttenuation) {
  69011. // Tricks to disable in a way embedded Web Audio attenuation
  69012. this._soundPanner.distanceModel = "linear";
  69013. this._soundPanner.maxDistance = Number.MAX_VALUE;
  69014. this._soundPanner.refDistance = 1;
  69015. this._soundPanner.rolloffFactor = 1;
  69016. this._soundPanner.panningModel = this._panningModel;
  69017. }
  69018. else {
  69019. this._soundPanner.distanceModel = this.distanceModel;
  69020. this._soundPanner.maxDistance = this.maxDistance;
  69021. this._soundPanner.refDistance = this.refDistance;
  69022. this._soundPanner.rolloffFactor = this.rolloffFactor;
  69023. this._soundPanner.panningModel = this._panningModel;
  69024. }
  69025. }
  69026. };
  69027. /**
  69028. * Switch the panning model to HRTF:
  69029. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69030. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69031. */
  69032. Sound.prototype.switchPanningModelToHRTF = function () {
  69033. this._panningModel = "HRTF";
  69034. this._switchPanningModel();
  69035. };
  69036. /**
  69037. * Switch the panning model to Equal Power:
  69038. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69039. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69040. */
  69041. Sound.prototype.switchPanningModelToEqualPower = function () {
  69042. this._panningModel = "equalpower";
  69043. this._switchPanningModel();
  69044. };
  69045. Sound.prototype._switchPanningModel = function () {
  69046. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69047. this._soundPanner.panningModel = this._panningModel;
  69048. }
  69049. };
  69050. /**
  69051. * Connect this sound to a sound track audio node like gain...
  69052. * @param soundTrackAudioNode the sound track audio node to connect to
  69053. */
  69054. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  69055. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69056. if (this._isOutputConnected) {
  69057. this._outputAudioNode.disconnect();
  69058. }
  69059. this._outputAudioNode.connect(soundTrackAudioNode);
  69060. this._isOutputConnected = true;
  69061. }
  69062. };
  69063. /**
  69064. * Transform this sound into a directional source
  69065. * @param coneInnerAngle Size of the inner cone in degree
  69066. * @param coneOuterAngle Size of the outer cone in degree
  69067. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  69068. */
  69069. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  69070. if (coneOuterAngle < coneInnerAngle) {
  69071. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  69072. return;
  69073. }
  69074. this._coneInnerAngle = coneInnerAngle;
  69075. this._coneOuterAngle = coneOuterAngle;
  69076. this._coneOuterGain = coneOuterGain;
  69077. this._isDirectional = true;
  69078. if (this.isPlaying && this.loop) {
  69079. this.stop();
  69080. this.play();
  69081. }
  69082. };
  69083. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  69084. /**
  69085. * Gets or sets the inner angle for the directional cone.
  69086. */
  69087. get: function () {
  69088. return this._coneInnerAngle;
  69089. },
  69090. /**
  69091. * Gets or sets the inner angle for the directional cone.
  69092. */
  69093. set: function (value) {
  69094. if (value != this._coneInnerAngle) {
  69095. if (this._coneOuterAngle < value) {
  69096. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69097. return;
  69098. }
  69099. this._coneInnerAngle = value;
  69100. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69101. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69102. }
  69103. }
  69104. },
  69105. enumerable: true,
  69106. configurable: true
  69107. });
  69108. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  69109. /**
  69110. * Gets or sets the outer angle for the directional cone.
  69111. */
  69112. get: function () {
  69113. return this._coneOuterAngle;
  69114. },
  69115. /**
  69116. * Gets or sets the outer angle for the directional cone.
  69117. */
  69118. set: function (value) {
  69119. if (value != this._coneOuterAngle) {
  69120. if (value < this._coneInnerAngle) {
  69121. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69122. return;
  69123. }
  69124. this._coneOuterAngle = value;
  69125. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69126. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69127. }
  69128. }
  69129. },
  69130. enumerable: true,
  69131. configurable: true
  69132. });
  69133. /**
  69134. * Sets the position of the emitter if spatial sound is enabled
  69135. * @param newPosition Defines the new posisiton
  69136. */
  69137. Sound.prototype.setPosition = function (newPosition) {
  69138. this._position = newPosition;
  69139. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69140. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69141. }
  69142. };
  69143. /**
  69144. * Sets the local direction of the emitter if spatial sound is enabled
  69145. * @param newLocalDirection Defines the new local direction
  69146. */
  69147. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  69148. this._localDirection = newLocalDirection;
  69149. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  69150. this._updateDirection();
  69151. }
  69152. };
  69153. Sound.prototype._updateDirection = function () {
  69154. if (!this._connectedMesh || !this._soundPanner) {
  69155. return;
  69156. }
  69157. var mat = this._connectedMesh.getWorldMatrix();
  69158. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  69159. direction.normalize();
  69160. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  69161. };
  69162. /** @hidden */
  69163. Sound.prototype.updateDistanceFromListener = function () {
  69164. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  69165. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  69166. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  69167. }
  69168. };
  69169. /**
  69170. * Sets a new custom attenuation function for the sound.
  69171. * @param callback Defines the function used for the attenuation
  69172. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69173. */
  69174. Sound.prototype.setAttenuationFunction = function (callback) {
  69175. this._customAttenuationFunction = callback;
  69176. };
  69177. /**
  69178. * Play the sound
  69179. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  69180. * @param offset (optional) Start the sound setting it at a specific time
  69181. */
  69182. Sound.prototype.play = function (time, offset) {
  69183. var _this = this;
  69184. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  69185. try {
  69186. if (this._startOffset < 0) {
  69187. time = -this._startOffset;
  69188. this._startOffset = 0;
  69189. }
  69190. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69191. if (!this._soundSource || !this._streamingSource) {
  69192. if (this.spatialSound && this._soundPanner) {
  69193. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69194. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69195. }
  69196. if (this._isDirectional) {
  69197. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69198. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69199. this._soundPanner.coneOuterGain = this._coneOuterGain;
  69200. if (this._connectedMesh) {
  69201. this._updateDirection();
  69202. }
  69203. else {
  69204. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  69205. }
  69206. }
  69207. }
  69208. }
  69209. if (this._streaming) {
  69210. if (!this._streamingSource) {
  69211. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  69212. this._htmlAudioElement.onended = function () { _this._onended(); };
  69213. this._htmlAudioElement.playbackRate = this._playbackRate;
  69214. }
  69215. this._streamingSource.disconnect();
  69216. this._streamingSource.connect(this._inputAudioNode);
  69217. if (this._htmlAudioElement) {
  69218. // required to manage properly the new suspended default state of Chrome
  69219. // When the option 'streaming: true' is used, we need first to wait for
  69220. // the audio engine to be unlocked by a user gesture before trying to play
  69221. // an HTML Audio elememt
  69222. var tryToPlay = function () {
  69223. if (BABYLON.Engine.audioEngine.unlocked) {
  69224. var playPromise = _this._htmlAudioElement.play();
  69225. // In browsers that don’t yet support this functionality,
  69226. // playPromise won’t be defined.
  69227. if (playPromise !== undefined) {
  69228. playPromise.catch(function (error) {
  69229. // Automatic playback failed.
  69230. // Waiting for the audio engine to be unlocked by user click on unmute
  69231. BABYLON.Engine.audioEngine.lock();
  69232. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69233. });
  69234. }
  69235. }
  69236. else {
  69237. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69238. }
  69239. };
  69240. tryToPlay();
  69241. }
  69242. }
  69243. else {
  69244. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  69245. this._soundSource.buffer = this._audioBuffer;
  69246. this._soundSource.connect(this._inputAudioNode);
  69247. this._soundSource.loop = this.loop;
  69248. this._soundSource.playbackRate.value = this._playbackRate;
  69249. this._soundSource.onended = function () { _this._onended(); };
  69250. if (this._soundSource.buffer) {
  69251. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  69252. }
  69253. }
  69254. this._startTime = startTime;
  69255. this.isPlaying = true;
  69256. this.isPaused = false;
  69257. }
  69258. catch (ex) {
  69259. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  69260. }
  69261. }
  69262. };
  69263. Sound.prototype._onended = function () {
  69264. this.isPlaying = false;
  69265. if (this.onended) {
  69266. this.onended();
  69267. }
  69268. this.onEndedObservable.notifyObservers(this);
  69269. };
  69270. /**
  69271. * Stop the sound
  69272. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  69273. */
  69274. Sound.prototype.stop = function (time) {
  69275. if (this.isPlaying) {
  69276. if (this._streaming) {
  69277. if (this._htmlAudioElement) {
  69278. this._htmlAudioElement.pause();
  69279. // Test needed for Firefox or it will generate an Invalid State Error
  69280. if (this._htmlAudioElement.currentTime > 0) {
  69281. this._htmlAudioElement.currentTime = 0;
  69282. }
  69283. }
  69284. else {
  69285. this._streamingSource.disconnect();
  69286. }
  69287. }
  69288. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  69289. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69290. this._soundSource.stop(stopTime);
  69291. this._soundSource.onended = function () { };
  69292. if (!this.isPaused) {
  69293. this._startOffset = 0;
  69294. }
  69295. }
  69296. this.isPlaying = false;
  69297. }
  69298. };
  69299. /**
  69300. * Put the sound in pause
  69301. */
  69302. Sound.prototype.pause = function () {
  69303. if (this.isPlaying) {
  69304. this.isPaused = true;
  69305. if (this._streaming) {
  69306. if (this._htmlAudioElement) {
  69307. this._htmlAudioElement.pause();
  69308. }
  69309. else {
  69310. this._streamingSource.disconnect();
  69311. }
  69312. }
  69313. else if (BABYLON.Engine.audioEngine.audioContext) {
  69314. this.stop(0);
  69315. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  69316. }
  69317. }
  69318. };
  69319. /**
  69320. * Sets a dedicated volume for this sounds
  69321. * @param newVolume Define the new volume of the sound
  69322. * @param time Define in how long the sound should be at this value
  69323. */
  69324. Sound.prototype.setVolume = function (newVolume, time) {
  69325. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  69326. if (time && BABYLON.Engine.audioEngine.audioContext) {
  69327. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  69328. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  69329. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  69330. }
  69331. else {
  69332. this._soundGain.gain.value = newVolume;
  69333. }
  69334. }
  69335. this._volume = newVolume;
  69336. };
  69337. /**
  69338. * Set the sound play back rate
  69339. * @param newPlaybackRate Define the playback rate the sound should be played at
  69340. */
  69341. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  69342. this._playbackRate = newPlaybackRate;
  69343. if (this.isPlaying) {
  69344. if (this._streaming && this._htmlAudioElement) {
  69345. this._htmlAudioElement.playbackRate = this._playbackRate;
  69346. }
  69347. else if (this._soundSource) {
  69348. this._soundSource.playbackRate.value = this._playbackRate;
  69349. }
  69350. }
  69351. };
  69352. /**
  69353. * Gets the volume of the sound.
  69354. * @returns the volume of the sound
  69355. */
  69356. Sound.prototype.getVolume = function () {
  69357. return this._volume;
  69358. };
  69359. /**
  69360. * Attach the sound to a dedicated mesh
  69361. * @param meshToConnectTo The mesh to connect the sound with
  69362. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  69363. */
  69364. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  69365. var _this = this;
  69366. if (this._connectedMesh && this._registerFunc) {
  69367. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69368. this._registerFunc = null;
  69369. }
  69370. this._connectedMesh = meshToConnectTo;
  69371. if (!this.spatialSound) {
  69372. this.spatialSound = true;
  69373. this._createSpatialParameters();
  69374. if (this.isPlaying && this.loop) {
  69375. this.stop();
  69376. this.play();
  69377. }
  69378. }
  69379. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  69380. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  69381. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  69382. };
  69383. /**
  69384. * Detach the sound from the previously attached mesh
  69385. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  69386. */
  69387. Sound.prototype.detachFromMesh = function () {
  69388. if (this._connectedMesh && this._registerFunc) {
  69389. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69390. this._registerFunc = null;
  69391. this._connectedMesh = null;
  69392. }
  69393. };
  69394. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  69395. if (!node.getBoundingInfo) {
  69396. return;
  69397. }
  69398. var mesh = node;
  69399. if (this._positionInEmitterSpace) {
  69400. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  69401. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  69402. }
  69403. else {
  69404. var boundingInfo = mesh.getBoundingInfo();
  69405. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  69406. }
  69407. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  69408. this._updateDirection();
  69409. }
  69410. };
  69411. /**
  69412. * Clone the current sound in the scene.
  69413. * @returns the new sound clone
  69414. */
  69415. Sound.prototype.clone = function () {
  69416. var _this = this;
  69417. if (!this._streaming) {
  69418. var setBufferAndRun = function () {
  69419. if (_this._isReadyToPlay) {
  69420. clonedSound._audioBuffer = _this.getAudioBuffer();
  69421. clonedSound._isReadyToPlay = true;
  69422. if (clonedSound.autoplay) {
  69423. clonedSound.play();
  69424. }
  69425. }
  69426. else {
  69427. window.setTimeout(setBufferAndRun, 300);
  69428. }
  69429. };
  69430. var currentOptions = {
  69431. autoplay: this.autoplay, loop: this.loop,
  69432. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  69433. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  69434. refDistance: this.refDistance, distanceModel: this.distanceModel
  69435. };
  69436. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  69437. if (this.useCustomAttenuation) {
  69438. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  69439. }
  69440. clonedSound.setPosition(this._position);
  69441. clonedSound.setPlaybackRate(this._playbackRate);
  69442. setBufferAndRun();
  69443. return clonedSound;
  69444. }
  69445. // Can't clone a streaming sound
  69446. else {
  69447. return null;
  69448. }
  69449. };
  69450. /**
  69451. * Gets the current underlying audio buffer containing the data
  69452. * @returns the audio buffer
  69453. */
  69454. Sound.prototype.getAudioBuffer = function () {
  69455. return this._audioBuffer;
  69456. };
  69457. /**
  69458. * Serializes the Sound in a JSON representation
  69459. * @returns the JSON representation of the sound
  69460. */
  69461. Sound.prototype.serialize = function () {
  69462. var serializationObject = {
  69463. name: this.name,
  69464. url: this.name,
  69465. autoplay: this.autoplay,
  69466. loop: this.loop,
  69467. volume: this._volume,
  69468. spatialSound: this.spatialSound,
  69469. maxDistance: this.maxDistance,
  69470. rolloffFactor: this.rolloffFactor,
  69471. refDistance: this.refDistance,
  69472. distanceModel: this.distanceModel,
  69473. playbackRate: this._playbackRate,
  69474. panningModel: this._panningModel,
  69475. soundTrackId: this.soundTrackId
  69476. };
  69477. if (this.spatialSound) {
  69478. if (this._connectedMesh)
  69479. serializationObject.connectedMeshId = this._connectedMesh.id;
  69480. serializationObject.position = this._position.asArray();
  69481. serializationObject.refDistance = this.refDistance;
  69482. serializationObject.distanceModel = this.distanceModel;
  69483. serializationObject.isDirectional = this._isDirectional;
  69484. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  69485. serializationObject.coneInnerAngle = this._coneInnerAngle;
  69486. serializationObject.coneOuterAngle = this._coneOuterAngle;
  69487. serializationObject.coneOuterGain = this._coneOuterGain;
  69488. }
  69489. return serializationObject;
  69490. };
  69491. /**
  69492. * Parse a JSON representation of a sound to innstantiate in a given scene
  69493. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  69494. * @param scene Define the scene the new parsed sound should be created in
  69495. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  69496. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  69497. * @returns the newly parsed sound
  69498. */
  69499. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  69500. var soundName = parsedSound.name;
  69501. var soundUrl;
  69502. if (parsedSound.url) {
  69503. soundUrl = rootUrl + parsedSound.url;
  69504. }
  69505. else {
  69506. soundUrl = rootUrl + soundName;
  69507. }
  69508. var options = {
  69509. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  69510. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  69511. rolloffFactor: parsedSound.rolloffFactor,
  69512. refDistance: parsedSound.refDistance,
  69513. distanceModel: parsedSound.distanceModel,
  69514. playbackRate: parsedSound.playbackRate
  69515. };
  69516. var newSound;
  69517. if (!sourceSound) {
  69518. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  69519. scene._addPendingData(newSound);
  69520. }
  69521. else {
  69522. var setBufferAndRun = function () {
  69523. if (sourceSound._isReadyToPlay) {
  69524. newSound._audioBuffer = sourceSound.getAudioBuffer();
  69525. newSound._isReadyToPlay = true;
  69526. if (newSound.autoplay) {
  69527. newSound.play();
  69528. }
  69529. }
  69530. else {
  69531. window.setTimeout(setBufferAndRun, 300);
  69532. }
  69533. };
  69534. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  69535. setBufferAndRun();
  69536. }
  69537. if (parsedSound.position) {
  69538. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  69539. newSound.setPosition(soundPosition);
  69540. }
  69541. if (parsedSound.isDirectional) {
  69542. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  69543. if (parsedSound.localDirectionToMesh) {
  69544. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  69545. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  69546. }
  69547. }
  69548. if (parsedSound.connectedMeshId) {
  69549. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  69550. if (connectedMesh) {
  69551. newSound.attachToMesh(connectedMesh);
  69552. }
  69553. }
  69554. return newSound;
  69555. };
  69556. return Sound;
  69557. }());
  69558. BABYLON.Sound = Sound;
  69559. })(BABYLON || (BABYLON = {}));
  69560. //# sourceMappingURL=babylon.sound.js.map
  69561. var BABYLON;
  69562. (function (BABYLON) {
  69563. /**
  69564. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  69565. * It will be also used in a future release to apply effects on a specific track.
  69566. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  69567. */
  69568. var SoundTrack = /** @class */ (function () {
  69569. /**
  69570. * Creates a new sound track.
  69571. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  69572. * @param scene Define the scene the sound track belongs to
  69573. * @param options
  69574. */
  69575. function SoundTrack(scene, options) {
  69576. if (options === void 0) { options = {}; }
  69577. /**
  69578. * The unique identifier of the sound track in the scene.
  69579. */
  69580. this.id = -1;
  69581. this._isMainTrack = false;
  69582. this._isInitialized = false;
  69583. this._scene = scene;
  69584. this.soundCollection = new Array();
  69585. this._options = options;
  69586. if (!this._isMainTrack && this._scene.soundTracks) {
  69587. this._scene.soundTracks.push(this);
  69588. this.id = this._scene.soundTracks.length - 1;
  69589. }
  69590. }
  69591. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  69592. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69593. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  69594. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  69595. if (this._options) {
  69596. if (this._options.volume) {
  69597. this._outputAudioNode.gain.value = this._options.volume;
  69598. }
  69599. if (this._options.mainTrack) {
  69600. this._isMainTrack = this._options.mainTrack;
  69601. }
  69602. }
  69603. this._isInitialized = true;
  69604. }
  69605. };
  69606. /**
  69607. * Release the sound track and its associated resources
  69608. */
  69609. SoundTrack.prototype.dispose = function () {
  69610. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  69611. if (this._connectedAnalyser) {
  69612. this._connectedAnalyser.stopDebugCanvas();
  69613. }
  69614. while (this.soundCollection.length) {
  69615. this.soundCollection[0].dispose();
  69616. }
  69617. if (this._outputAudioNode) {
  69618. this._outputAudioNode.disconnect();
  69619. }
  69620. this._outputAudioNode = null;
  69621. }
  69622. };
  69623. /**
  69624. * Adds a sound to this sound track
  69625. * @param sound define the cound to add
  69626. * @ignoreNaming
  69627. */
  69628. SoundTrack.prototype.AddSound = function (sound) {
  69629. if (!this._isInitialized) {
  69630. this._initializeSoundTrackAudioGraph();
  69631. }
  69632. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69633. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  69634. }
  69635. if (sound.soundTrackId) {
  69636. if (sound.soundTrackId === -1) {
  69637. this._scene.mainSoundTrack.RemoveSound(sound);
  69638. }
  69639. else if (this._scene.soundTracks) {
  69640. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  69641. }
  69642. }
  69643. this.soundCollection.push(sound);
  69644. sound.soundTrackId = this.id;
  69645. };
  69646. /**
  69647. * Removes a sound to this sound track
  69648. * @param sound define the cound to remove
  69649. * @ignoreNaming
  69650. */
  69651. SoundTrack.prototype.RemoveSound = function (sound) {
  69652. var index = this.soundCollection.indexOf(sound);
  69653. if (index !== -1) {
  69654. this.soundCollection.splice(index, 1);
  69655. }
  69656. };
  69657. /**
  69658. * Set a global volume for the full sound track.
  69659. * @param newVolume Define the new volume of the sound track
  69660. */
  69661. SoundTrack.prototype.setVolume = function (newVolume) {
  69662. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69663. this._outputAudioNode.gain.value = newVolume;
  69664. }
  69665. };
  69666. /**
  69667. * Switch the panning model to HRTF:
  69668. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69669. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69670. */
  69671. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  69672. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69673. for (var i = 0; i < this.soundCollection.length; i++) {
  69674. this.soundCollection[i].switchPanningModelToHRTF();
  69675. }
  69676. }
  69677. };
  69678. /**
  69679. * Switch the panning model to Equal Power:
  69680. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69681. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69682. */
  69683. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  69684. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69685. for (var i = 0; i < this.soundCollection.length; i++) {
  69686. this.soundCollection[i].switchPanningModelToEqualPower();
  69687. }
  69688. }
  69689. };
  69690. /**
  69691. * Connect the sound track to an audio analyser allowing some amazing
  69692. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69693. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69694. * @param analyser The analyser to connect to the engine
  69695. */
  69696. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  69697. if (this._connectedAnalyser) {
  69698. this._connectedAnalyser.stopDebugCanvas();
  69699. }
  69700. this._connectedAnalyser = analyser;
  69701. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69702. this._outputAudioNode.disconnect();
  69703. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  69704. }
  69705. };
  69706. return SoundTrack;
  69707. }());
  69708. BABYLON.SoundTrack = SoundTrack;
  69709. })(BABYLON || (BABYLON = {}));
  69710. //# sourceMappingURL=babylon.soundtrack.js.map
  69711. var BABYLON;
  69712. (function (BABYLON) {
  69713. /**
  69714. * Class used to work with sound analyzer using fast fourier transform (FFT)
  69715. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69716. */
  69717. var Analyser = /** @class */ (function () {
  69718. /**
  69719. * Creates a new analyser
  69720. * @param scene defines hosting scene
  69721. */
  69722. function Analyser(scene) {
  69723. /**
  69724. * Gets or sets the smoothing
  69725. * @ignorenaming
  69726. */
  69727. this.SMOOTHING = 0.75;
  69728. /**
  69729. * Gets or sets the FFT table size
  69730. * @ignorenaming
  69731. */
  69732. this.FFT_SIZE = 512;
  69733. /**
  69734. * Gets or sets the bar graph amplitude
  69735. * @ignorenaming
  69736. */
  69737. this.BARGRAPHAMPLITUDE = 256;
  69738. /**
  69739. * Gets or sets the position of the debug canvas
  69740. * @ignorenaming
  69741. */
  69742. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  69743. /**
  69744. * Gets or sets the debug canvas size
  69745. * @ignorenaming
  69746. */
  69747. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  69748. this._scene = scene;
  69749. this._audioEngine = BABYLON.Engine.audioEngine;
  69750. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  69751. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  69752. this._webAudioAnalyser.minDecibels = -140;
  69753. this._webAudioAnalyser.maxDecibels = 0;
  69754. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  69755. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  69756. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  69757. }
  69758. }
  69759. /**
  69760. * Get the number of data values you will have to play with for the visualization
  69761. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  69762. * @returns a number
  69763. */
  69764. Analyser.prototype.getFrequencyBinCount = function () {
  69765. if (this._audioEngine.canUseWebAudio) {
  69766. return this._webAudioAnalyser.frequencyBinCount;
  69767. }
  69768. else {
  69769. return 0;
  69770. }
  69771. };
  69772. /**
  69773. * Gets the current frequency data as a byte array
  69774. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  69775. * @returns a Uint8Array
  69776. */
  69777. Analyser.prototype.getByteFrequencyData = function () {
  69778. if (this._audioEngine.canUseWebAudio) {
  69779. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69780. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69781. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  69782. }
  69783. return this._byteFreqs;
  69784. };
  69785. /**
  69786. * Gets the current waveform as a byte array
  69787. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  69788. * @returns a Uint8Array
  69789. */
  69790. Analyser.prototype.getByteTimeDomainData = function () {
  69791. if (this._audioEngine.canUseWebAudio) {
  69792. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69793. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69794. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  69795. }
  69796. return this._byteTime;
  69797. };
  69798. /**
  69799. * Gets the current frequency data as a float array
  69800. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  69801. * @returns a Float32Array
  69802. */
  69803. Analyser.prototype.getFloatFrequencyData = function () {
  69804. if (this._audioEngine.canUseWebAudio) {
  69805. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69806. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69807. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  69808. }
  69809. return this._floatFreqs;
  69810. };
  69811. /**
  69812. * Renders the debug canvas
  69813. */
  69814. Analyser.prototype.drawDebugCanvas = function () {
  69815. var _this = this;
  69816. if (this._audioEngine.canUseWebAudio) {
  69817. if (!this._debugCanvas) {
  69818. this._debugCanvas = document.createElement("canvas");
  69819. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  69820. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  69821. this._debugCanvas.style.position = "absolute";
  69822. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  69823. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  69824. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  69825. document.body.appendChild(this._debugCanvas);
  69826. this._registerFunc = function () {
  69827. _this.drawDebugCanvas();
  69828. };
  69829. this._scene.registerBeforeRender(this._registerFunc);
  69830. }
  69831. if (this._registerFunc && this._debugCanvasContext) {
  69832. var workingArray = this.getByteFrequencyData();
  69833. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  69834. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  69835. // Draw the frequency domain chart.
  69836. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  69837. var value = workingArray[i];
  69838. var percent = value / this.BARGRAPHAMPLITUDE;
  69839. var height = this.DEBUGCANVASSIZE.height * percent;
  69840. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  69841. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  69842. var hue = i / this.getFrequencyBinCount() * 360;
  69843. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  69844. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  69845. }
  69846. }
  69847. }
  69848. };
  69849. /**
  69850. * Stops rendering the debug canvas and removes it
  69851. */
  69852. Analyser.prototype.stopDebugCanvas = function () {
  69853. if (this._debugCanvas) {
  69854. if (this._registerFunc) {
  69855. this._scene.unregisterBeforeRender(this._registerFunc);
  69856. this._registerFunc = null;
  69857. }
  69858. document.body.removeChild(this._debugCanvas);
  69859. this._debugCanvas = null;
  69860. this._debugCanvasContext = null;
  69861. }
  69862. };
  69863. /**
  69864. * Connects two audio nodes
  69865. * @param inputAudioNode defines first node to connect
  69866. * @param outputAudioNode defines second node to connect
  69867. */
  69868. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  69869. if (this._audioEngine.canUseWebAudio) {
  69870. inputAudioNode.connect(this._webAudioAnalyser);
  69871. this._webAudioAnalyser.connect(outputAudioNode);
  69872. }
  69873. };
  69874. /**
  69875. * Releases all associated resources
  69876. */
  69877. Analyser.prototype.dispose = function () {
  69878. if (this._audioEngine.canUseWebAudio) {
  69879. this._webAudioAnalyser.disconnect();
  69880. }
  69881. };
  69882. return Analyser;
  69883. }());
  69884. BABYLON.Analyser = Analyser;
  69885. })(BABYLON || (BABYLON = {}));
  69886. //# sourceMappingURL=babylon.analyser.js.map
  69887. var BABYLON;
  69888. (function (BABYLON) {
  69889. /**
  69890. * Wraps one or more Sound objects and selects one with random weight for playback.
  69891. */
  69892. var WeightedSound = /** @class */ (function () {
  69893. /**
  69894. * Creates a new WeightedSound from the list of sounds given.
  69895. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  69896. * @param sounds Array of Sounds that will be selected from.
  69897. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  69898. */
  69899. function WeightedSound(loop, sounds, weights) {
  69900. var _this = this;
  69901. /** When true a Sound will be selected and played when the current playing Sound completes. */
  69902. this.loop = false;
  69903. this._coneInnerAngle = 360;
  69904. this._coneOuterAngle = 360;
  69905. this._volume = 1;
  69906. /** A Sound is currently playing. */
  69907. this.isPlaying = false;
  69908. /** A Sound is currently paused. */
  69909. this.isPaused = false;
  69910. this._sounds = [];
  69911. this._weights = [];
  69912. if (sounds.length !== weights.length) {
  69913. throw new Error('Sounds length does not equal weights length');
  69914. }
  69915. this.loop = loop;
  69916. this._weights = weights;
  69917. // Normalize the weights
  69918. var weightSum = 0;
  69919. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  69920. var weight = weights_1[_i];
  69921. weightSum += weight;
  69922. }
  69923. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  69924. for (var i = 0; i < this._weights.length; i++) {
  69925. this._weights[i] *= invWeightSum;
  69926. }
  69927. this._sounds = sounds;
  69928. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  69929. var sound = _b[_a];
  69930. sound.onEndedObservable.add(function () { _this._onended(); });
  69931. }
  69932. }
  69933. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  69934. /**
  69935. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  69936. */
  69937. get: function () {
  69938. return this._coneInnerAngle;
  69939. },
  69940. /**
  69941. * The size of cone in degress for a directional sound in which there will be no attenuation.
  69942. */
  69943. set: function (value) {
  69944. if (value !== this._coneInnerAngle) {
  69945. if (this._coneOuterAngle < value) {
  69946. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69947. return;
  69948. }
  69949. this._coneInnerAngle = value;
  69950. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69951. var sound = _a[_i];
  69952. sound.directionalConeInnerAngle = value;
  69953. }
  69954. }
  69955. },
  69956. enumerable: true,
  69957. configurable: true
  69958. });
  69959. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  69960. /**
  69961. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  69962. * Listener angles between innerAngle and outerAngle will falloff linearly.
  69963. */
  69964. get: function () {
  69965. return this._coneOuterAngle;
  69966. },
  69967. /**
  69968. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  69969. * Listener angles between innerAngle and outerAngle will falloff linearly.
  69970. */
  69971. set: function (value) {
  69972. if (value !== this._coneOuterAngle) {
  69973. if (value < this._coneInnerAngle) {
  69974. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69975. return;
  69976. }
  69977. this._coneOuterAngle = value;
  69978. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69979. var sound = _a[_i];
  69980. sound.directionalConeOuterAngle = value;
  69981. }
  69982. }
  69983. },
  69984. enumerable: true,
  69985. configurable: true
  69986. });
  69987. Object.defineProperty(WeightedSound.prototype, "volume", {
  69988. /**
  69989. * Playback volume.
  69990. */
  69991. get: function () {
  69992. return this._volume;
  69993. },
  69994. /**
  69995. * Playback volume.
  69996. */
  69997. set: function (value) {
  69998. if (value !== this._volume) {
  69999. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70000. var sound = _a[_i];
  70001. sound.setVolume(value);
  70002. }
  70003. }
  70004. },
  70005. enumerable: true,
  70006. configurable: true
  70007. });
  70008. WeightedSound.prototype._onended = function () {
  70009. if (this._currentIndex !== undefined) {
  70010. this._sounds[this._currentIndex].autoplay = false;
  70011. }
  70012. if (this.loop && this.isPlaying) {
  70013. this.play();
  70014. }
  70015. else {
  70016. this.isPlaying = false;
  70017. }
  70018. };
  70019. /**
  70020. * Suspend playback
  70021. */
  70022. WeightedSound.prototype.pause = function () {
  70023. this.isPaused = true;
  70024. if (this._currentIndex !== undefined) {
  70025. this._sounds[this._currentIndex].pause();
  70026. }
  70027. };
  70028. /**
  70029. * Stop playback
  70030. */
  70031. WeightedSound.prototype.stop = function () {
  70032. this.isPlaying = false;
  70033. if (this._currentIndex !== undefined) {
  70034. this._sounds[this._currentIndex].stop();
  70035. }
  70036. };
  70037. /**
  70038. * Start playback.
  70039. * @param startOffset Position the clip head at a specific time in seconds.
  70040. */
  70041. WeightedSound.prototype.play = function (startOffset) {
  70042. if (!this.isPaused) {
  70043. this.stop();
  70044. var randomValue = Math.random();
  70045. var total = 0;
  70046. for (var i = 0; i < this._weights.length; i++) {
  70047. total += this._weights[i];
  70048. if (randomValue <= total) {
  70049. this._currentIndex = i;
  70050. break;
  70051. }
  70052. }
  70053. }
  70054. var sound = this._sounds[this._currentIndex];
  70055. if (sound.isReady()) {
  70056. sound.play(0, this.isPaused ? undefined : startOffset);
  70057. }
  70058. else {
  70059. sound.autoplay = true;
  70060. }
  70061. this.isPlaying = true;
  70062. this.isPaused = false;
  70063. };
  70064. return WeightedSound;
  70065. }());
  70066. BABYLON.WeightedSound = WeightedSound;
  70067. })(BABYLON || (BABYLON = {}));
  70068. //# sourceMappingURL=babylon.weightedsound.js.map
  70069. var BABYLON;
  70070. (function (BABYLON) {
  70071. // Adds the parser to the scene parsers.
  70072. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  70073. // TODO: add sound
  70074. var loadedSounds = [];
  70075. var loadedSound;
  70076. container.sounds = container.sounds || [];
  70077. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70078. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70079. var parsedSound = parsedData.sounds[index];
  70080. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70081. if (!parsedSound.url)
  70082. parsedSound.url = parsedSound.name;
  70083. if (!loadedSounds[parsedSound.url]) {
  70084. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70085. loadedSounds[parsedSound.url] = loadedSound;
  70086. container.sounds.push(loadedSound);
  70087. }
  70088. else {
  70089. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70090. }
  70091. }
  70092. else {
  70093. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70094. }
  70095. }
  70096. }
  70097. loadedSounds = [];
  70098. });
  70099. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  70100. get: function () {
  70101. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70102. if (!compo) {
  70103. compo = new AudioSceneComponent(this);
  70104. this._addComponent(compo);
  70105. }
  70106. if (!this._mainSoundTrack) {
  70107. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  70108. }
  70109. return this._mainSoundTrack;
  70110. },
  70111. enumerable: true,
  70112. configurable: true
  70113. });
  70114. BABYLON.Scene.prototype.getSoundByName = function (name) {
  70115. var index;
  70116. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  70117. if (this.mainSoundTrack.soundCollection[index].name === name) {
  70118. return this.mainSoundTrack.soundCollection[index];
  70119. }
  70120. }
  70121. if (this.soundTracks) {
  70122. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  70123. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  70124. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  70125. return this.soundTracks[sdIndex].soundCollection[index];
  70126. }
  70127. }
  70128. }
  70129. }
  70130. return null;
  70131. };
  70132. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  70133. get: function () {
  70134. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70135. if (!compo) {
  70136. compo = new AudioSceneComponent(this);
  70137. this._addComponent(compo);
  70138. }
  70139. return compo.audioEnabled;
  70140. },
  70141. set: function (value) {
  70142. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70143. if (!compo) {
  70144. compo = new AudioSceneComponent(this);
  70145. this._addComponent(compo);
  70146. }
  70147. if (value) {
  70148. compo.enableAudio();
  70149. }
  70150. else {
  70151. compo.disableAudio();
  70152. }
  70153. },
  70154. enumerable: true,
  70155. configurable: true
  70156. });
  70157. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  70158. get: function () {
  70159. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70160. if (!compo) {
  70161. compo = new AudioSceneComponent(this);
  70162. this._addComponent(compo);
  70163. }
  70164. return compo.headphone;
  70165. },
  70166. set: function (value) {
  70167. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70168. if (!compo) {
  70169. compo = new AudioSceneComponent(this);
  70170. this._addComponent(compo);
  70171. }
  70172. if (value) {
  70173. compo.switchAudioModeForHeadphones();
  70174. }
  70175. else {
  70176. compo.switchAudioModeForNormalSpeakers();
  70177. }
  70178. },
  70179. enumerable: true,
  70180. configurable: true
  70181. });
  70182. /**
  70183. * Defines the sound scene component responsible to manage any sounds
  70184. * in a given scene.
  70185. */
  70186. var AudioSceneComponent = /** @class */ (function () {
  70187. /**
  70188. * Creates a new instance of the component for the given scene
  70189. * @param scene Defines the scene to register the component in
  70190. */
  70191. function AudioSceneComponent(scene) {
  70192. /**
  70193. * The component name helpfull to identify the component in the list of scene components.
  70194. */
  70195. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  70196. this._audioEnabled = true;
  70197. this._headphone = false;
  70198. this.scene = scene;
  70199. scene.soundTracks = new Array();
  70200. scene.sounds = new Array();
  70201. }
  70202. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  70203. /**
  70204. * Gets whether audio is enabled or not.
  70205. * Please use related enable/disable method to switch state.
  70206. */
  70207. get: function () {
  70208. return this._audioEnabled;
  70209. },
  70210. enumerable: true,
  70211. configurable: true
  70212. });
  70213. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  70214. /**
  70215. * Gets whether audio is outputing to headphone or not.
  70216. * Please use the according Switch methods to change output.
  70217. */
  70218. get: function () {
  70219. return this._headphone;
  70220. },
  70221. enumerable: true,
  70222. configurable: true
  70223. });
  70224. /**
  70225. * Registers the component in a given scene
  70226. */
  70227. AudioSceneComponent.prototype.register = function () {
  70228. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  70229. };
  70230. /**
  70231. * Rebuilds the elements related to this component in case of
  70232. * context lost for instance.
  70233. */
  70234. AudioSceneComponent.prototype.rebuild = function () {
  70235. // Nothing to do here. (Not rendering related)
  70236. };
  70237. /**
  70238. * Serializes the component data to the specified json object
  70239. * @param serializationObject The object to serialize to
  70240. */
  70241. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  70242. serializationObject.sounds = [];
  70243. if (this.scene.soundTracks) {
  70244. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  70245. var soundtrack = this.scene.soundTracks[index];
  70246. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70247. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70248. }
  70249. }
  70250. }
  70251. };
  70252. /**
  70253. * Adds all the element from the container to the scene
  70254. * @param container the container holding the elements
  70255. */
  70256. AudioSceneComponent.prototype.addFromContainer = function (container) {
  70257. var _this = this;
  70258. if (!container.sounds) {
  70259. return;
  70260. }
  70261. container.sounds.forEach(function (sound) {
  70262. sound.play();
  70263. sound.autoplay = true;
  70264. _this.scene.mainSoundTrack.AddSound(sound);
  70265. });
  70266. };
  70267. /**
  70268. * Removes all the elements in the container from the scene
  70269. * @param container contains the elements to remove
  70270. */
  70271. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  70272. var _this = this;
  70273. if (!container.sounds) {
  70274. return;
  70275. }
  70276. container.sounds.forEach(function (sound) {
  70277. sound.stop();
  70278. sound.autoplay = false;
  70279. _this.scene.mainSoundTrack.RemoveSound(sound);
  70280. });
  70281. };
  70282. /**
  70283. * Disposes the component and the associated ressources.
  70284. */
  70285. AudioSceneComponent.prototype.dispose = function () {
  70286. var scene = this.scene;
  70287. if (scene._mainSoundTrack) {
  70288. scene.mainSoundTrack.dispose();
  70289. }
  70290. if (scene.soundTracks) {
  70291. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  70292. scene.soundTracks[scIndex].dispose();
  70293. }
  70294. }
  70295. };
  70296. /**
  70297. * Disables audio in the associated scene.
  70298. */
  70299. AudioSceneComponent.prototype.disableAudio = function () {
  70300. var scene = this.scene;
  70301. this._audioEnabled = false;
  70302. var i;
  70303. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70304. scene.mainSoundTrack.soundCollection[i].pause();
  70305. }
  70306. if (scene.soundTracks) {
  70307. for (i = 0; i < scene.soundTracks.length; i++) {
  70308. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70309. scene.soundTracks[i].soundCollection[j].pause();
  70310. }
  70311. }
  70312. }
  70313. };
  70314. /**
  70315. * Enables audio in the associated scene.
  70316. */
  70317. AudioSceneComponent.prototype.enableAudio = function () {
  70318. var scene = this.scene;
  70319. this._audioEnabled = true;
  70320. var i;
  70321. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70322. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  70323. scene.mainSoundTrack.soundCollection[i].play();
  70324. }
  70325. }
  70326. if (scene.soundTracks) {
  70327. for (i = 0; i < scene.soundTracks.length; i++) {
  70328. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70329. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  70330. scene.soundTracks[i].soundCollection[j].play();
  70331. }
  70332. }
  70333. }
  70334. }
  70335. };
  70336. /**
  70337. * Switch audio to headphone output.
  70338. */
  70339. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  70340. var scene = this.scene;
  70341. this._headphone = true;
  70342. scene.mainSoundTrack.switchPanningModelToHRTF();
  70343. if (scene.soundTracks) {
  70344. for (var i = 0; i < scene.soundTracks.length; i++) {
  70345. scene.soundTracks[i].switchPanningModelToHRTF();
  70346. }
  70347. }
  70348. };
  70349. /**
  70350. * Switch audio to normal speakers.
  70351. */
  70352. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  70353. var scene = this.scene;
  70354. this._headphone = false;
  70355. scene.mainSoundTrack.switchPanningModelToEqualPower();
  70356. if (scene.soundTracks) {
  70357. for (var i = 0; i < scene.soundTracks.length; i++) {
  70358. scene.soundTracks[i].switchPanningModelToEqualPower();
  70359. }
  70360. }
  70361. };
  70362. AudioSceneComponent.prototype._afterRender = function () {
  70363. var scene = this.scene;
  70364. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  70365. return;
  70366. }
  70367. var listeningCamera;
  70368. var audioEngine = BABYLON.Engine.audioEngine;
  70369. if (scene.activeCameras.length > 0) {
  70370. listeningCamera = scene.activeCameras[0];
  70371. }
  70372. else {
  70373. listeningCamera = scene.activeCamera;
  70374. }
  70375. if (listeningCamera && audioEngine.audioContext) {
  70376. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  70377. // for VR cameras
  70378. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  70379. listeningCamera = listeningCamera.rigCameras[0];
  70380. }
  70381. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  70382. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  70383. cameraDirection.normalize();
  70384. // To avoid some errors on GearVR
  70385. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  70386. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  70387. }
  70388. var i;
  70389. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70390. var sound = scene.mainSoundTrack.soundCollection[i];
  70391. if (sound.useCustomAttenuation) {
  70392. sound.updateDistanceFromListener();
  70393. }
  70394. }
  70395. if (scene.soundTracks) {
  70396. for (i = 0; i < scene.soundTracks.length; i++) {
  70397. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70398. sound = scene.soundTracks[i].soundCollection[j];
  70399. if (sound.useCustomAttenuation) {
  70400. sound.updateDistanceFromListener();
  70401. }
  70402. }
  70403. }
  70404. }
  70405. }
  70406. };
  70407. return AudioSceneComponent;
  70408. }());
  70409. BABYLON.AudioSceneComponent = AudioSceneComponent;
  70410. })(BABYLON || (BABYLON = {}));
  70411. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  70412. var BABYLON;
  70413. (function (BABYLON) {
  70414. /**
  70415. * This defines an action helpful to play a defined sound on a triggered action.
  70416. */
  70417. var PlaySoundAction = /** @class */ (function (_super) {
  70418. __extends(PlaySoundAction, _super);
  70419. /**
  70420. * Instantiate the action
  70421. * @param triggerOptions defines the trigger options
  70422. * @param sound defines the sound to play
  70423. * @param condition defines the trigger related conditions
  70424. */
  70425. function PlaySoundAction(triggerOptions, sound, condition) {
  70426. var _this = _super.call(this, triggerOptions, condition) || this;
  70427. _this._sound = sound;
  70428. return _this;
  70429. }
  70430. /** @hidden */
  70431. PlaySoundAction.prototype._prepare = function () {
  70432. };
  70433. /**
  70434. * Execute the action and play the sound.
  70435. */
  70436. PlaySoundAction.prototype.execute = function () {
  70437. if (this._sound !== undefined)
  70438. this._sound.play();
  70439. };
  70440. /**
  70441. * Serializes the actions and its related information.
  70442. * @param parent defines the object to serialize in
  70443. * @returns the serialized object
  70444. */
  70445. PlaySoundAction.prototype.serialize = function (parent) {
  70446. return _super.prototype._serialize.call(this, {
  70447. name: "PlaySoundAction",
  70448. properties: [{ name: "sound", value: this._sound.name }]
  70449. }, parent);
  70450. };
  70451. return PlaySoundAction;
  70452. }(BABYLON.Action));
  70453. BABYLON.PlaySoundAction = PlaySoundAction;
  70454. /**
  70455. * This defines an action helpful to stop a defined sound on a triggered action.
  70456. */
  70457. var StopSoundAction = /** @class */ (function (_super) {
  70458. __extends(StopSoundAction, _super);
  70459. /**
  70460. * Instantiate the action
  70461. * @param triggerOptions defines the trigger options
  70462. * @param sound defines the sound to stop
  70463. * @param condition defines the trigger related conditions
  70464. */
  70465. function StopSoundAction(triggerOptions, sound, condition) {
  70466. var _this = _super.call(this, triggerOptions, condition) || this;
  70467. _this._sound = sound;
  70468. return _this;
  70469. }
  70470. /** @hidden */
  70471. StopSoundAction.prototype._prepare = function () {
  70472. };
  70473. /**
  70474. * Execute the action and stop the sound.
  70475. */
  70476. StopSoundAction.prototype.execute = function () {
  70477. if (this._sound !== undefined)
  70478. this._sound.stop();
  70479. };
  70480. /**
  70481. * Serializes the actions and its related information.
  70482. * @param parent defines the object to serialize in
  70483. * @returns the serialized object
  70484. */
  70485. StopSoundAction.prototype.serialize = function (parent) {
  70486. return _super.prototype._serialize.call(this, {
  70487. name: "StopSoundAction",
  70488. properties: [{ name: "sound", value: this._sound.name }]
  70489. }, parent);
  70490. };
  70491. return StopSoundAction;
  70492. }(BABYLON.Action));
  70493. BABYLON.StopSoundAction = StopSoundAction;
  70494. })(BABYLON || (BABYLON = {}));
  70495. //# sourceMappingURL=babylon.directAudioActions.js.map
  70496. var BABYLON;
  70497. (function (BABYLON) {
  70498. /**
  70499. * Class for creating a cube texture
  70500. */
  70501. var CubeTexture = /** @class */ (function (_super) {
  70502. __extends(CubeTexture, _super);
  70503. /**
  70504. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  70505. * as prefiltered data.
  70506. * @param rootUrl defines the url of the texture or the root name of the six images
  70507. * @param scene defines the scene the texture is attached to
  70508. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  70509. * @param noMipmap defines if mipmaps should be created or not
  70510. * @param files defines the six files to load for the different faces
  70511. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  70512. * @param onError defines a callback triggered in case of error during load
  70513. * @param format defines the internal format to use for the texture once loaded
  70514. * @param prefiltered defines whether or not the texture is created from prefiltered data
  70515. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  70516. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  70517. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  70518. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  70519. * @return the cube texture
  70520. */
  70521. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  70522. if (extensions === void 0) { extensions = null; }
  70523. if (noMipmap === void 0) { noMipmap = false; }
  70524. if (files === void 0) { files = null; }
  70525. if (onLoad === void 0) { onLoad = null; }
  70526. if (onError === void 0) { onError = null; }
  70527. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70528. if (prefiltered === void 0) { prefiltered = false; }
  70529. if (forcedExtension === void 0) { forcedExtension = null; }
  70530. if (createPolynomials === void 0) { createPolynomials = false; }
  70531. if (lodScale === void 0) { lodScale = 0.8; }
  70532. if (lodOffset === void 0) { lodOffset = 0; }
  70533. var _this = _super.call(this, scene) || this;
  70534. /**
  70535. * Gets or sets the center of the bounding box associated with the cube texture.
  70536. * It must define where the camera used to render the texture was set
  70537. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  70538. */
  70539. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70540. _this._rotationY = 0;
  70541. /** @hidden */
  70542. _this._prefiltered = false;
  70543. _this.name = rootUrl;
  70544. _this.url = rootUrl;
  70545. _this._noMipmap = noMipmap;
  70546. _this.hasAlpha = false;
  70547. _this._format = format;
  70548. _this.isCube = true;
  70549. _this._textureMatrix = BABYLON.Matrix.Identity();
  70550. _this._createPolynomials = createPolynomials;
  70551. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  70552. if (!rootUrl && !files) {
  70553. return _this;
  70554. }
  70555. var lastDot = rootUrl.lastIndexOf(".");
  70556. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  70557. var isDDS = (extension === ".dds");
  70558. var isEnv = (extension === ".env");
  70559. if (isEnv) {
  70560. _this.gammaSpace = false;
  70561. _this._prefiltered = false;
  70562. }
  70563. else {
  70564. _this._prefiltered = prefiltered;
  70565. if (prefiltered) {
  70566. _this.gammaSpace = false;
  70567. }
  70568. }
  70569. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  70570. if (!files) {
  70571. if (!isEnv && !isDDS && !extensions) {
  70572. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  70573. }
  70574. files = [];
  70575. if (extensions) {
  70576. for (var index = 0; index < extensions.length; index++) {
  70577. files.push(rootUrl + extensions[index]);
  70578. }
  70579. }
  70580. }
  70581. _this._files = files;
  70582. if (!_this._texture) {
  70583. if (!scene.useDelayedTextureLoading) {
  70584. if (prefiltered) {
  70585. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  70586. }
  70587. else {
  70588. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  70589. }
  70590. }
  70591. else {
  70592. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  70593. }
  70594. }
  70595. else if (onLoad) {
  70596. if (_this._texture.isReady) {
  70597. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  70598. }
  70599. else {
  70600. _this._texture.onLoadedObservable.add(onLoad);
  70601. }
  70602. }
  70603. return _this;
  70604. }
  70605. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  70606. /**
  70607. * Returns the bounding box size
  70608. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  70609. */
  70610. get: function () {
  70611. return this._boundingBoxSize;
  70612. },
  70613. /**
  70614. * Gets or sets the size of the bounding box associated with the cube texture
  70615. * When defined, the cubemap will switch to local mode
  70616. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  70617. * @example https://www.babylonjs-playground.com/#RNASML
  70618. */
  70619. set: function (value) {
  70620. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  70621. return;
  70622. }
  70623. this._boundingBoxSize = value;
  70624. var scene = this.getScene();
  70625. if (scene) {
  70626. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  70627. }
  70628. },
  70629. enumerable: true,
  70630. configurable: true
  70631. });
  70632. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  70633. /**
  70634. * Gets texture matrix rotation angle around Y axis radians.
  70635. */
  70636. get: function () {
  70637. return this._rotationY;
  70638. },
  70639. /**
  70640. * Sets texture matrix rotation angle around Y axis in radians.
  70641. */
  70642. set: function (value) {
  70643. this._rotationY = value;
  70644. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  70645. },
  70646. enumerable: true,
  70647. configurable: true
  70648. });
  70649. /**
  70650. * Creates a cube texture from an array of image urls
  70651. * @param files defines an array of image urls
  70652. * @param scene defines the hosting scene
  70653. * @param noMipmap specifies if mip maps are not used
  70654. * @returns a cube texture
  70655. */
  70656. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  70657. var rootUrlKey = "";
  70658. files.forEach(function (url) { return rootUrlKey += url; });
  70659. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  70660. };
  70661. /**
  70662. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  70663. * @param url defines the url of the prefiltered texture
  70664. * @param scene defines the scene the texture is attached to
  70665. * @param forcedExtension defines the extension of the file if different from the url
  70666. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  70667. * @return the prefiltered texture
  70668. */
  70669. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  70670. if (forcedExtension === void 0) { forcedExtension = null; }
  70671. if (createPolynomials === void 0) { createPolynomials = true; }
  70672. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  70673. };
  70674. /**
  70675. * Delays loading of the cube texture
  70676. */
  70677. CubeTexture.prototype.delayLoad = function () {
  70678. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  70679. return;
  70680. }
  70681. var scene = this.getScene();
  70682. if (!scene) {
  70683. return;
  70684. }
  70685. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  70686. this._texture = this._getFromCache(this.url, this._noMipmap);
  70687. if (!this._texture) {
  70688. if (this._prefiltered) {
  70689. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  70690. }
  70691. else {
  70692. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  70693. }
  70694. }
  70695. };
  70696. /**
  70697. * Returns the reflection texture matrix
  70698. * @returns the reflection texture matrix
  70699. */
  70700. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  70701. return this._textureMatrix;
  70702. };
  70703. /**
  70704. * Sets the reflection texture matrix
  70705. * @param value Reflection texture matrix
  70706. */
  70707. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  70708. this._textureMatrix = value;
  70709. };
  70710. /**
  70711. * Parses text to create a cube texture
  70712. * @param parsedTexture define the serialized text to read from
  70713. * @param scene defines the hosting scene
  70714. * @param rootUrl defines the root url of the cube texture
  70715. * @returns a cube texture
  70716. */
  70717. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  70718. var texture = BABYLON.SerializationHelper.Parse(function () {
  70719. var prefiltered = false;
  70720. if (parsedTexture.prefiltered) {
  70721. prefiltered = parsedTexture.prefiltered;
  70722. }
  70723. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  70724. }, parsedTexture, scene);
  70725. // Local Cubemaps
  70726. if (parsedTexture.boundingBoxPosition) {
  70727. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  70728. }
  70729. if (parsedTexture.boundingBoxSize) {
  70730. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  70731. }
  70732. // Animations
  70733. if (parsedTexture.animations) {
  70734. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  70735. var parsedAnimation = parsedTexture.animations[animationIndex];
  70736. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  70737. }
  70738. }
  70739. return texture;
  70740. };
  70741. /**
  70742. * Makes a clone, or deep copy, of the cube texture
  70743. * @returns a new cube texture
  70744. */
  70745. CubeTexture.prototype.clone = function () {
  70746. var _this = this;
  70747. return BABYLON.SerializationHelper.Clone(function () {
  70748. var scene = _this.getScene();
  70749. if (!scene) {
  70750. return _this;
  70751. }
  70752. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  70753. }, this);
  70754. };
  70755. __decorate([
  70756. BABYLON.serialize("rotationY")
  70757. ], CubeTexture.prototype, "rotationY", null);
  70758. return CubeTexture;
  70759. }(BABYLON.BaseTexture));
  70760. BABYLON.CubeTexture = CubeTexture;
  70761. })(BABYLON || (BABYLON = {}));
  70762. //# sourceMappingURL=babylon.cubeTexture.js.map
  70763. var BABYLON;
  70764. (function (BABYLON) {
  70765. /**
  70766. * Raw cube texture where the raw buffers are passed in
  70767. */
  70768. var RawCubeTexture = /** @class */ (function (_super) {
  70769. __extends(RawCubeTexture, _super);
  70770. /**
  70771. * Creates a cube texture where the raw buffers are passed in.
  70772. * @param scene defines the scene the texture is attached to
  70773. * @param data defines the array of data to use to create each face
  70774. * @param size defines the size of the textures
  70775. * @param format defines the format of the data
  70776. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  70777. * @param generateMipMaps defines if the engine should generate the mip levels
  70778. * @param invertY defines if data must be stored with Y axis inverted
  70779. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  70780. * @param compression defines the compression used (null by default)
  70781. */
  70782. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  70783. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70784. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70785. if (generateMipMaps === void 0) { generateMipMaps = false; }
  70786. if (invertY === void 0) { invertY = false; }
  70787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70788. if (compression === void 0) { compression = null; }
  70789. var _this = _super.call(this, "", scene) || this;
  70790. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  70791. return _this;
  70792. }
  70793. /**
  70794. * Updates the raw cube texture.
  70795. * @param data defines the data to store
  70796. * @param format defines the data format
  70797. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  70798. * @param invertY defines if data must be stored with Y axis inverted
  70799. * @param compression defines the compression used (null by default)
  70800. * @param level defines which level of the texture to update
  70801. */
  70802. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  70803. if (compression === void 0) { compression = null; }
  70804. if (level === void 0) { level = 0; }
  70805. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  70806. };
  70807. /**
  70808. * Updates a raw cube texture with RGBD encoded data.
  70809. * @param data defines the array of data [mipmap][face] to use to create each face
  70810. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  70811. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  70812. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  70813. * @returns a promsie that resolves when the operation is complete
  70814. */
  70815. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  70816. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  70817. if (lodScale === void 0) { lodScale = 0.8; }
  70818. if (lodOffset === void 0) { lodOffset = 0; }
  70819. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  70820. };
  70821. /**
  70822. * Clones the raw cube texture.
  70823. * @return a new cube texture
  70824. */
  70825. RawCubeTexture.prototype.clone = function () {
  70826. var _this = this;
  70827. return BABYLON.SerializationHelper.Clone(function () {
  70828. var scene = _this.getScene();
  70829. var internalTexture = _this._texture;
  70830. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  70831. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  70832. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  70833. }
  70834. return texture;
  70835. }, this);
  70836. };
  70837. /** @hidden */
  70838. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  70839. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  70840. internalTexture._bufferViewArrayArray = data;
  70841. internalTexture._lodGenerationScale = lodScale;
  70842. internalTexture._lodGenerationOffset = lodOffset;
  70843. internalTexture._sphericalPolynomial = sphericalPolynomial;
  70844. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  70845. internalTexture.isReady = true;
  70846. });
  70847. };
  70848. return RawCubeTexture;
  70849. }(BABYLON.CubeTexture));
  70850. BABYLON.RawCubeTexture = RawCubeTexture;
  70851. })(BABYLON || (BABYLON = {}));
  70852. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  70853. var BABYLON;
  70854. (function (BABYLON) {
  70855. var RenderTargetTexture = /** @class */ (function (_super) {
  70856. __extends(RenderTargetTexture, _super);
  70857. /**
  70858. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  70859. * or used a shadow, depth texture...
  70860. * @param name The friendly name of the texture
  70861. * @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)
  70862. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  70863. * @param generateMipMaps True if mip maps need to be generated after render.
  70864. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  70865. * @param type The type of the buffer in the RTT (int, half float, float...)
  70866. * @param isCube True if a cube texture needs to be created
  70867. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  70868. * @param generateDepthBuffer True to generate a depth buffer
  70869. * @param generateStencilBuffer True to generate a stencil buffer
  70870. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  70871. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  70872. */
  70873. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  70874. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  70875. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70876. if (isCube === void 0) { isCube = false; }
  70877. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70878. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70879. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  70880. if (isMulti === void 0) { isMulti = false; }
  70881. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70882. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70883. _this.isCube = isCube;
  70884. _this.renderParticles = true;
  70885. _this.renderSprites = false;
  70886. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  70887. _this.ignoreCameraViewport = false;
  70888. // Events
  70889. /**
  70890. * An event triggered when the texture is unbind.
  70891. */
  70892. _this.onBeforeBindObservable = new BABYLON.Observable();
  70893. /**
  70894. * An event triggered when the texture is unbind.
  70895. */
  70896. _this.onAfterUnbindObservable = new BABYLON.Observable();
  70897. /**
  70898. * An event triggered before rendering the texture
  70899. */
  70900. _this.onBeforeRenderObservable = new BABYLON.Observable();
  70901. /**
  70902. * An event triggered after rendering the texture
  70903. */
  70904. _this.onAfterRenderObservable = new BABYLON.Observable();
  70905. /**
  70906. * An event triggered after the texture clear
  70907. */
  70908. _this.onClearObservable = new BABYLON.Observable();
  70909. _this._currentRefreshId = -1;
  70910. _this._refreshRate = 1;
  70911. _this._samples = 1;
  70912. /**
  70913. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  70914. * It must define where the camera used to render the texture is set
  70915. */
  70916. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70917. scene = _this.getScene();
  70918. if (!scene) {
  70919. return _this;
  70920. }
  70921. _this.renderList = new Array();
  70922. _this._engine = scene.getEngine();
  70923. _this.name = name;
  70924. _this.isRenderTarget = true;
  70925. _this._initialSizeParameter = size;
  70926. _this._processSizeParameter(size);
  70927. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  70928. });
  70929. _this._generateMipMaps = generateMipMaps ? true : false;
  70930. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  70931. // Rendering groups
  70932. _this._renderingManager = new BABYLON.RenderingManager(scene);
  70933. _this._renderingManager._useSceneAutoClearSetup = true;
  70934. if (isMulti) {
  70935. return _this;
  70936. }
  70937. _this._renderTargetOptions = {
  70938. generateMipMaps: generateMipMaps,
  70939. type: type,
  70940. format: format,
  70941. samplingMode: samplingMode,
  70942. generateDepthBuffer: generateDepthBuffer,
  70943. generateStencilBuffer: generateStencilBuffer
  70944. };
  70945. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  70946. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70947. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70948. }
  70949. if (isCube) {
  70950. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  70951. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  70952. _this._textureMatrix = BABYLON.Matrix.Identity();
  70953. }
  70954. else {
  70955. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  70956. }
  70957. return _this;
  70958. }
  70959. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  70960. get: function () {
  70961. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  70962. },
  70963. enumerable: true,
  70964. configurable: true
  70965. });
  70966. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  70967. get: function () {
  70968. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  70969. },
  70970. enumerable: true,
  70971. configurable: true
  70972. });
  70973. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  70974. get: function () {
  70975. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  70976. },
  70977. enumerable: true,
  70978. configurable: true
  70979. });
  70980. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  70981. /**
  70982. * Use this list to define the list of mesh you want to render.
  70983. */
  70984. get: function () {
  70985. return this._renderList;
  70986. },
  70987. set: function (value) {
  70988. this._renderList = value;
  70989. if (this._renderList) {
  70990. this._hookArray(this._renderList);
  70991. }
  70992. },
  70993. enumerable: true,
  70994. configurable: true
  70995. });
  70996. RenderTargetTexture.prototype._hookArray = function (array) {
  70997. var _this = this;
  70998. var oldPush = array.push;
  70999. array.push = function () {
  71000. var items = [];
  71001. for (var _i = 0; _i < arguments.length; _i++) {
  71002. items[_i] = arguments[_i];
  71003. }
  71004. var wasEmpty = array.length === 0;
  71005. var result = oldPush.apply(array, items);
  71006. if (wasEmpty) {
  71007. _this.getScene().meshes.forEach(function (mesh) {
  71008. mesh._markSubMeshesAsLightDirty();
  71009. });
  71010. }
  71011. return result;
  71012. };
  71013. var oldSplice = array.splice;
  71014. array.splice = function (index, deleteCount) {
  71015. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71016. if (array.length === 0) {
  71017. _this.getScene().meshes.forEach(function (mesh) {
  71018. mesh._markSubMeshesAsLightDirty();
  71019. });
  71020. }
  71021. return deleted;
  71022. };
  71023. };
  71024. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  71025. set: function (callback) {
  71026. if (this._onAfterUnbindObserver) {
  71027. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  71028. }
  71029. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  71030. },
  71031. enumerable: true,
  71032. configurable: true
  71033. });
  71034. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  71035. set: function (callback) {
  71036. if (this._onBeforeRenderObserver) {
  71037. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71038. }
  71039. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71040. },
  71041. enumerable: true,
  71042. configurable: true
  71043. });
  71044. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  71045. set: function (callback) {
  71046. if (this._onAfterRenderObserver) {
  71047. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71048. }
  71049. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71050. },
  71051. enumerable: true,
  71052. configurable: true
  71053. });
  71054. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  71055. set: function (callback) {
  71056. if (this._onClearObserver) {
  71057. this.onClearObservable.remove(this._onClearObserver);
  71058. }
  71059. this._onClearObserver = this.onClearObservable.add(callback);
  71060. },
  71061. enumerable: true,
  71062. configurable: true
  71063. });
  71064. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  71065. get: function () {
  71066. return this._renderTargetOptions;
  71067. },
  71068. enumerable: true,
  71069. configurable: true
  71070. });
  71071. RenderTargetTexture.prototype._onRatioRescale = function () {
  71072. if (this._sizeRatio) {
  71073. this.resize(this._initialSizeParameter);
  71074. }
  71075. };
  71076. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  71077. get: function () {
  71078. return this._boundingBoxSize;
  71079. },
  71080. /**
  71081. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  71082. * When defined, the cubemap will switch to local mode
  71083. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71084. * @example https://www.babylonjs-playground.com/#RNASML
  71085. */
  71086. set: function (value) {
  71087. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71088. return;
  71089. }
  71090. this._boundingBoxSize = value;
  71091. var scene = this.getScene();
  71092. if (scene) {
  71093. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71094. }
  71095. },
  71096. enumerable: true,
  71097. configurable: true
  71098. });
  71099. /**
  71100. * Creates a depth stencil texture.
  71101. * This is only available in WebGL 2 or with the depth texture extension available.
  71102. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  71103. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  71104. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  71105. */
  71106. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  71107. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  71108. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  71109. if (generateStencil === void 0) { generateStencil = false; }
  71110. if (!this.getScene()) {
  71111. return;
  71112. }
  71113. var engine = this.getScene().getEngine();
  71114. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  71115. bilinearFiltering: bilinearFiltering,
  71116. comparisonFunction: comparisonFunction,
  71117. generateStencil: generateStencil,
  71118. isCube: this.isCube
  71119. });
  71120. engine.setFrameBufferDepthStencilTexture(this);
  71121. };
  71122. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  71123. if (size.ratio) {
  71124. this._sizeRatio = size.ratio;
  71125. this._size = {
  71126. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  71127. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  71128. };
  71129. }
  71130. else {
  71131. this._size = size;
  71132. }
  71133. };
  71134. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  71135. get: function () {
  71136. return this._samples;
  71137. },
  71138. set: function (value) {
  71139. if (this._samples === value) {
  71140. return;
  71141. }
  71142. var scene = this.getScene();
  71143. if (!scene) {
  71144. return;
  71145. }
  71146. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  71147. },
  71148. enumerable: true,
  71149. configurable: true
  71150. });
  71151. /**
  71152. * Resets the refresh counter of the texture and start bak from scratch.
  71153. * Could be usefull to regenerate the texture if it is setup to render only once.
  71154. */
  71155. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  71156. this._currentRefreshId = -1;
  71157. };
  71158. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  71159. /**
  71160. * Define the refresh rate of the texture or the rendering frequency.
  71161. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71162. */
  71163. get: function () {
  71164. return this._refreshRate;
  71165. },
  71166. set: function (value) {
  71167. this._refreshRate = value;
  71168. this.resetRefreshCounter();
  71169. },
  71170. enumerable: true,
  71171. configurable: true
  71172. });
  71173. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  71174. if (!this._postProcessManager) {
  71175. var scene = this.getScene();
  71176. if (!scene) {
  71177. return;
  71178. }
  71179. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  71180. this._postProcesses = new Array();
  71181. }
  71182. this._postProcesses.push(postProcess);
  71183. this._postProcesses[0].autoClear = false;
  71184. };
  71185. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  71186. if (!this._postProcesses) {
  71187. return;
  71188. }
  71189. if (dispose) {
  71190. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  71191. var postProcess = _a[_i];
  71192. postProcess.dispose();
  71193. }
  71194. }
  71195. this._postProcesses = [];
  71196. };
  71197. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  71198. if (!this._postProcesses) {
  71199. return;
  71200. }
  71201. var index = this._postProcesses.indexOf(postProcess);
  71202. if (index === -1) {
  71203. return;
  71204. }
  71205. this._postProcesses.splice(index, 1);
  71206. if (this._postProcesses.length > 0) {
  71207. this._postProcesses[0].autoClear = false;
  71208. }
  71209. };
  71210. /** @hidden */
  71211. RenderTargetTexture.prototype._shouldRender = function () {
  71212. if (this._currentRefreshId === -1) { // At least render once
  71213. this._currentRefreshId = 1;
  71214. return true;
  71215. }
  71216. if (this.refreshRate === this._currentRefreshId) {
  71217. this._currentRefreshId = 1;
  71218. return true;
  71219. }
  71220. this._currentRefreshId++;
  71221. return false;
  71222. };
  71223. RenderTargetTexture.prototype.getRenderSize = function () {
  71224. if (this._size.width) {
  71225. return this._size.width;
  71226. }
  71227. return this._size;
  71228. };
  71229. RenderTargetTexture.prototype.getRenderWidth = function () {
  71230. if (this._size.width) {
  71231. return this._size.width;
  71232. }
  71233. return this._size;
  71234. };
  71235. RenderTargetTexture.prototype.getRenderHeight = function () {
  71236. if (this._size.width) {
  71237. return this._size.height;
  71238. }
  71239. return this._size;
  71240. };
  71241. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  71242. get: function () {
  71243. return true;
  71244. },
  71245. enumerable: true,
  71246. configurable: true
  71247. });
  71248. RenderTargetTexture.prototype.scale = function (ratio) {
  71249. var newSize = this.getRenderSize() * ratio;
  71250. this.resize(newSize);
  71251. };
  71252. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  71253. if (this.isCube) {
  71254. return this._textureMatrix;
  71255. }
  71256. return _super.prototype.getReflectionTextureMatrix.call(this);
  71257. };
  71258. RenderTargetTexture.prototype.resize = function (size) {
  71259. this.releaseInternalTexture();
  71260. var scene = this.getScene();
  71261. if (!scene) {
  71262. return;
  71263. }
  71264. this._processSizeParameter(size);
  71265. if (this.isCube) {
  71266. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  71267. }
  71268. else {
  71269. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  71270. }
  71271. };
  71272. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  71273. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  71274. if (dumpForDebug === void 0) { dumpForDebug = false; }
  71275. var scene = this.getScene();
  71276. if (!scene) {
  71277. return;
  71278. }
  71279. var engine = scene.getEngine();
  71280. if (this.useCameraPostProcesses !== undefined) {
  71281. useCameraPostProcess = this.useCameraPostProcesses;
  71282. }
  71283. if (this._waitingRenderList) {
  71284. this.renderList = [];
  71285. for (var index = 0; index < this._waitingRenderList.length; index++) {
  71286. var id = this._waitingRenderList[index];
  71287. var mesh_1 = scene.getMeshByID(id);
  71288. if (mesh_1) {
  71289. this.renderList.push(mesh_1);
  71290. }
  71291. }
  71292. delete this._waitingRenderList;
  71293. }
  71294. // Is predicate defined?
  71295. if (this.renderListPredicate) {
  71296. if (this.renderList) {
  71297. this.renderList.splice(0); // Clear previous renderList
  71298. }
  71299. else {
  71300. this.renderList = [];
  71301. }
  71302. var scene = this.getScene();
  71303. if (!scene) {
  71304. return;
  71305. }
  71306. var sceneMeshes = scene.meshes;
  71307. for (var index = 0; index < sceneMeshes.length; index++) {
  71308. var mesh = sceneMeshes[index];
  71309. if (this.renderListPredicate(mesh)) {
  71310. this.renderList.push(mesh);
  71311. }
  71312. }
  71313. }
  71314. this.onBeforeBindObservable.notifyObservers(this);
  71315. // Set custom projection.
  71316. // Needs to be before binding to prevent changing the aspect ratio.
  71317. var camera;
  71318. if (this.activeCamera) {
  71319. camera = this.activeCamera;
  71320. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  71321. if (this.activeCamera !== scene.activeCamera) {
  71322. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  71323. }
  71324. }
  71325. else {
  71326. camera = scene.activeCamera;
  71327. if (camera) {
  71328. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  71329. }
  71330. }
  71331. // Prepare renderingManager
  71332. this._renderingManager.reset();
  71333. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  71334. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  71335. var sceneRenderId = scene.getRenderId();
  71336. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  71337. var mesh = currentRenderList[meshIndex];
  71338. if (mesh) {
  71339. if (!mesh.isReady(this.refreshRate === 0)) {
  71340. this.resetRefreshCounter();
  71341. continue;
  71342. }
  71343. mesh._preActivateForIntermediateRendering(sceneRenderId);
  71344. var isMasked = void 0;
  71345. if (!this.renderList && camera) {
  71346. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  71347. }
  71348. else {
  71349. isMasked = false;
  71350. }
  71351. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  71352. mesh._activate(sceneRenderId);
  71353. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  71354. var subMesh = mesh.subMeshes[subIndex];
  71355. scene._activeIndices.addCount(subMesh.indexCount, false);
  71356. this._renderingManager.dispatch(subMesh, mesh);
  71357. }
  71358. }
  71359. }
  71360. }
  71361. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  71362. var particleSystem = scene.particleSystems[particleIndex];
  71363. var emitter = particleSystem.emitter;
  71364. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  71365. continue;
  71366. }
  71367. if (currentRenderList.indexOf(emitter) >= 0) {
  71368. this._renderingManager.dispatchParticles(particleSystem);
  71369. }
  71370. }
  71371. if (this.isCube) {
  71372. for (var face = 0; face < 6; face++) {
  71373. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  71374. scene.incrementRenderId();
  71375. scene.resetCachedMaterial();
  71376. }
  71377. }
  71378. else {
  71379. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  71380. }
  71381. this.onAfterUnbindObservable.notifyObservers(this);
  71382. if (scene.activeCamera) {
  71383. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  71384. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  71385. }
  71386. engine.setViewport(scene.activeCamera.viewport);
  71387. }
  71388. scene.resetCachedMaterial();
  71389. };
  71390. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  71391. var minimum = 128;
  71392. var x = renderDimension * scale;
  71393. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  71394. // Ensure we don't exceed the render dimension (while staying POT)
  71395. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  71396. };
  71397. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  71398. var _this = this;
  71399. if (!this._texture) {
  71400. return;
  71401. }
  71402. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  71403. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  71404. });
  71405. };
  71406. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  71407. var scene = this.getScene();
  71408. if (!scene) {
  71409. return;
  71410. }
  71411. var engine = scene.getEngine();
  71412. if (!this._texture) {
  71413. return;
  71414. }
  71415. // Bind
  71416. if (this._postProcessManager) {
  71417. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  71418. }
  71419. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  71420. if (this._texture) {
  71421. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  71422. }
  71423. }
  71424. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  71425. // Clear
  71426. if (this.onClearObservable.hasObservers()) {
  71427. this.onClearObservable.notifyObservers(engine);
  71428. }
  71429. else {
  71430. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  71431. }
  71432. if (!this._doNotChangeAspectRatio) {
  71433. scene.updateTransformMatrix(true);
  71434. }
  71435. // Render
  71436. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  71437. if (this._postProcessManager) {
  71438. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  71439. }
  71440. else if (useCameraPostProcess) {
  71441. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  71442. }
  71443. if (!this._doNotChangeAspectRatio) {
  71444. scene.updateTransformMatrix(true);
  71445. }
  71446. // Dump ?
  71447. if (dumpForDebug) {
  71448. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  71449. }
  71450. // Unbind
  71451. if (!this.isCube || faceIndex === 5) {
  71452. if (this.isCube) {
  71453. if (faceIndex === 5) {
  71454. engine.generateMipMapsForCubemap(this._texture);
  71455. }
  71456. }
  71457. this.unbindFrameBuffer(engine, faceIndex);
  71458. }
  71459. else {
  71460. this.onAfterRenderObservable.notifyObservers(faceIndex);
  71461. }
  71462. };
  71463. /**
  71464. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  71465. * This allowed control for front to back rendering or reversly depending of the special needs.
  71466. *
  71467. * @param renderingGroupId The rendering group id corresponding to its index
  71468. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  71469. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  71470. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  71471. */
  71472. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  71473. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  71474. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  71475. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  71476. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  71477. };
  71478. /**
  71479. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  71480. *
  71481. * @param renderingGroupId The rendering group id corresponding to its index
  71482. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  71483. */
  71484. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  71485. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  71486. this._renderingManager._useSceneAutoClearSetup = false;
  71487. };
  71488. RenderTargetTexture.prototype.clone = function () {
  71489. var textureSize = this.getSize();
  71490. 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);
  71491. // Base texture
  71492. newTexture.hasAlpha = this.hasAlpha;
  71493. newTexture.level = this.level;
  71494. // RenderTarget Texture
  71495. newTexture.coordinatesMode = this.coordinatesMode;
  71496. if (this.renderList) {
  71497. newTexture.renderList = this.renderList.slice(0);
  71498. }
  71499. return newTexture;
  71500. };
  71501. RenderTargetTexture.prototype.serialize = function () {
  71502. if (!this.name) {
  71503. return null;
  71504. }
  71505. var serializationObject = _super.prototype.serialize.call(this);
  71506. serializationObject.renderTargetSize = this.getRenderSize();
  71507. serializationObject.renderList = [];
  71508. if (this.renderList) {
  71509. for (var index = 0; index < this.renderList.length; index++) {
  71510. serializationObject.renderList.push(this.renderList[index].id);
  71511. }
  71512. }
  71513. return serializationObject;
  71514. };
  71515. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  71516. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  71517. var objBuffer = this.getInternalTexture();
  71518. var scene = this.getScene();
  71519. if (objBuffer && scene) {
  71520. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  71521. }
  71522. };
  71523. RenderTargetTexture.prototype.dispose = function () {
  71524. if (this._postProcessManager) {
  71525. this._postProcessManager.dispose();
  71526. this._postProcessManager = null;
  71527. }
  71528. this.clearPostProcesses(true);
  71529. if (this._resizeObserver) {
  71530. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  71531. this._resizeObserver = null;
  71532. }
  71533. this.renderList = null;
  71534. // Remove from custom render targets
  71535. var scene = this.getScene();
  71536. if (!scene) {
  71537. return;
  71538. }
  71539. var index = scene.customRenderTargets.indexOf(this);
  71540. if (index >= 0) {
  71541. scene.customRenderTargets.splice(index, 1);
  71542. }
  71543. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  71544. var camera = _a[_i];
  71545. index = camera.customRenderTargets.indexOf(this);
  71546. if (index >= 0) {
  71547. camera.customRenderTargets.splice(index, 1);
  71548. }
  71549. }
  71550. _super.prototype.dispose.call(this);
  71551. };
  71552. /** @hidden */
  71553. RenderTargetTexture.prototype._rebuild = function () {
  71554. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71555. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71556. }
  71557. if (this._postProcessManager) {
  71558. this._postProcessManager._rebuild();
  71559. }
  71560. };
  71561. /**
  71562. * Clear the info related to rendering groups preventing retention point in material dispose.
  71563. */
  71564. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  71565. if (this._renderingManager) {
  71566. this._renderingManager.freeRenderingGroups();
  71567. }
  71568. };
  71569. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  71570. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  71571. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  71572. return RenderTargetTexture;
  71573. }(BABYLON.Texture));
  71574. BABYLON.RenderTargetTexture = RenderTargetTexture;
  71575. })(BABYLON || (BABYLON = {}));
  71576. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  71577. var BABYLON;
  71578. (function (BABYLON) {
  71579. ;
  71580. /**
  71581. * A multi render target, like a render target provides the ability to render to a texture.
  71582. * Unlike the render target, it can render to several draw buffers in one draw.
  71583. * This is specially interesting in deferred rendering or for any effects requiring more than
  71584. * just one color from a single pass.
  71585. */
  71586. var MultiRenderTarget = /** @class */ (function (_super) {
  71587. __extends(MultiRenderTarget, _super);
  71588. /**
  71589. * Instantiate a new multi render target texture.
  71590. * A multi render target, like a render target provides the ability to render to a texture.
  71591. * Unlike the render target, it can render to several draw buffers in one draw.
  71592. * This is specially interesting in deferred rendering or for any effects requiring more than
  71593. * just one color from a single pass.
  71594. * @param name Define the name of the texture
  71595. * @param size Define the size of the buffers to render to
  71596. * @param count Define the number of target we are rendering into
  71597. * @param scene Define the scene the texture belongs to
  71598. * @param options Define the options used to create the multi render target
  71599. */
  71600. function MultiRenderTarget(name, size, count, scene, options) {
  71601. var _this = this;
  71602. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  71603. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  71604. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  71605. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  71606. _this._engine = scene.getEngine();
  71607. if (!_this.isSupported) {
  71608. _this.dispose();
  71609. return;
  71610. }
  71611. var types = [];
  71612. var samplingModes = [];
  71613. for (var i = 0; i < count; i++) {
  71614. if (options && options.types && options.types[i] !== undefined) {
  71615. types.push(options.types[i]);
  71616. }
  71617. else {
  71618. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71619. }
  71620. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  71621. samplingModes.push(options.samplingModes[i]);
  71622. }
  71623. else {
  71624. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71625. }
  71626. }
  71627. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  71628. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  71629. _this._size = size;
  71630. _this._multiRenderTargetOptions = {
  71631. samplingModes: samplingModes,
  71632. generateMipMaps: generateMipMaps,
  71633. generateDepthBuffer: generateDepthBuffer,
  71634. generateStencilBuffer: generateStencilBuffer,
  71635. generateDepthTexture: generateDepthTexture,
  71636. types: types,
  71637. textureCount: count
  71638. };
  71639. _this._createInternalTextures();
  71640. _this._createTextures();
  71641. return _this;
  71642. }
  71643. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  71644. /**
  71645. * Get if draw buffers are currently supported by the used hardware and browser.
  71646. */
  71647. get: function () {
  71648. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  71649. },
  71650. enumerable: true,
  71651. configurable: true
  71652. });
  71653. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  71654. /**
  71655. * Get the list of textures generated by the multi render target.
  71656. */
  71657. get: function () {
  71658. return this._textures;
  71659. },
  71660. enumerable: true,
  71661. configurable: true
  71662. });
  71663. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  71664. /**
  71665. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  71666. */
  71667. get: function () {
  71668. return this._textures[this._textures.length - 1];
  71669. },
  71670. enumerable: true,
  71671. configurable: true
  71672. });
  71673. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  71674. /**
  71675. * Set the wrapping mode on U of all the textures we are rendering to.
  71676. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  71677. */
  71678. set: function (wrap) {
  71679. if (this._textures) {
  71680. for (var i = 0; i < this._textures.length; i++) {
  71681. this._textures[i].wrapU = wrap;
  71682. }
  71683. }
  71684. },
  71685. enumerable: true,
  71686. configurable: true
  71687. });
  71688. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  71689. /**
  71690. * Set the wrapping mode on V of all the textures we are rendering to.
  71691. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  71692. */
  71693. set: function (wrap) {
  71694. if (this._textures) {
  71695. for (var i = 0; i < this._textures.length; i++) {
  71696. this._textures[i].wrapV = wrap;
  71697. }
  71698. }
  71699. },
  71700. enumerable: true,
  71701. configurable: true
  71702. });
  71703. /** @hidden */
  71704. MultiRenderTarget.prototype._rebuild = function () {
  71705. this.releaseInternalTextures();
  71706. this._createInternalTextures();
  71707. for (var i = 0; i < this._internalTextures.length; i++) {
  71708. var texture = this._textures[i];
  71709. texture._texture = this._internalTextures[i];
  71710. }
  71711. // Keeps references to frame buffer and stencil/depth buffer
  71712. this._texture = this._internalTextures[0];
  71713. };
  71714. MultiRenderTarget.prototype._createInternalTextures = function () {
  71715. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  71716. };
  71717. MultiRenderTarget.prototype._createTextures = function () {
  71718. this._textures = [];
  71719. for (var i = 0; i < this._internalTextures.length; i++) {
  71720. var texture = new BABYLON.Texture(null, this.getScene());
  71721. texture._texture = this._internalTextures[i];
  71722. this._textures.push(texture);
  71723. }
  71724. // Keeps references to frame buffer and stencil/depth buffer
  71725. this._texture = this._internalTextures[0];
  71726. };
  71727. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  71728. /**
  71729. * Define the number of samples used if MSAA is enabled.
  71730. */
  71731. get: function () {
  71732. return this._samples;
  71733. },
  71734. set: function (value) {
  71735. if (this._samples === value) {
  71736. return;
  71737. }
  71738. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  71739. },
  71740. enumerable: true,
  71741. configurable: true
  71742. });
  71743. /**
  71744. * Resize all the textures in the multi render target.
  71745. * Be carrefull as it will recreate all the data in the new texture.
  71746. * @param size Define the new size
  71747. */
  71748. MultiRenderTarget.prototype.resize = function (size) {
  71749. this.releaseInternalTextures();
  71750. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  71751. this._createInternalTextures();
  71752. };
  71753. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  71754. var _this = this;
  71755. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  71756. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  71757. });
  71758. };
  71759. /**
  71760. * Dispose the render targets and their associated resources
  71761. */
  71762. MultiRenderTarget.prototype.dispose = function () {
  71763. this.releaseInternalTextures();
  71764. _super.prototype.dispose.call(this);
  71765. };
  71766. /**
  71767. * Release all the underlying texture used as draw buffers.
  71768. */
  71769. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  71770. if (!this._internalTextures) {
  71771. return;
  71772. }
  71773. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  71774. if (this._internalTextures[i] !== undefined) {
  71775. this._internalTextures[i].dispose();
  71776. this._internalTextures.splice(i, 1);
  71777. }
  71778. }
  71779. };
  71780. return MultiRenderTarget;
  71781. }(BABYLON.RenderTargetTexture));
  71782. BABYLON.MultiRenderTarget = MultiRenderTarget;
  71783. })(BABYLON || (BABYLON = {}));
  71784. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  71785. var BABYLON;
  71786. (function (BABYLON) {
  71787. /**
  71788. * Mirror texture can be used to simulate the view from a mirror in a scene.
  71789. * It will dynamically be rendered every frame to adapt to the camera point of view.
  71790. * You can then easily use it as a reflectionTexture on a flat surface.
  71791. * In case the surface is not a plane, please consider relying on reflection probes.
  71792. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  71793. */
  71794. var MirrorTexture = /** @class */ (function (_super) {
  71795. __extends(MirrorTexture, _super);
  71796. /**
  71797. * Instantiates a Mirror Texture.
  71798. * Mirror texture can be used to simulate the view from a mirror in a scene.
  71799. * It will dynamically be rendered every frame to adapt to the camera point of view.
  71800. * You can then easily use it as a reflectionTexture on a flat surface.
  71801. * In case the surface is not a plane, please consider relying on reflection probes.
  71802. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  71803. * @param name
  71804. * @param size
  71805. * @param scene
  71806. * @param generateMipMaps
  71807. * @param type
  71808. * @param samplingMode
  71809. * @param generateDepthBuffer
  71810. */
  71811. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  71812. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71813. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71814. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71815. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  71816. _this.scene = scene;
  71817. /**
  71818. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  71819. * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.
  71820. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  71821. */
  71822. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  71823. _this._transformMatrix = BABYLON.Matrix.Zero();
  71824. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  71825. _this._adaptiveBlurKernel = 0;
  71826. _this._blurKernelX = 0;
  71827. _this._blurKernelY = 0;
  71828. _this._blurRatio = 1.0;
  71829. _this.ignoreCameraViewport = true;
  71830. _this._updateGammaSpace();
  71831. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  71832. _this._updateGammaSpace;
  71833. });
  71834. _this.onBeforeRenderObservable.add(function () {
  71835. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  71836. _this._savedViewMatrix = scene.getViewMatrix();
  71837. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  71838. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  71839. scene.clipPlane = _this.mirrorPlane;
  71840. scene.getEngine().cullBackFaces = false;
  71841. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  71842. });
  71843. _this.onAfterRenderObservable.add(function () {
  71844. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  71845. scene.getEngine().cullBackFaces = true;
  71846. scene._mirroredCameraPosition = null;
  71847. delete scene.clipPlane;
  71848. });
  71849. return _this;
  71850. }
  71851. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  71852. get: function () {
  71853. return this._blurRatio;
  71854. },
  71855. /**
  71856. * Define the blur ratio used to blur the reflection if needed.
  71857. */
  71858. set: function (value) {
  71859. if (this._blurRatio === value) {
  71860. return;
  71861. }
  71862. this._blurRatio = value;
  71863. this._preparePostProcesses();
  71864. },
  71865. enumerable: true,
  71866. configurable: true
  71867. });
  71868. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  71869. /**
  71870. * Define the adaptive blur kernel used to blur the reflection if needed.
  71871. * This will autocompute the closest best match for the `blurKernel`
  71872. */
  71873. set: function (value) {
  71874. this._adaptiveBlurKernel = value;
  71875. this._autoComputeBlurKernel();
  71876. },
  71877. enumerable: true,
  71878. configurable: true
  71879. });
  71880. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  71881. /**
  71882. * Define the blur kernel used to blur the reflection if needed.
  71883. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  71884. */
  71885. set: function (value) {
  71886. this.blurKernelX = value;
  71887. this.blurKernelY = value;
  71888. },
  71889. enumerable: true,
  71890. configurable: true
  71891. });
  71892. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  71893. get: function () {
  71894. return this._blurKernelX;
  71895. },
  71896. /**
  71897. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  71898. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  71899. */
  71900. set: function (value) {
  71901. if (this._blurKernelX === value) {
  71902. return;
  71903. }
  71904. this._blurKernelX = value;
  71905. this._preparePostProcesses();
  71906. },
  71907. enumerable: true,
  71908. configurable: true
  71909. });
  71910. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  71911. get: function () {
  71912. return this._blurKernelY;
  71913. },
  71914. /**
  71915. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  71916. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  71917. */
  71918. set: function (value) {
  71919. if (this._blurKernelY === value) {
  71920. return;
  71921. }
  71922. this._blurKernelY = value;
  71923. this._preparePostProcesses();
  71924. },
  71925. enumerable: true,
  71926. configurable: true
  71927. });
  71928. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  71929. var engine = this.getScene().getEngine();
  71930. var dw = this.getRenderWidth() / engine.getRenderWidth();
  71931. var dh = this.getRenderHeight() / engine.getRenderHeight();
  71932. this.blurKernelX = this._adaptiveBlurKernel * dw;
  71933. this.blurKernelY = this._adaptiveBlurKernel * dh;
  71934. };
  71935. MirrorTexture.prototype._onRatioRescale = function () {
  71936. if (this._sizeRatio) {
  71937. this.resize(this._initialSizeParameter);
  71938. if (!this._adaptiveBlurKernel) {
  71939. this._preparePostProcesses();
  71940. }
  71941. }
  71942. if (this._adaptiveBlurKernel) {
  71943. this._autoComputeBlurKernel();
  71944. }
  71945. };
  71946. MirrorTexture.prototype._updateGammaSpace = function () {
  71947. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  71948. };
  71949. MirrorTexture.prototype._preparePostProcesses = function () {
  71950. this.clearPostProcesses(true);
  71951. if (this._blurKernelX && this._blurKernelY) {
  71952. var engine = this.getScene().getEngine();
  71953. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71954. 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);
  71955. this._blurX.autoClear = false;
  71956. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  71957. this._blurX.inputTexture = this._texture;
  71958. }
  71959. else {
  71960. this._blurX.alwaysForcePOT = true;
  71961. }
  71962. 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);
  71963. this._blurY.autoClear = false;
  71964. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  71965. this.addPostProcess(this._blurX);
  71966. this.addPostProcess(this._blurY);
  71967. }
  71968. else {
  71969. if (this._blurY) {
  71970. this.removePostProcess(this._blurY);
  71971. this._blurY.dispose();
  71972. this._blurY = null;
  71973. }
  71974. if (this._blurX) {
  71975. this.removePostProcess(this._blurX);
  71976. this._blurX.dispose();
  71977. this._blurX = null;
  71978. }
  71979. }
  71980. };
  71981. /**
  71982. * Clone the mirror texture.
  71983. * @returns the cloned texture
  71984. */
  71985. MirrorTexture.prototype.clone = function () {
  71986. var scene = this.getScene();
  71987. if (!scene) {
  71988. return this;
  71989. }
  71990. var textureSize = this.getSize();
  71991. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  71992. // Base texture
  71993. newTexture.hasAlpha = this.hasAlpha;
  71994. newTexture.level = this.level;
  71995. // Mirror Texture
  71996. newTexture.mirrorPlane = this.mirrorPlane.clone();
  71997. if (this.renderList) {
  71998. newTexture.renderList = this.renderList.slice(0);
  71999. }
  72000. return newTexture;
  72001. };
  72002. /**
  72003. * Serialize the texture to a JSON representation you could use in Parse later on
  72004. * @returns the serialized JSON representation
  72005. */
  72006. MirrorTexture.prototype.serialize = function () {
  72007. if (!this.name) {
  72008. return null;
  72009. }
  72010. var serializationObject = _super.prototype.serialize.call(this);
  72011. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  72012. return serializationObject;
  72013. };
  72014. /**
  72015. * Dispose the texture and release its associated resources.
  72016. */
  72017. MirrorTexture.prototype.dispose = function () {
  72018. _super.prototype.dispose.call(this);
  72019. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  72020. };
  72021. return MirrorTexture;
  72022. }(BABYLON.RenderTargetTexture));
  72023. BABYLON.MirrorTexture = MirrorTexture;
  72024. })(BABYLON || (BABYLON = {}));
  72025. //# sourceMappingURL=babylon.mirrorTexture.js.map
  72026. var BABYLON;
  72027. (function (BABYLON) {
  72028. /**
  72029. * Creates a refraction texture used by refraction channel of the standard material.
  72030. * It is like a mirror but to see through a material.
  72031. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72032. */
  72033. var RefractionTexture = /** @class */ (function (_super) {
  72034. __extends(RefractionTexture, _super);
  72035. /**
  72036. * Creates a refraction texture used by refraction channel of the standard material.
  72037. * It is like a mirror but to see through a material.
  72038. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72039. * @param name Define the texture name
  72040. * @param size Define the size of the underlying texture
  72041. * @param scene Define the scene the refraction belongs to
  72042. * @param generateMipMaps Define if we need to generate mips level for the refraction
  72043. */
  72044. function RefractionTexture(name, size, scene, generateMipMaps) {
  72045. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  72046. /**
  72047. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  72048. * It is possible to directly set the refractionPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.
  72049. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72050. */
  72051. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  72052. /**
  72053. * Define how deep under the surface we should see.
  72054. */
  72055. _this.depth = 2.0;
  72056. _this.onBeforeRenderObservable.add(function () {
  72057. scene.clipPlane = _this.refractionPlane;
  72058. });
  72059. _this.onAfterRenderObservable.add(function () {
  72060. delete scene.clipPlane;
  72061. });
  72062. return _this;
  72063. }
  72064. /**
  72065. * Clone the refraction texture.
  72066. * @returns the cloned texture
  72067. */
  72068. RefractionTexture.prototype.clone = function () {
  72069. var scene = this.getScene();
  72070. if (!scene) {
  72071. return this;
  72072. }
  72073. var textureSize = this.getSize();
  72074. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  72075. // Base texture
  72076. newTexture.hasAlpha = this.hasAlpha;
  72077. newTexture.level = this.level;
  72078. // Refraction Texture
  72079. newTexture.refractionPlane = this.refractionPlane.clone();
  72080. if (this.renderList) {
  72081. newTexture.renderList = this.renderList.slice(0);
  72082. }
  72083. newTexture.depth = this.depth;
  72084. return newTexture;
  72085. };
  72086. /**
  72087. * Serialize the texture to a JSON representation you could use in Parse later on
  72088. * @returns the serialized JSON representation
  72089. */
  72090. RefractionTexture.prototype.serialize = function () {
  72091. if (!this.name) {
  72092. return null;
  72093. }
  72094. var serializationObject = _super.prototype.serialize.call(this);
  72095. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  72096. serializationObject.depth = this.depth;
  72097. return serializationObject;
  72098. };
  72099. return RefractionTexture;
  72100. }(BABYLON.RenderTargetTexture));
  72101. BABYLON.RefractionTexture = RefractionTexture;
  72102. })(BABYLON || (BABYLON = {}));
  72103. //# sourceMappingURL=babylon.refractionTexture.js.map
  72104. var BABYLON;
  72105. (function (BABYLON) {
  72106. /**
  72107. * A class extending {BABYLON.Texture} allowing drawing on a texture
  72108. * @see http://doc.babylonjs.com/how_to/dynamictexture
  72109. */
  72110. var DynamicTexture = /** @class */ (function (_super) {
  72111. __extends(DynamicTexture, _super);
  72112. /**
  72113. * Creates a {BABYLON.DynamicTexture}
  72114. * @param name defines the name of the texture
  72115. * @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
  72116. * @param scene defines the scene where you want the texture
  72117. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  72118. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  72119. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  72120. */
  72121. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  72122. if (scene === void 0) { scene = null; }
  72123. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72124. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72125. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  72126. _this.name = name;
  72127. _this._engine = _this.getScene().getEngine();
  72128. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72129. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72130. _this._generateMipMaps = generateMipMaps;
  72131. if (options.getContext) {
  72132. _this._canvas = options;
  72133. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72134. }
  72135. else {
  72136. _this._canvas = document.createElement("canvas");
  72137. if (options.width || options.width === 0) {
  72138. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72139. }
  72140. else {
  72141. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  72142. }
  72143. }
  72144. var textureSize = _this.getSize();
  72145. _this._canvas.width = textureSize.width;
  72146. _this._canvas.height = textureSize.height;
  72147. _this._context = _this._canvas.getContext("2d");
  72148. return _this;
  72149. }
  72150. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  72151. /**
  72152. * Gets the current state of canRescale
  72153. */
  72154. get: function () {
  72155. return true;
  72156. },
  72157. enumerable: true,
  72158. configurable: true
  72159. });
  72160. DynamicTexture.prototype._recreate = function (textureSize) {
  72161. this._canvas.width = textureSize.width;
  72162. this._canvas.height = textureSize.height;
  72163. this.releaseInternalTexture();
  72164. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  72165. };
  72166. /**
  72167. * Scales the texture
  72168. * @param ratio the scale factor to apply to both width and height
  72169. */
  72170. DynamicTexture.prototype.scale = function (ratio) {
  72171. var textureSize = this.getSize();
  72172. textureSize.width *= ratio;
  72173. textureSize.height *= ratio;
  72174. this._recreate(textureSize);
  72175. };
  72176. /**
  72177. * Resizes the texture
  72178. * @param width the new width
  72179. * @param height the new height
  72180. */
  72181. DynamicTexture.prototype.scaleTo = function (width, height) {
  72182. var textureSize = this.getSize();
  72183. textureSize.width = width;
  72184. textureSize.height = height;
  72185. this._recreate(textureSize);
  72186. };
  72187. /**
  72188. * Gets the context of the canvas used by the texture
  72189. * @returns the canvas context of the dynamic texture
  72190. */
  72191. DynamicTexture.prototype.getContext = function () {
  72192. return this._context;
  72193. };
  72194. /**
  72195. * Clears the texture
  72196. */
  72197. DynamicTexture.prototype.clear = function () {
  72198. var size = this.getSize();
  72199. this._context.fillRect(0, 0, size.width, size.height);
  72200. };
  72201. /**
  72202. * Updates the texture
  72203. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  72204. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  72205. */
  72206. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  72207. if (premulAlpha === void 0) { premulAlpha = false; }
  72208. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  72209. };
  72210. /**
  72211. * Draws text onto the texture
  72212. * @param text defines the text to be drawn
  72213. * @param x defines the placement of the text from the left
  72214. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  72215. * @param font defines the font to be used with font-style, font-size, font-name
  72216. * @param color defines the color used for the text
  72217. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  72218. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  72219. * @param update defines whether texture is immediately update (default is true)
  72220. */
  72221. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  72222. if (update === void 0) { update = true; }
  72223. var size = this.getSize();
  72224. if (clearColor) {
  72225. this._context.fillStyle = clearColor;
  72226. this._context.fillRect(0, 0, size.width, size.height);
  72227. }
  72228. this._context.font = font;
  72229. if (x === null || x === undefined) {
  72230. var textSize = this._context.measureText(text);
  72231. x = (size.width - textSize.width) / 2;
  72232. }
  72233. if (y === null || y === undefined) {
  72234. var fontSize = parseInt((font.replace(/\D/g, '')));
  72235. y = (size.height / 2) + (fontSize / 3.65);
  72236. }
  72237. this._context.fillStyle = color;
  72238. this._context.fillText(text, x, y);
  72239. if (update) {
  72240. this.update(invertY);
  72241. }
  72242. };
  72243. /**
  72244. * Clones the texture
  72245. * @returns the clone of the texture.
  72246. */
  72247. DynamicTexture.prototype.clone = function () {
  72248. var scene = this.getScene();
  72249. if (!scene) {
  72250. return this;
  72251. }
  72252. var textureSize = this.getSize();
  72253. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  72254. // Base texture
  72255. newTexture.hasAlpha = this.hasAlpha;
  72256. newTexture.level = this.level;
  72257. // Dynamic Texture
  72258. newTexture.wrapU = this.wrapU;
  72259. newTexture.wrapV = this.wrapV;
  72260. return newTexture;
  72261. };
  72262. /**
  72263. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  72264. * @returns a serialized dynamic texture object
  72265. */
  72266. DynamicTexture.prototype.serialize = function () {
  72267. var scene = this.getScene();
  72268. if (scene && !scene.isReady()) {
  72269. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  72270. }
  72271. var serializationObject = _super.prototype.serialize.call(this);
  72272. serializationObject.base64String = this._canvas.toDataURL();
  72273. serializationObject.invertY = this._invertY;
  72274. serializationObject.samplingMode = this.samplingMode;
  72275. return serializationObject;
  72276. };
  72277. /** @hidden */
  72278. DynamicTexture.prototype._rebuild = function () {
  72279. this.update();
  72280. };
  72281. return DynamicTexture;
  72282. }(BABYLON.Texture));
  72283. BABYLON.DynamicTexture = DynamicTexture;
  72284. })(BABYLON || (BABYLON = {}));
  72285. //# sourceMappingURL=babylon.dynamicTexture.js.map
  72286. var BABYLON;
  72287. (function (BABYLON) {
  72288. /**
  72289. * If you want to display a video in your scene, this is the special texture for that.
  72290. * This special texture works similar to other textures, with the exception of a few parameters.
  72291. * @see https://doc.babylonjs.com/how_to/video_texture
  72292. */
  72293. var VideoTexture = /** @class */ (function (_super) {
  72294. __extends(VideoTexture, _super);
  72295. /**
  72296. * Creates a video texture.
  72297. * If you want to display a video in your scene, this is the special texture for that.
  72298. * This special texture works similar to other textures, with the exception of a few parameters.
  72299. * @see https://doc.babylonjs.com/how_to/video_texture
  72300. * @param {string | null} name optional name, will detect from video source, if not defined
  72301. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  72302. * @param {BABYLON.Scene} scene is obviously the current scene.
  72303. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  72304. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  72305. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  72306. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  72307. */
  72308. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  72309. if (generateMipMaps === void 0) { generateMipMaps = false; }
  72310. if (invertY === void 0) { invertY = false; }
  72311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72312. if (settings === void 0) { settings = {
  72313. autoPlay: true,
  72314. loop: true,
  72315. autoUpdateTexture: true,
  72316. }; }
  72317. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72318. _this._onUserActionRequestedObservable = null;
  72319. _this._stillImageCaptured = false;
  72320. _this._poster = false;
  72321. _this._createInternalTexture = function () {
  72322. if (_this._texture != null) {
  72323. if (_this._poster) {
  72324. _this._texture.dispose();
  72325. _this._poster = false;
  72326. }
  72327. else {
  72328. return;
  72329. }
  72330. }
  72331. if (!_this._engine.needPOTTextures ||
  72332. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  72333. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72334. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72335. }
  72336. else {
  72337. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72338. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72339. _this._generateMipMaps = false;
  72340. }
  72341. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  72342. if (!_this.video.autoplay) {
  72343. var oldHandler_1 = _this.video.onplaying;
  72344. var error_1 = false;
  72345. _this.video.onplaying = function () {
  72346. _this.video.onplaying = oldHandler_1;
  72347. _this._texture.isReady = true;
  72348. _this._updateInternalTexture();
  72349. if (!error_1) {
  72350. _this.video.pause();
  72351. }
  72352. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72353. _this.onLoadObservable.notifyObservers(_this);
  72354. }
  72355. };
  72356. var playing = _this.video.play();
  72357. if (playing) {
  72358. playing.then(function () {
  72359. // Everything is good.
  72360. })
  72361. .catch(function () {
  72362. error_1 = true;
  72363. // On Chrome for instance, new policies might prevent playing without user interaction.
  72364. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  72365. _this._onUserActionRequestedObservable.notifyObservers(_this);
  72366. }
  72367. });
  72368. }
  72369. else {
  72370. _this.video.onplaying = oldHandler_1;
  72371. _this._texture.isReady = true;
  72372. _this._updateInternalTexture();
  72373. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72374. _this.onLoadObservable.notifyObservers(_this);
  72375. }
  72376. }
  72377. }
  72378. else {
  72379. _this._texture.isReady = true;
  72380. _this._updateInternalTexture();
  72381. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72382. _this.onLoadObservable.notifyObservers(_this);
  72383. }
  72384. }
  72385. };
  72386. _this.reset = function () {
  72387. if (_this._texture == null) {
  72388. return;
  72389. }
  72390. if (!_this._poster) {
  72391. _this._texture.dispose();
  72392. _this._texture = null;
  72393. }
  72394. };
  72395. _this._updateInternalTexture = function (e) {
  72396. if (_this._texture == null || !_this._texture.isReady) {
  72397. return;
  72398. }
  72399. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  72400. return;
  72401. }
  72402. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  72403. };
  72404. _this._engine = _this.getScene().getEngine();
  72405. _this._generateMipMaps = generateMipMaps;
  72406. _this._samplingMode = samplingMode;
  72407. _this.autoUpdateTexture = settings.autoUpdateTexture;
  72408. _this.name = name || _this._getName(src);
  72409. _this.video = _this._getVideo(src);
  72410. if (settings.poster) {
  72411. _this.video.poster = settings.poster;
  72412. }
  72413. if (settings.autoPlay !== undefined) {
  72414. _this.video.autoplay = settings.autoPlay;
  72415. }
  72416. if (settings.loop !== undefined) {
  72417. _this.video.loop = settings.loop;
  72418. }
  72419. _this.video.setAttribute("playsinline", "");
  72420. _this.video.addEventListener("canplay", _this._createInternalTexture);
  72421. _this.video.addEventListener("paused", _this._updateInternalTexture);
  72422. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  72423. _this.video.addEventListener("emptied", _this.reset);
  72424. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  72425. _this._createInternalTexture();
  72426. }
  72427. if (settings.poster) {
  72428. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  72429. _this._poster = true;
  72430. }
  72431. return _this;
  72432. }
  72433. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  72434. /**
  72435. * Event triggerd when a dom action is required by the user to play the video.
  72436. * This happens due to recent changes in browser policies preventing video to auto start.
  72437. */
  72438. get: function () {
  72439. if (!this._onUserActionRequestedObservable) {
  72440. this._onUserActionRequestedObservable = new BABYLON.Observable();
  72441. }
  72442. return this._onUserActionRequestedObservable;
  72443. },
  72444. enumerable: true,
  72445. configurable: true
  72446. });
  72447. VideoTexture.prototype._getName = function (src) {
  72448. if (src instanceof HTMLVideoElement) {
  72449. return src.currentSrc;
  72450. }
  72451. if (typeof src === "object") {
  72452. return src.toString();
  72453. }
  72454. return src;
  72455. };
  72456. ;
  72457. VideoTexture.prototype._getVideo = function (src) {
  72458. if (src instanceof HTMLVideoElement) {
  72459. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  72460. return src;
  72461. }
  72462. var video = document.createElement("video");
  72463. if (typeof src === "string") {
  72464. BABYLON.Tools.SetCorsBehavior(src, video);
  72465. video.src = src;
  72466. }
  72467. else {
  72468. BABYLON.Tools.SetCorsBehavior(src[0], video);
  72469. src.forEach(function (url) {
  72470. var source = document.createElement("source");
  72471. source.src = url;
  72472. video.appendChild(source);
  72473. });
  72474. }
  72475. return video;
  72476. };
  72477. ;
  72478. /**
  72479. * @hidden Internal method to initiate `update`.
  72480. */
  72481. VideoTexture.prototype._rebuild = function () {
  72482. this.update();
  72483. };
  72484. /**
  72485. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  72486. */
  72487. VideoTexture.prototype.update = function () {
  72488. if (!this.autoUpdateTexture) {
  72489. // Expecting user to call `updateTexture` manually
  72490. return;
  72491. }
  72492. this.updateTexture(true);
  72493. };
  72494. /**
  72495. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  72496. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  72497. */
  72498. VideoTexture.prototype.updateTexture = function (isVisible) {
  72499. if (!isVisible) {
  72500. return;
  72501. }
  72502. if (this.video.paused && this._stillImageCaptured) {
  72503. return;
  72504. }
  72505. this._stillImageCaptured = true;
  72506. this._updateInternalTexture();
  72507. };
  72508. /**
  72509. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  72510. * @param url New url.
  72511. */
  72512. VideoTexture.prototype.updateURL = function (url) {
  72513. this.video.src = url;
  72514. };
  72515. /**
  72516. * Dispose the texture and release its associated resources.
  72517. */
  72518. VideoTexture.prototype.dispose = function () {
  72519. _super.prototype.dispose.call(this);
  72520. if (this._onUserActionRequestedObservable) {
  72521. this._onUserActionRequestedObservable.clear();
  72522. this._onUserActionRequestedObservable = null;
  72523. }
  72524. this.video.removeEventListener("canplay", this._createInternalTexture);
  72525. this.video.removeEventListener("paused", this._updateInternalTexture);
  72526. this.video.removeEventListener("seeked", this._updateInternalTexture);
  72527. this.video.removeEventListener("emptied", this.reset);
  72528. this.video.pause();
  72529. };
  72530. /**
  72531. * Creates a video texture straight from your WebCam video feed.
  72532. * @param scene Define the scene the texture should be created in
  72533. * @param onReady Define a callback to triggered once the texture will be ready
  72534. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  72535. */
  72536. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  72537. var video = document.createElement("video");
  72538. video.setAttribute('autoplay', '');
  72539. video.setAttribute('muted', '');
  72540. video.setAttribute('playsinline', '');
  72541. var constraintsDeviceId;
  72542. if (constraints && constraints.deviceId) {
  72543. constraintsDeviceId = {
  72544. exact: constraints.deviceId,
  72545. };
  72546. }
  72547. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  72548. if (navigator.mediaDevices) {
  72549. navigator.mediaDevices.getUserMedia({ video: constraints })
  72550. .then(function (stream) {
  72551. if (video.mozSrcObject !== undefined) {
  72552. // hack for Firefox < 19
  72553. video.mozSrcObject = stream;
  72554. }
  72555. else {
  72556. video.srcObject = stream;
  72557. }
  72558. var onPlaying = function () {
  72559. if (onReady) {
  72560. onReady(new VideoTexture("video", video, scene, true, true));
  72561. }
  72562. video.removeEventListener("playing", onPlaying);
  72563. };
  72564. video.addEventListener("playing", onPlaying);
  72565. video.play();
  72566. })
  72567. .catch(function (err) {
  72568. BABYLON.Tools.Error(err.name);
  72569. });
  72570. }
  72571. else {
  72572. navigator.getUserMedia =
  72573. navigator.getUserMedia ||
  72574. navigator.webkitGetUserMedia ||
  72575. navigator.mozGetUserMedia ||
  72576. navigator.msGetUserMedia;
  72577. if (navigator.getUserMedia) {
  72578. navigator.getUserMedia({
  72579. video: {
  72580. deviceId: constraintsDeviceId,
  72581. width: {
  72582. min: (constraints && constraints.minWidth) || 256,
  72583. max: (constraints && constraints.maxWidth) || 640,
  72584. },
  72585. height: {
  72586. min: (constraints && constraints.minHeight) || 256,
  72587. max: (constraints && constraints.maxHeight) || 480,
  72588. },
  72589. },
  72590. }, function (stream) {
  72591. if (video.mozSrcObject !== undefined) {
  72592. // hack for Firefox < 19
  72593. video.mozSrcObject = stream;
  72594. }
  72595. else {
  72596. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  72597. }
  72598. video.play();
  72599. if (onReady) {
  72600. onReady(new VideoTexture("video", video, scene, true, true));
  72601. }
  72602. }, function (e) {
  72603. BABYLON.Tools.Error(e.name);
  72604. });
  72605. }
  72606. }
  72607. };
  72608. return VideoTexture;
  72609. }(BABYLON.Texture));
  72610. BABYLON.VideoTexture = VideoTexture;
  72611. })(BABYLON || (BABYLON = {}));
  72612. //# sourceMappingURL=babylon.videoTexture.js.map
  72613. var BABYLON;
  72614. (function (BABYLON) {
  72615. /**
  72616. * Raw texture can help creating a texture directly from an array of data.
  72617. * This can be super useful if you either get the data from an uncompressed source or
  72618. * if you wish to create your texture pixel by pixel.
  72619. */
  72620. var RawTexture = /** @class */ (function (_super) {
  72621. __extends(RawTexture, _super);
  72622. /**
  72623. * Instantiates a new RawTexture.
  72624. * Raw texture can help creating a texture directly from an array of data.
  72625. * This can be super useful if you either get the data from an uncompressed source or
  72626. * if you wish to create your texture pixel by pixel.
  72627. * @param data define the array of data to use to create the texture
  72628. * @param width define the width of the texture
  72629. * @param height define the height of the texture
  72630. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  72631. * @param scene define the scene the texture belongs to
  72632. * @param generateMipMaps define whether mip maps should be generated or not
  72633. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72634. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72635. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  72636. */
  72637. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  72638. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72639. if (invertY === void 0) { invertY = false; }
  72640. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72641. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72642. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72643. _this.format = format;
  72644. _this._engine = scene.getEngine();
  72645. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  72646. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72647. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72648. return _this;
  72649. }
  72650. /**
  72651. * Updates the texture underlying data.
  72652. * @param data Define the new data of the texture
  72653. */
  72654. RawTexture.prototype.update = function (data) {
  72655. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  72656. };
  72657. /**
  72658. * Creates a luminance texture from some data.
  72659. * @param data Define the texture data
  72660. * @param width Define the width of the texture
  72661. * @param height Define the height of the texture
  72662. * @param scene Define the scene the texture belongs to
  72663. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72664. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72665. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72666. * @returns the luminance texture
  72667. */
  72668. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72669. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72670. if (invertY === void 0) { invertY = false; }
  72671. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72672. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  72673. };
  72674. /**
  72675. * Creates a luminance alpha texture from some data.
  72676. * @param data Define the texture data
  72677. * @param width Define the width of the texture
  72678. * @param height Define the height of the texture
  72679. * @param scene Define the scene the texture belongs to
  72680. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72681. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72682. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72683. * @returns the luminance alpha texture
  72684. */
  72685. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72686. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72687. if (invertY === void 0) { invertY = false; }
  72688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72689. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  72690. };
  72691. /**
  72692. * Creates an alpha texture from some data.
  72693. * @param data Define the texture data
  72694. * @param width Define the width of the texture
  72695. * @param height Define the height of the texture
  72696. * @param scene Define the scene the texture belongs to
  72697. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72698. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72699. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72700. * @returns the alpha texture
  72701. */
  72702. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72703. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72704. if (invertY === void 0) { invertY = false; }
  72705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72706. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  72707. };
  72708. /**
  72709. * Creates a RGB texture from some data.
  72710. * @param data Define the texture data
  72711. * @param width Define the width of the texture
  72712. * @param height Define the height of the texture
  72713. * @param scene Define the scene the texture belongs to
  72714. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72715. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72716. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72717. * @returns the RGB alpha texture
  72718. */
  72719. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72720. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72721. if (invertY === void 0) { invertY = false; }
  72722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72723. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72724. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  72725. };
  72726. /**
  72727. * Creates a RGBA texture from some data.
  72728. * @param data Define the texture data
  72729. * @param width Define the width of the texture
  72730. * @param height Define the height of the texture
  72731. * @param scene Define the scene the texture belongs to
  72732. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72733. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72734. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72735. * @returns the RGBA texture
  72736. */
  72737. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72738. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72739. if (invertY === void 0) { invertY = false; }
  72740. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72741. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72742. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  72743. };
  72744. /**
  72745. * Creates a R texture from some data.
  72746. * @param data Define the texture data
  72747. * @param width Define the width of the texture
  72748. * @param height Define the height of the texture
  72749. * @param scene Define the scene the texture belongs to
  72750. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72751. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72752. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72753. * @returns the R texture
  72754. */
  72755. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72756. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72757. if (invertY === void 0) { invertY = false; }
  72758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72759. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72760. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  72761. };
  72762. return RawTexture;
  72763. }(BABYLON.Texture));
  72764. BABYLON.RawTexture = RawTexture;
  72765. })(BABYLON || (BABYLON = {}));
  72766. //# sourceMappingURL=babylon.rawTexture.js.map
  72767. var BABYLON;
  72768. (function (BABYLON) {
  72769. /**
  72770. * Class used to store 3D textures containing user data
  72771. */
  72772. var RawTexture3D = /** @class */ (function (_super) {
  72773. __extends(RawTexture3D, _super);
  72774. /**
  72775. * Create a new RawTexture3D
  72776. * @param data defines the data of the texture
  72777. * @param width defines the width of the texture
  72778. * @param height defines the height of the texture
  72779. * @param depth defines the depth of the texture
  72780. * @param format defines the texture format to use
  72781. * @param scene defines the hosting scene
  72782. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  72783. * @param invertY defines if texture must be stored with Y axis inverted
  72784. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  72785. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  72786. */
  72787. function RawTexture3D(data, width, height, depth,
  72788. /** Gets or sets the texture format to use */
  72789. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  72790. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72791. if (invertY === void 0) { invertY = false; }
  72792. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72793. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72794. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72795. _this.format = format;
  72796. _this._engine = scene.getEngine();
  72797. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  72798. _this.is3D = true;
  72799. return _this;
  72800. }
  72801. /**
  72802. * Update the texture with new data
  72803. * @param data defines the data to store in the texture
  72804. */
  72805. RawTexture3D.prototype.update = function (data) {
  72806. if (!this._texture) {
  72807. return;
  72808. }
  72809. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  72810. };
  72811. return RawTexture3D;
  72812. }(BABYLON.Texture));
  72813. BABYLON.RawTexture3D = RawTexture3D;
  72814. })(BABYLON || (BABYLON = {}));
  72815. //# sourceMappingURL=babylon.rawTexture3D.js.map
  72816. var BABYLON;
  72817. (function (BABYLON) {
  72818. /**
  72819. * PostProcessManager is used to manage one or more post processes or post process pipelines
  72820. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  72821. */
  72822. var PostProcessManager = /** @class */ (function () {
  72823. /**
  72824. * Creates a new instance PostProcess
  72825. * @param scene The scene that the post process is associated with.
  72826. */
  72827. function PostProcessManager(scene) {
  72828. this._vertexBuffers = {};
  72829. this._scene = scene;
  72830. }
  72831. PostProcessManager.prototype._prepareBuffers = function () {
  72832. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  72833. return;
  72834. }
  72835. // VBO
  72836. var vertices = [];
  72837. vertices.push(1, 1);
  72838. vertices.push(-1, 1);
  72839. vertices.push(-1, -1);
  72840. vertices.push(1, -1);
  72841. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72842. this._buildIndexBuffer();
  72843. };
  72844. PostProcessManager.prototype._buildIndexBuffer = function () {
  72845. // Indices
  72846. var indices = [];
  72847. indices.push(0);
  72848. indices.push(1);
  72849. indices.push(2);
  72850. indices.push(0);
  72851. indices.push(2);
  72852. indices.push(3);
  72853. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  72854. };
  72855. /**
  72856. * Rebuilds the vertex buffers of the manager.
  72857. * @hidden
  72858. */
  72859. PostProcessManager.prototype._rebuild = function () {
  72860. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72861. if (!vb) {
  72862. return;
  72863. }
  72864. vb._rebuild();
  72865. this._buildIndexBuffer();
  72866. };
  72867. // Methods
  72868. /**
  72869. * Prepares a frame to be run through a post process.
  72870. * @param sourceTexture The input texture to the post procesess. (default: null)
  72871. * @param postProcesses An array of post processes to be run. (default: null)
  72872. * @returns True if the post processes were able to be run.
  72873. * @hidden
  72874. */
  72875. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  72876. if (sourceTexture === void 0) { sourceTexture = null; }
  72877. if (postProcesses === void 0) { postProcesses = null; }
  72878. var camera = this._scene.activeCamera;
  72879. if (!camera) {
  72880. return false;
  72881. }
  72882. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  72883. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  72884. return false;
  72885. }
  72886. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  72887. return true;
  72888. };
  72889. /**
  72890. * Manually render a set of post processes to a texture.
  72891. * @param postProcesses An array of post processes to be run.
  72892. * @param targetTexture The target texture to render to.
  72893. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  72894. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  72895. * @param lodLevel defines which lod of the texture to render to
  72896. */
  72897. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  72898. if (targetTexture === void 0) { targetTexture = null; }
  72899. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  72900. if (faceIndex === void 0) { faceIndex = 0; }
  72901. if (lodLevel === void 0) { lodLevel = 0; }
  72902. var engine = this._scene.getEngine();
  72903. for (var index = 0; index < postProcesses.length; index++) {
  72904. if (index < postProcesses.length - 1) {
  72905. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  72906. }
  72907. else {
  72908. if (targetTexture) {
  72909. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  72910. }
  72911. else {
  72912. engine.restoreDefaultFramebuffer();
  72913. }
  72914. }
  72915. var pp = postProcesses[index];
  72916. var effect = pp.apply();
  72917. if (effect) {
  72918. pp.onBeforeRenderObservable.notifyObservers(effect);
  72919. // VBOs
  72920. this._prepareBuffers();
  72921. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  72922. // Draw order
  72923. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72924. pp.onAfterRenderObservable.notifyObservers(effect);
  72925. }
  72926. }
  72927. // Restore depth buffer
  72928. engine.setDepthBuffer(true);
  72929. engine.setDepthWrite(true);
  72930. };
  72931. /**
  72932. * Finalize the result of the output of the postprocesses.
  72933. * @param doNotPresent If true the result will not be displayed to the screen.
  72934. * @param targetTexture The target texture to render to.
  72935. * @param faceIndex The index of the face to bind the target texture to.
  72936. * @param postProcesses The array of post processes to render.
  72937. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  72938. * @hidden
  72939. */
  72940. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  72941. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  72942. var camera = this._scene.activeCamera;
  72943. if (!camera) {
  72944. return;
  72945. }
  72946. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  72947. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  72948. return;
  72949. }
  72950. var engine = this._scene.getEngine();
  72951. for (var index = 0, len = postProcesses.length; index < len; index++) {
  72952. var pp = postProcesses[index];
  72953. if (index < len - 1) {
  72954. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  72955. }
  72956. else {
  72957. if (targetTexture) {
  72958. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  72959. pp._outputTexture = targetTexture;
  72960. }
  72961. else {
  72962. engine.restoreDefaultFramebuffer();
  72963. pp._outputTexture = null;
  72964. }
  72965. }
  72966. if (doNotPresent) {
  72967. break;
  72968. }
  72969. var effect = pp.apply();
  72970. if (effect) {
  72971. pp.onBeforeRenderObservable.notifyObservers(effect);
  72972. // VBOs
  72973. this._prepareBuffers();
  72974. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  72975. // Draw order
  72976. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72977. pp.onAfterRenderObservable.notifyObservers(effect);
  72978. }
  72979. }
  72980. // Restore states
  72981. engine.setDepthBuffer(true);
  72982. engine.setDepthWrite(true);
  72983. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72984. };
  72985. /**
  72986. * Disposes of the post process manager.
  72987. */
  72988. PostProcessManager.prototype.dispose = function () {
  72989. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72990. if (buffer) {
  72991. buffer.dispose();
  72992. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72993. }
  72994. if (this._indexBuffer) {
  72995. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72996. this._indexBuffer = null;
  72997. }
  72998. };
  72999. return PostProcessManager;
  73000. }());
  73001. BABYLON.PostProcessManager = PostProcessManager;
  73002. })(BABYLON || (BABYLON = {}));
  73003. //# sourceMappingURL=babylon.postProcessManager.js.map
  73004. var BABYLON;
  73005. (function (BABYLON) {
  73006. /**
  73007. * PostProcess can be used to apply a shader to a texture after it has been rendered
  73008. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73009. */
  73010. var PostProcess = /** @class */ (function () {
  73011. /**
  73012. * Creates a new instance PostProcess
  73013. * @param name The name of the PostProcess.
  73014. * @param fragmentUrl The url of the fragment shader to be used.
  73015. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  73016. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  73017. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73018. * @param camera The camera to apply the render pass to.
  73019. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73020. * @param engine The engine which the post process will be applied. (default: current engine)
  73021. * @param reusable If the post process can be reused on the same frame. (default: false)
  73022. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  73023. * @param textureType Type of textures used when performing the post process. (default: 0)
  73024. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  73025. * @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
  73026. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  73027. */
  73028. function PostProcess(
  73029. /** Name of the PostProcess. */
  73030. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  73031. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  73032. if (defines === void 0) { defines = null; }
  73033. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73034. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  73035. if (blockCompilation === void 0) { blockCompilation = false; }
  73036. this.name = name;
  73037. /**
  73038. * Width of the texture to apply the post process on
  73039. */
  73040. this.width = -1;
  73041. /**
  73042. * Height of the texture to apply the post process on
  73043. */
  73044. this.height = -1;
  73045. /**
  73046. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  73047. * @hidden
  73048. */
  73049. this._outputTexture = null;
  73050. /**
  73051. * If the buffer needs to be cleared before applying the post process. (default: true)
  73052. * Should be set to false if shader will overwrite all previous pixels.
  73053. */
  73054. this.autoClear = true;
  73055. /**
  73056. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  73057. */
  73058. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  73059. /**
  73060. * Animations to be used for the post processing
  73061. */
  73062. this.animations = new Array();
  73063. /**
  73064. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  73065. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  73066. */
  73067. this.enablePixelPerfectMode = false;
  73068. /**
  73069. * Force the postprocess to be applied without taking in account viewport
  73070. */
  73071. this.forceFullscreenViewport = true;
  73072. /**
  73073. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  73074. *
  73075. * | Value | Type | Description |
  73076. * | ----- | ----------------------------------- | ----------- |
  73077. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  73078. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  73079. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  73080. *
  73081. */
  73082. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  73083. /**
  73084. * Force textures to be a power of two (default: false)
  73085. */
  73086. this.alwaysForcePOT = false;
  73087. this._samples = 1;
  73088. /**
  73089. * Modify the scale of the post process to be the same as the viewport (default: false)
  73090. */
  73091. this.adaptScaleToCurrentViewport = false;
  73092. this._reusable = false;
  73093. /**
  73094. * Smart array of input and output textures for the post process.
  73095. * @hidden
  73096. */
  73097. this._textures = new BABYLON.SmartArray(2);
  73098. /**
  73099. * The index in _textures that corresponds to the output texture.
  73100. * @hidden
  73101. */
  73102. this._currentRenderTextureInd = 0;
  73103. this._scaleRatio = new BABYLON.Vector2(1, 1);
  73104. this._texelSize = BABYLON.Vector2.Zero();
  73105. // Events
  73106. /**
  73107. * An event triggered when the postprocess is activated.
  73108. */
  73109. this.onActivateObservable = new BABYLON.Observable();
  73110. /**
  73111. * An event triggered when the postprocess changes its size.
  73112. */
  73113. this.onSizeChangedObservable = new BABYLON.Observable();
  73114. /**
  73115. * An event triggered when the postprocess applies its effect.
  73116. */
  73117. this.onApplyObservable = new BABYLON.Observable();
  73118. /**
  73119. * An event triggered before rendering the postprocess
  73120. */
  73121. this.onBeforeRenderObservable = new BABYLON.Observable();
  73122. /**
  73123. * An event triggered after rendering the postprocess
  73124. */
  73125. this.onAfterRenderObservable = new BABYLON.Observable();
  73126. if (camera != null) {
  73127. this._camera = camera;
  73128. this._scene = camera.getScene();
  73129. camera.attachPostProcess(this);
  73130. this._engine = this._scene.getEngine();
  73131. this._scene.postProcesses.push(this);
  73132. }
  73133. else if (engine) {
  73134. this._engine = engine;
  73135. this._engine.postProcesses.push(this);
  73136. }
  73137. this._options = options;
  73138. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  73139. this._reusable = reusable || false;
  73140. this._textureType = textureType;
  73141. this._samplers = samplers || [];
  73142. this._samplers.push("textureSampler");
  73143. this._fragmentUrl = fragmentUrl;
  73144. this._vertexUrl = vertexUrl;
  73145. this._parameters = parameters || [];
  73146. this._parameters.push("scale");
  73147. this._indexParameters = indexParameters;
  73148. if (!blockCompilation) {
  73149. this.updateEffect(defines);
  73150. }
  73151. }
  73152. Object.defineProperty(PostProcess.prototype, "samples", {
  73153. /**
  73154. * Number of sample textures (default: 1)
  73155. */
  73156. get: function () {
  73157. return this._samples;
  73158. },
  73159. set: function (n) {
  73160. var _this = this;
  73161. this._samples = n;
  73162. this._textures.forEach(function (texture) {
  73163. if (texture.samples !== _this._samples) {
  73164. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  73165. }
  73166. });
  73167. },
  73168. enumerable: true,
  73169. configurable: true
  73170. });
  73171. Object.defineProperty(PostProcess.prototype, "onActivate", {
  73172. /**
  73173. * A function that is added to the onActivateObservable
  73174. */
  73175. set: function (callback) {
  73176. if (this._onActivateObserver) {
  73177. this.onActivateObservable.remove(this._onActivateObserver);
  73178. }
  73179. if (callback) {
  73180. this._onActivateObserver = this.onActivateObservable.add(callback);
  73181. }
  73182. },
  73183. enumerable: true,
  73184. configurable: true
  73185. });
  73186. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  73187. /**
  73188. * A function that is added to the onSizeChangedObservable
  73189. */
  73190. set: function (callback) {
  73191. if (this._onSizeChangedObserver) {
  73192. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  73193. }
  73194. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  73195. },
  73196. enumerable: true,
  73197. configurable: true
  73198. });
  73199. Object.defineProperty(PostProcess.prototype, "onApply", {
  73200. /**
  73201. * A function that is added to the onApplyObservable
  73202. */
  73203. set: function (callback) {
  73204. if (this._onApplyObserver) {
  73205. this.onApplyObservable.remove(this._onApplyObserver);
  73206. }
  73207. this._onApplyObserver = this.onApplyObservable.add(callback);
  73208. },
  73209. enumerable: true,
  73210. configurable: true
  73211. });
  73212. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  73213. /**
  73214. * A function that is added to the onBeforeRenderObservable
  73215. */
  73216. set: function (callback) {
  73217. if (this._onBeforeRenderObserver) {
  73218. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73219. }
  73220. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73221. },
  73222. enumerable: true,
  73223. configurable: true
  73224. });
  73225. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  73226. /**
  73227. * A function that is added to the onAfterRenderObservable
  73228. */
  73229. set: function (callback) {
  73230. if (this._onAfterRenderObserver) {
  73231. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73232. }
  73233. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73234. },
  73235. enumerable: true,
  73236. configurable: true
  73237. });
  73238. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  73239. /**
  73240. * 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
  73241. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  73242. */
  73243. get: function () {
  73244. return this._textures.data[this._currentRenderTextureInd];
  73245. },
  73246. set: function (value) {
  73247. this._forcedOutputTexture = value;
  73248. },
  73249. enumerable: true,
  73250. configurable: true
  73251. });
  73252. /**
  73253. * Gets the camera which post process is applied to.
  73254. * @returns The camera the post process is applied to.
  73255. */
  73256. PostProcess.prototype.getCamera = function () {
  73257. return this._camera;
  73258. };
  73259. Object.defineProperty(PostProcess.prototype, "texelSize", {
  73260. /**
  73261. * Gets the texel size of the postprocess.
  73262. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  73263. */
  73264. get: function () {
  73265. if (this._shareOutputWithPostProcess) {
  73266. return this._shareOutputWithPostProcess.texelSize;
  73267. }
  73268. if (this._forcedOutputTexture) {
  73269. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  73270. }
  73271. return this._texelSize;
  73272. },
  73273. enumerable: true,
  73274. configurable: true
  73275. });
  73276. /**
  73277. * Gets the engine which this post process belongs to.
  73278. * @returns The engine the post process was enabled with.
  73279. */
  73280. PostProcess.prototype.getEngine = function () {
  73281. return this._engine;
  73282. };
  73283. /**
  73284. * The effect that is created when initializing the post process.
  73285. * @returns The created effect corrisponding the the postprocess.
  73286. */
  73287. PostProcess.prototype.getEffect = function () {
  73288. return this._effect;
  73289. };
  73290. /**
  73291. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  73292. * @param postProcess The post process to share the output with.
  73293. * @returns This post process.
  73294. */
  73295. PostProcess.prototype.shareOutputWith = function (postProcess) {
  73296. this._disposeTextures();
  73297. this._shareOutputWithPostProcess = postProcess;
  73298. return this;
  73299. };
  73300. /**
  73301. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  73302. * This should be called if the post process that shares output with this post process is disabled/disposed.
  73303. */
  73304. PostProcess.prototype.useOwnOutput = function () {
  73305. if (this._textures.length == 0) {
  73306. this._textures = new BABYLON.SmartArray(2);
  73307. }
  73308. this._shareOutputWithPostProcess = null;
  73309. };
  73310. /**
  73311. * Updates the effect with the current post process compile time values and recompiles the shader.
  73312. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73313. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73314. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73315. * @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
  73316. * @param onCompiled Called when the shader has been compiled.
  73317. * @param onError Called if there is an error when compiling a shader.
  73318. */
  73319. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73320. if (defines === void 0) { defines = null; }
  73321. if (uniforms === void 0) { uniforms = null; }
  73322. if (samplers === void 0) { samplers = null; }
  73323. 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);
  73324. };
  73325. /**
  73326. * The post process is reusable if it can be used multiple times within one frame.
  73327. * @returns If the post process is reusable
  73328. */
  73329. PostProcess.prototype.isReusable = function () {
  73330. return this._reusable;
  73331. };
  73332. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  73333. PostProcess.prototype.markTextureDirty = function () {
  73334. this.width = -1;
  73335. };
  73336. /**
  73337. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  73338. * 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.
  73339. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  73340. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  73341. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  73342. * @returns The target texture that was bound to be written to.
  73343. */
  73344. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  73345. var _this = this;
  73346. if (sourceTexture === void 0) { sourceTexture = null; }
  73347. camera = camera || this._camera;
  73348. var scene = camera.getScene();
  73349. var engine = scene.getEngine();
  73350. var maxSize = engine.getCaps().maxTextureSize;
  73351. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  73352. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  73353. // 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
  73354. var webVRCamera = camera.parent;
  73355. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  73356. requiredWidth /= 2;
  73357. }
  73358. var desiredWidth = (this._options.width || requiredWidth);
  73359. var desiredHeight = this._options.height || requiredHeight;
  73360. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  73361. if (this.adaptScaleToCurrentViewport) {
  73362. var currentViewport = engine.currentViewport;
  73363. if (currentViewport) {
  73364. desiredWidth *= currentViewport.width;
  73365. desiredHeight *= currentViewport.height;
  73366. }
  73367. }
  73368. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  73369. if (!this._options.width) {
  73370. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  73371. }
  73372. if (!this._options.height) {
  73373. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  73374. }
  73375. }
  73376. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  73377. if (this._textures.length > 0) {
  73378. for (var i = 0; i < this._textures.length; i++) {
  73379. this._engine._releaseTexture(this._textures.data[i]);
  73380. }
  73381. this._textures.reset();
  73382. }
  73383. this.width = desiredWidth;
  73384. this.height = desiredHeight;
  73385. var textureSize = { width: this.width, height: this.height };
  73386. var textureOptions = {
  73387. generateMipMaps: false,
  73388. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  73389. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  73390. samplingMode: this.renderTargetSamplingMode,
  73391. type: this._textureType
  73392. };
  73393. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  73394. if (this._reusable) {
  73395. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  73396. }
  73397. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  73398. this.onSizeChangedObservable.notifyObservers(this);
  73399. }
  73400. this._textures.forEach(function (texture) {
  73401. if (texture.samples !== _this.samples) {
  73402. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  73403. }
  73404. });
  73405. }
  73406. var target;
  73407. if (this._shareOutputWithPostProcess) {
  73408. target = this._shareOutputWithPostProcess.inputTexture;
  73409. }
  73410. else if (this._forcedOutputTexture) {
  73411. target = this._forcedOutputTexture;
  73412. this.width = this._forcedOutputTexture.width;
  73413. this.height = this._forcedOutputTexture.height;
  73414. }
  73415. else {
  73416. target = this.inputTexture;
  73417. }
  73418. // Bind the input of this post process to be used as the output of the previous post process.
  73419. if (this.enablePixelPerfectMode) {
  73420. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  73421. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  73422. }
  73423. else {
  73424. this._scaleRatio.copyFromFloats(1, 1);
  73425. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  73426. }
  73427. this.onActivateObservable.notifyObservers(camera);
  73428. // Clear
  73429. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  73430. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  73431. }
  73432. if (this._reusable) {
  73433. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  73434. }
  73435. return target;
  73436. };
  73437. Object.defineProperty(PostProcess.prototype, "isSupported", {
  73438. /**
  73439. * If the post process is supported.
  73440. */
  73441. get: function () {
  73442. return this._effect.isSupported;
  73443. },
  73444. enumerable: true,
  73445. configurable: true
  73446. });
  73447. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  73448. /**
  73449. * The aspect ratio of the output texture.
  73450. */
  73451. get: function () {
  73452. if (this._shareOutputWithPostProcess) {
  73453. return this._shareOutputWithPostProcess.aspectRatio;
  73454. }
  73455. if (this._forcedOutputTexture) {
  73456. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  73457. }
  73458. return this.width / this.height;
  73459. },
  73460. enumerable: true,
  73461. configurable: true
  73462. });
  73463. /**
  73464. * Get a value indicating if the post-process is ready to be used
  73465. * @returns true if the post-process is ready (shader is compiled)
  73466. */
  73467. PostProcess.prototype.isReady = function () {
  73468. return this._effect && this._effect.isReady();
  73469. };
  73470. /**
  73471. * Binds all textures and uniforms to the shader, this will be run on every pass.
  73472. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  73473. */
  73474. PostProcess.prototype.apply = function () {
  73475. // Check
  73476. if (!this._effect || !this._effect.isReady())
  73477. return null;
  73478. // States
  73479. this._engine.enableEffect(this._effect);
  73480. this._engine.setState(false);
  73481. this._engine.setDepthBuffer(false);
  73482. this._engine.setDepthWrite(false);
  73483. // Alpha
  73484. this._engine.setAlphaMode(this.alphaMode);
  73485. if (this.alphaConstants) {
  73486. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  73487. }
  73488. // Bind the output texture of the preivous post process as the input to this post process.
  73489. var source;
  73490. if (this._shareOutputWithPostProcess) {
  73491. source = this._shareOutputWithPostProcess.inputTexture;
  73492. }
  73493. else if (this._forcedOutputTexture) {
  73494. source = this._forcedOutputTexture;
  73495. }
  73496. else {
  73497. source = this.inputTexture;
  73498. }
  73499. this._effect._bindTexture("textureSampler", source);
  73500. // Parameters
  73501. this._effect.setVector2("scale", this._scaleRatio);
  73502. this.onApplyObservable.notifyObservers(this._effect);
  73503. return this._effect;
  73504. };
  73505. PostProcess.prototype._disposeTextures = function () {
  73506. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  73507. return;
  73508. }
  73509. if (this._textures.length > 0) {
  73510. for (var i = 0; i < this._textures.length; i++) {
  73511. this._engine._releaseTexture(this._textures.data[i]);
  73512. }
  73513. }
  73514. this._textures.dispose();
  73515. };
  73516. /**
  73517. * Disposes the post process.
  73518. * @param camera The camera to dispose the post process on.
  73519. */
  73520. PostProcess.prototype.dispose = function (camera) {
  73521. camera = camera || this._camera;
  73522. this._disposeTextures();
  73523. if (this._scene) {
  73524. var index_1 = this._scene.postProcesses.indexOf(this);
  73525. if (index_1 !== -1) {
  73526. this._scene.postProcesses.splice(index_1, 1);
  73527. }
  73528. }
  73529. else {
  73530. var index_2 = this._engine.postProcesses.indexOf(this);
  73531. if (index_2 !== -1) {
  73532. this._engine.postProcesses.splice(index_2, 1);
  73533. }
  73534. }
  73535. if (!camera) {
  73536. return;
  73537. }
  73538. camera.detachPostProcess(this);
  73539. var index = camera._postProcesses.indexOf(this);
  73540. if (index === 0 && camera._postProcesses.length > 0) {
  73541. var firstPostProcess = this._camera._getFirstPostProcess();
  73542. if (firstPostProcess) {
  73543. firstPostProcess.markTextureDirty();
  73544. }
  73545. }
  73546. this.onActivateObservable.clear();
  73547. this.onAfterRenderObservable.clear();
  73548. this.onApplyObservable.clear();
  73549. this.onBeforeRenderObservable.clear();
  73550. this.onSizeChangedObservable.clear();
  73551. };
  73552. return PostProcess;
  73553. }());
  73554. BABYLON.PostProcess = PostProcess;
  73555. })(BABYLON || (BABYLON = {}));
  73556. //# sourceMappingURL=babylon.postProcess.js.map
  73557. var BABYLON;
  73558. (function (BABYLON) {
  73559. var PassPostProcess = /** @class */ (function (_super) {
  73560. __extends(PassPostProcess, _super);
  73561. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73562. if (camera === void 0) { camera = null; }
  73563. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73564. if (blockCompilation === void 0) { blockCompilation = false; }
  73565. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  73566. }
  73567. return PassPostProcess;
  73568. }(BABYLON.PostProcess));
  73569. BABYLON.PassPostProcess = PassPostProcess;
  73570. })(BABYLON || (BABYLON = {}));
  73571. //# sourceMappingURL=babylon.passPostProcess.js.map
  73572. var __assign = (this && this.__assign) || function () {
  73573. __assign = Object.assign || function(t) {
  73574. for (var s, i = 1, n = arguments.length; i < n; i++) {
  73575. s = arguments[i];
  73576. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  73577. t[p] = s[p];
  73578. }
  73579. return t;
  73580. };
  73581. return __assign.apply(this, arguments);
  73582. };
  73583. var BABYLON;
  73584. (function (BABYLON) {
  73585. /**
  73586. * Default implementation IShadowGenerator.
  73587. * This is the main object responsible of generating shadows in the framework.
  73588. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  73589. */
  73590. var ShadowGenerator = /** @class */ (function () {
  73591. /**
  73592. * Creates a ShadowGenerator object.
  73593. * A ShadowGenerator is the required tool to use the shadows.
  73594. * Each light casting shadows needs to use its own ShadowGenerator.
  73595. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  73596. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  73597. * @param light The light object generating the shadows.
  73598. * @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.
  73599. */
  73600. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  73601. this._bias = 0.00005;
  73602. this._normalBias = 0;
  73603. this._blurBoxOffset = 1;
  73604. this._blurScale = 2;
  73605. this._blurKernel = 1;
  73606. this._useKernelBlur = false;
  73607. this._filter = ShadowGenerator.FILTER_NONE;
  73608. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  73609. this._contactHardeningLightSizeUVRatio = 0.1;
  73610. this._darkness = 0;
  73611. this._transparencyShadow = false;
  73612. /**
  73613. * Controls the extent to which the shadows fade out at the edge of the frustum
  73614. * Used only by directionals and spots
  73615. */
  73616. this.frustumEdgeFalloff = 0;
  73617. /**
  73618. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  73619. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  73620. * It might on the other hand introduce peter panning.
  73621. */
  73622. this.forceBackFacesOnly = false;
  73623. this._lightDirection = BABYLON.Vector3.Zero();
  73624. this._viewMatrix = BABYLON.Matrix.Zero();
  73625. this._projectionMatrix = BABYLON.Matrix.Zero();
  73626. this._transformMatrix = BABYLON.Matrix.Zero();
  73627. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  73628. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  73629. this._currentFaceIndex = 0;
  73630. this._currentFaceIndexCache = 0;
  73631. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  73632. this._mapSize = mapSize;
  73633. this._light = light;
  73634. this._scene = light.getScene();
  73635. light._shadowGenerator = this;
  73636. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  73637. if (!component) {
  73638. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  73639. this._scene._addComponent(component);
  73640. }
  73641. // Texture type fallback from float to int if not supported.
  73642. var caps = this._scene.getEngine().getCaps();
  73643. if (!useFullFloatFirst) {
  73644. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  73645. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73646. }
  73647. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  73648. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73649. }
  73650. else {
  73651. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73652. }
  73653. }
  73654. else {
  73655. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  73656. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73657. }
  73658. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  73659. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73660. }
  73661. else {
  73662. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73663. }
  73664. }
  73665. this._initializeGenerator();
  73666. this._applyFilterValues();
  73667. }
  73668. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  73669. /**
  73670. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  73671. */
  73672. get: function () {
  73673. return this._bias;
  73674. },
  73675. /**
  73676. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  73677. */
  73678. set: function (bias) {
  73679. this._bias = bias;
  73680. },
  73681. enumerable: true,
  73682. configurable: true
  73683. });
  73684. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  73685. /**
  73686. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  73687. */
  73688. get: function () {
  73689. return this._normalBias;
  73690. },
  73691. /**
  73692. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  73693. */
  73694. set: function (normalBias) {
  73695. this._normalBias = normalBias;
  73696. },
  73697. enumerable: true,
  73698. configurable: true
  73699. });
  73700. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  73701. /**
  73702. * Gets the blur box offset: offset applied during the blur pass.
  73703. * Only usefull if useKernelBlur = false
  73704. */
  73705. get: function () {
  73706. return this._blurBoxOffset;
  73707. },
  73708. /**
  73709. * Sets the blur box offset: offset applied during the blur pass.
  73710. * Only usefull if useKernelBlur = false
  73711. */
  73712. set: function (value) {
  73713. if (this._blurBoxOffset === value) {
  73714. return;
  73715. }
  73716. this._blurBoxOffset = value;
  73717. this._disposeBlurPostProcesses();
  73718. },
  73719. enumerable: true,
  73720. configurable: true
  73721. });
  73722. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  73723. /**
  73724. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  73725. * 2 means half of the size.
  73726. */
  73727. get: function () {
  73728. return this._blurScale;
  73729. },
  73730. /**
  73731. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  73732. * 2 means half of the size.
  73733. */
  73734. set: function (value) {
  73735. if (this._blurScale === value) {
  73736. return;
  73737. }
  73738. this._blurScale = value;
  73739. this._disposeBlurPostProcesses();
  73740. },
  73741. enumerable: true,
  73742. configurable: true
  73743. });
  73744. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  73745. /**
  73746. * Gets the blur kernel: kernel size of the blur pass.
  73747. * Only usefull if useKernelBlur = true
  73748. */
  73749. get: function () {
  73750. return this._blurKernel;
  73751. },
  73752. /**
  73753. * Sets the blur kernel: kernel size of the blur pass.
  73754. * Only usefull if useKernelBlur = true
  73755. */
  73756. set: function (value) {
  73757. if (this._blurKernel === value) {
  73758. return;
  73759. }
  73760. this._blurKernel = value;
  73761. this._disposeBlurPostProcesses();
  73762. },
  73763. enumerable: true,
  73764. configurable: true
  73765. });
  73766. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  73767. /**
  73768. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  73769. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  73770. */
  73771. get: function () {
  73772. return this._useKernelBlur;
  73773. },
  73774. /**
  73775. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  73776. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  73777. */
  73778. set: function (value) {
  73779. if (this._useKernelBlur === value) {
  73780. return;
  73781. }
  73782. this._useKernelBlur = value;
  73783. this._disposeBlurPostProcesses();
  73784. },
  73785. enumerable: true,
  73786. configurable: true
  73787. });
  73788. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  73789. /**
  73790. * Gets the depth scale used in ESM mode.
  73791. */
  73792. get: function () {
  73793. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  73794. },
  73795. /**
  73796. * Sets the depth scale used in ESM mode.
  73797. * This can override the scale stored on the light.
  73798. */
  73799. set: function (value) {
  73800. this._depthScale = value;
  73801. },
  73802. enumerable: true,
  73803. configurable: true
  73804. });
  73805. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  73806. /**
  73807. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  73808. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  73809. */
  73810. get: function () {
  73811. return this._filter;
  73812. },
  73813. /**
  73814. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  73815. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  73816. */
  73817. set: function (value) {
  73818. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  73819. if (this._light.needCube()) {
  73820. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  73821. this.useExponentialShadowMap = true;
  73822. return;
  73823. }
  73824. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  73825. this.useCloseExponentialShadowMap = true;
  73826. return;
  73827. }
  73828. // PCF on cubemap would also be expensive
  73829. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  73830. this.usePoissonSampling = true;
  73831. return;
  73832. }
  73833. }
  73834. // Weblg1 fallback for PCF.
  73835. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  73836. if (this._scene.getEngine().webGLVersion === 1) {
  73837. this.usePoissonSampling = true;
  73838. return;
  73839. }
  73840. }
  73841. if (this._filter === value) {
  73842. return;
  73843. }
  73844. this._filter = value;
  73845. this._disposeBlurPostProcesses();
  73846. this._applyFilterValues();
  73847. this._light._markMeshesAsLightDirty();
  73848. },
  73849. enumerable: true,
  73850. configurable: true
  73851. });
  73852. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  73853. /**
  73854. * Gets if the current filter is set to Poisson Sampling.
  73855. */
  73856. get: function () {
  73857. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  73858. },
  73859. /**
  73860. * Sets the current filter to Poisson Sampling.
  73861. */
  73862. set: function (value) {
  73863. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  73864. return;
  73865. }
  73866. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  73867. },
  73868. enumerable: true,
  73869. configurable: true
  73870. });
  73871. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  73872. /**
  73873. * Gets if the current filter is set to VSM.
  73874. * DEPRECATED. Should use useExponentialShadowMap instead.
  73875. */
  73876. get: function () {
  73877. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  73878. return this.useExponentialShadowMap;
  73879. },
  73880. /**
  73881. * Sets the current filter is to VSM.
  73882. * DEPRECATED. Should use useExponentialShadowMap instead.
  73883. */
  73884. set: function (value) {
  73885. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  73886. this.useExponentialShadowMap = value;
  73887. },
  73888. enumerable: true,
  73889. configurable: true
  73890. });
  73891. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  73892. /**
  73893. * Gets if the current filter is set to blurred VSM.
  73894. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  73895. */
  73896. get: function () {
  73897. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  73898. return this.useBlurExponentialShadowMap;
  73899. },
  73900. /**
  73901. * Sets the current filter is to blurred VSM.
  73902. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  73903. */
  73904. set: function (value) {
  73905. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  73906. this.useBlurExponentialShadowMap = value;
  73907. },
  73908. enumerable: true,
  73909. configurable: true
  73910. });
  73911. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  73912. /**
  73913. * Gets if the current filter is set to ESM.
  73914. */
  73915. get: function () {
  73916. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  73917. },
  73918. /**
  73919. * Sets the current filter is to ESM.
  73920. */
  73921. set: function (value) {
  73922. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  73923. return;
  73924. }
  73925. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73926. },
  73927. enumerable: true,
  73928. configurable: true
  73929. });
  73930. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  73931. /**
  73932. * Gets if the current filter is set to filtered ESM.
  73933. */
  73934. get: function () {
  73935. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  73936. },
  73937. /**
  73938. * Gets if the current filter is set to filtered ESM.
  73939. */
  73940. set: function (value) {
  73941. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  73942. return;
  73943. }
  73944. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73945. },
  73946. enumerable: true,
  73947. configurable: true
  73948. });
  73949. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  73950. /**
  73951. * Gets if the current filter is set to "close ESM" (using the inverse of the
  73952. * exponential to prevent steep falloff artifacts).
  73953. */
  73954. get: function () {
  73955. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  73956. },
  73957. /**
  73958. * Sets the current filter to "close ESM" (using the inverse of the
  73959. * exponential to prevent steep falloff artifacts).
  73960. */
  73961. set: function (value) {
  73962. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  73963. return;
  73964. }
  73965. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73966. },
  73967. enumerable: true,
  73968. configurable: true
  73969. });
  73970. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  73971. /**
  73972. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  73973. * exponential to prevent steep falloff artifacts).
  73974. */
  73975. get: function () {
  73976. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  73977. },
  73978. /**
  73979. * Sets the current filter to filtered "close ESM" (using the inverse of the
  73980. * exponential to prevent steep falloff artifacts).
  73981. */
  73982. set: function (value) {
  73983. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  73984. return;
  73985. }
  73986. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73987. },
  73988. enumerable: true,
  73989. configurable: true
  73990. });
  73991. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  73992. /**
  73993. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  73994. */
  73995. get: function () {
  73996. return this.filter === ShadowGenerator.FILTER_PCF;
  73997. },
  73998. /**
  73999. * Sets the current filter to "PCF" (percentage closer filtering).
  74000. */
  74001. set: function (value) {
  74002. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  74003. return;
  74004. }
  74005. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  74006. },
  74007. enumerable: true,
  74008. configurable: true
  74009. });
  74010. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  74011. /**
  74012. * Gets the PCF or PCSS Quality.
  74013. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74014. */
  74015. get: function () {
  74016. return this._filteringQuality;
  74017. },
  74018. /**
  74019. * Sets the PCF or PCSS Quality.
  74020. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74021. */
  74022. set: function (filteringQuality) {
  74023. this._filteringQuality = filteringQuality;
  74024. },
  74025. enumerable: true,
  74026. configurable: true
  74027. });
  74028. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  74029. /**
  74030. * Gets if the current filter is set to "PCSS" (contact hardening).
  74031. */
  74032. get: function () {
  74033. return this.filter === ShadowGenerator.FILTER_PCSS;
  74034. },
  74035. /**
  74036. * Sets the current filter to "PCSS" (contact hardening).
  74037. */
  74038. set: function (value) {
  74039. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  74040. return;
  74041. }
  74042. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  74043. },
  74044. enumerable: true,
  74045. configurable: true
  74046. });
  74047. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  74048. /**
  74049. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74050. * Using a ratio helps keeping shape stability independently of the map size.
  74051. *
  74052. * It does not account for the light projection as it was having too much
  74053. * instability during the light setup or during light position changes.
  74054. *
  74055. * Only valid if useContactHardeningShadow is true.
  74056. */
  74057. get: function () {
  74058. return this._contactHardeningLightSizeUVRatio;
  74059. },
  74060. /**
  74061. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74062. * Using a ratio helps keeping shape stability independently of the map size.
  74063. *
  74064. * It does not account for the light projection as it was having too much
  74065. * instability during the light setup or during light position changes.
  74066. *
  74067. * Only valid if useContactHardeningShadow is true.
  74068. */
  74069. set: function (contactHardeningLightSizeUVRatio) {
  74070. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  74071. },
  74072. enumerable: true,
  74073. configurable: true
  74074. });
  74075. /**
  74076. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  74077. * 0 means strongest and 1 would means no shadow.
  74078. * @returns the darkness.
  74079. */
  74080. ShadowGenerator.prototype.getDarkness = function () {
  74081. return this._darkness;
  74082. };
  74083. /**
  74084. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  74085. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  74086. * @returns the shadow generator allowing fluent coding.
  74087. */
  74088. ShadowGenerator.prototype.setDarkness = function (darkness) {
  74089. if (darkness >= 1.0)
  74090. this._darkness = 1.0;
  74091. else if (darkness <= 0.0)
  74092. this._darkness = 0.0;
  74093. else
  74094. this._darkness = darkness;
  74095. return this;
  74096. };
  74097. /**
  74098. * Sets the ability to have transparent shadow (boolean).
  74099. * @param transparent True if transparent else False
  74100. * @returns the shadow generator allowing fluent coding
  74101. */
  74102. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  74103. this._transparencyShadow = transparent;
  74104. return this;
  74105. };
  74106. /**
  74107. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  74108. * @returns The render target texture if present otherwise, null
  74109. */
  74110. ShadowGenerator.prototype.getShadowMap = function () {
  74111. return this._shadowMap;
  74112. };
  74113. /**
  74114. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  74115. * @returns The render target texture if the shadow map is present otherwise, null
  74116. */
  74117. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  74118. if (this._shadowMap2) {
  74119. return this._shadowMap2;
  74120. }
  74121. return this._shadowMap;
  74122. };
  74123. /**
  74124. * Helper function to add a mesh and its descendants to the list of shadow casters.
  74125. * @param mesh Mesh to add
  74126. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  74127. * @returns the Shadow Generator itself
  74128. */
  74129. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  74130. if (includeDescendants === void 0) { includeDescendants = true; }
  74131. var _a;
  74132. if (!this._shadowMap) {
  74133. return this;
  74134. }
  74135. if (!this._shadowMap.renderList) {
  74136. this._shadowMap.renderList = [];
  74137. }
  74138. this._shadowMap.renderList.push(mesh);
  74139. if (includeDescendants) {
  74140. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  74141. }
  74142. return this;
  74143. };
  74144. /**
  74145. * Helper function to remove a mesh and its descendants from the list of shadow casters
  74146. * @param mesh Mesh to remove
  74147. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  74148. * @returns the Shadow Generator itself
  74149. */
  74150. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  74151. if (includeDescendants === void 0) { includeDescendants = true; }
  74152. if (!this._shadowMap || !this._shadowMap.renderList) {
  74153. return this;
  74154. }
  74155. var index = this._shadowMap.renderList.indexOf(mesh);
  74156. if (index !== -1) {
  74157. this._shadowMap.renderList.splice(index, 1);
  74158. }
  74159. if (includeDescendants) {
  74160. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  74161. var child = _a[_i];
  74162. this.removeShadowCaster(child);
  74163. }
  74164. }
  74165. return this;
  74166. };
  74167. /**
  74168. * Returns the associated light object.
  74169. * @returns the light generating the shadow
  74170. */
  74171. ShadowGenerator.prototype.getLight = function () {
  74172. return this._light;
  74173. };
  74174. ShadowGenerator.prototype._initializeGenerator = function () {
  74175. this._light._markMeshesAsLightDirty();
  74176. this._initializeShadowMap();
  74177. };
  74178. ShadowGenerator.prototype._initializeShadowMap = function () {
  74179. var _this = this;
  74180. // Render target
  74181. var engine = this._scene.getEngine();
  74182. if (engine.webGLVersion > 1) {
  74183. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  74184. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  74185. }
  74186. else {
  74187. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  74188. }
  74189. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74190. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74191. this._shadowMap.anisotropicFilteringLevel = 1;
  74192. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74193. this._shadowMap.renderParticles = false;
  74194. this._shadowMap.ignoreCameraViewport = true;
  74195. // Record Face Index before render.
  74196. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  74197. _this._currentFaceIndex = faceIndex;
  74198. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  74199. engine.setColorWrite(false);
  74200. }
  74201. });
  74202. // Custom render function.
  74203. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  74204. // Blur if required afer render.
  74205. this._shadowMap.onAfterUnbindObservable.add(function () {
  74206. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  74207. engine.setColorWrite(true);
  74208. }
  74209. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  74210. return;
  74211. }
  74212. var shadowMap = _this.getShadowMapForRendering();
  74213. if (shadowMap) {
  74214. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  74215. }
  74216. });
  74217. // Clear according to the chosen filter.
  74218. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  74219. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  74220. this._shadowMap.onClearObservable.add(function (engine) {
  74221. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  74222. engine.clear(clearOne, false, true, false);
  74223. }
  74224. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  74225. engine.clear(clearZero, true, true, false);
  74226. }
  74227. else {
  74228. engine.clear(clearOne, true, true, false);
  74229. }
  74230. });
  74231. };
  74232. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  74233. var _this = this;
  74234. var engine = this._scene.getEngine();
  74235. var targetSize = this._mapSize / this.blurScale;
  74236. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  74237. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  74238. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74239. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74240. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74241. }
  74242. if (this.useKernelBlur) {
  74243. 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);
  74244. this._kernelBlurXPostprocess.width = targetSize;
  74245. this._kernelBlurXPostprocess.height = targetSize;
  74246. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  74247. effect.setTexture("textureSampler", _this._shadowMap);
  74248. });
  74249. 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);
  74250. this._kernelBlurXPostprocess.autoClear = false;
  74251. this._kernelBlurYPostprocess.autoClear = false;
  74252. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74253. this._kernelBlurXPostprocess.packedFloat = true;
  74254. this._kernelBlurYPostprocess.packedFloat = true;
  74255. }
  74256. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  74257. }
  74258. else {
  74259. 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);
  74260. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  74261. effect.setFloat2("screenSize", targetSize, targetSize);
  74262. effect.setTexture("textureSampler", _this._shadowMap);
  74263. });
  74264. this._boxBlurPostprocess.autoClear = false;
  74265. this._blurPostProcesses = [this._boxBlurPostprocess];
  74266. }
  74267. };
  74268. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74269. var index;
  74270. var engine = this._scene.getEngine();
  74271. if (depthOnlySubMeshes.length) {
  74272. engine.setColorWrite(false);
  74273. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74274. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  74275. }
  74276. engine.setColorWrite(true);
  74277. }
  74278. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74279. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  74280. }
  74281. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74282. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  74283. }
  74284. if (this._transparencyShadow) {
  74285. for (index = 0; index < transparentSubMeshes.length; index++) {
  74286. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  74287. }
  74288. }
  74289. };
  74290. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  74291. var _this = this;
  74292. var mesh = subMesh.getRenderingMesh();
  74293. var scene = this._scene;
  74294. var engine = scene.getEngine();
  74295. var material = subMesh.getMaterial();
  74296. if (!material) {
  74297. return;
  74298. }
  74299. // Culling
  74300. engine.setState(material.backFaceCulling);
  74301. // Managing instances
  74302. var batch = mesh._getInstancesRenderList(subMesh._id);
  74303. if (batch.mustReturn) {
  74304. return;
  74305. }
  74306. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  74307. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  74308. engine.enableEffect(this._effect);
  74309. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  74310. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  74311. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  74312. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  74313. this._effect.setVector3("lightData", this._cachedDirection);
  74314. }
  74315. else {
  74316. this._effect.setVector3("lightData", this._cachedPosition);
  74317. }
  74318. if (scene.activeCamera) {
  74319. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  74320. }
  74321. // Alpha test
  74322. if (material && material.needAlphaTesting()) {
  74323. var alphaTexture = material.getAlphaTestTexture();
  74324. if (alphaTexture) {
  74325. this._effect.setTexture("diffuseSampler", alphaTexture);
  74326. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  74327. }
  74328. }
  74329. // Bones
  74330. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74331. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  74332. }
  74333. // Morph targets
  74334. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  74335. if (this.forceBackFacesOnly) {
  74336. engine.setState(true, 0, false, true);
  74337. }
  74338. // Draw
  74339. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74340. if (this.forceBackFacesOnly) {
  74341. engine.setState(true, 0, false, false);
  74342. }
  74343. }
  74344. else {
  74345. // Need to reset refresh rate of the shadowMap
  74346. if (this._shadowMap) {
  74347. this._shadowMap.resetRefreshCounter();
  74348. }
  74349. }
  74350. };
  74351. ShadowGenerator.prototype._applyFilterValues = function () {
  74352. if (!this._shadowMap) {
  74353. return;
  74354. }
  74355. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  74356. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  74357. }
  74358. else {
  74359. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74360. }
  74361. };
  74362. /**
  74363. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  74364. * @param onCompiled Callback triggered at the and of the effects compilation
  74365. * @param options Sets of optional options forcing the compilation with different modes
  74366. */
  74367. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  74368. var _this = this;
  74369. var localOptions = __assign({ useInstances: false }, options);
  74370. var shadowMap = this.getShadowMap();
  74371. if (!shadowMap) {
  74372. if (onCompiled) {
  74373. onCompiled(this);
  74374. }
  74375. return;
  74376. }
  74377. var renderList = shadowMap.renderList;
  74378. if (!renderList) {
  74379. if (onCompiled) {
  74380. onCompiled(this);
  74381. }
  74382. return;
  74383. }
  74384. var subMeshes = new Array();
  74385. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  74386. var mesh = renderList_1[_i];
  74387. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  74388. }
  74389. if (subMeshes.length === 0) {
  74390. if (onCompiled) {
  74391. onCompiled(this);
  74392. }
  74393. return;
  74394. }
  74395. var currentIndex = 0;
  74396. var checkReady = function () {
  74397. if (!_this._scene || !_this._scene.getEngine()) {
  74398. return;
  74399. }
  74400. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  74401. currentIndex++;
  74402. if (currentIndex >= subMeshes.length) {
  74403. if (onCompiled) {
  74404. onCompiled(_this);
  74405. }
  74406. return;
  74407. }
  74408. }
  74409. setTimeout(checkReady, 16);
  74410. };
  74411. checkReady();
  74412. };
  74413. /**
  74414. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  74415. * @param options Sets of optional options forcing the compilation with different modes
  74416. * @returns A promise that resolves when the compilation completes
  74417. */
  74418. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  74419. var _this = this;
  74420. return new Promise(function (resolve) {
  74421. _this.forceCompilation(function () {
  74422. resolve();
  74423. }, options);
  74424. });
  74425. };
  74426. /**
  74427. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  74428. * @param subMesh The submesh we want to render in the shadow map
  74429. * @param useInstances Defines wether will draw in the map using instances
  74430. * @returns true if ready otherwise, false
  74431. */
  74432. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  74433. var defines = [];
  74434. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74435. defines.push("#define FLOAT");
  74436. }
  74437. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  74438. defines.push("#define ESM");
  74439. }
  74440. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  74441. defines.push("#define DEPTHTEXTURE");
  74442. }
  74443. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74444. var mesh = subMesh.getMesh();
  74445. var material = subMesh.getMaterial();
  74446. // Normal bias.
  74447. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  74448. attribs.push(BABYLON.VertexBuffer.NormalKind);
  74449. defines.push("#define NORMAL");
  74450. if (mesh.nonUniformScaling) {
  74451. defines.push("#define NONUNIFORMSCALING");
  74452. }
  74453. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  74454. defines.push("#define DIRECTIONINLIGHTDATA");
  74455. }
  74456. }
  74457. // Alpha test
  74458. if (material && material.needAlphaTesting()) {
  74459. var alphaTexture = material.getAlphaTestTexture();
  74460. if (alphaTexture) {
  74461. defines.push("#define ALPHATEST");
  74462. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74463. attribs.push(BABYLON.VertexBuffer.UVKind);
  74464. defines.push("#define UV1");
  74465. }
  74466. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74467. if (alphaTexture.coordinatesIndex === 1) {
  74468. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74469. defines.push("#define UV2");
  74470. }
  74471. }
  74472. }
  74473. }
  74474. // Bones
  74475. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74476. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74477. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74478. if (mesh.numBoneInfluencers > 4) {
  74479. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74480. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74481. }
  74482. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74483. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  74484. }
  74485. else {
  74486. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74487. }
  74488. // Morph targets
  74489. var manager = mesh.morphTargetManager;
  74490. var morphInfluencers = 0;
  74491. if (manager) {
  74492. if (manager.numInfluencers > 0) {
  74493. defines.push("#define MORPHTARGETS");
  74494. morphInfluencers = manager.numInfluencers;
  74495. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  74496. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  74497. }
  74498. }
  74499. // Instances
  74500. if (useInstances) {
  74501. defines.push("#define INSTANCES");
  74502. attribs.push("world0");
  74503. attribs.push("world1");
  74504. attribs.push("world2");
  74505. attribs.push("world3");
  74506. }
  74507. // Get correct effect
  74508. var join = defines.join("\n");
  74509. if (this._cachedDefines !== join) {
  74510. this._cachedDefines = join;
  74511. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  74512. }
  74513. if (!this._effect.isReady()) {
  74514. return false;
  74515. }
  74516. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  74517. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  74518. this._initializeBlurRTTAndPostProcesses();
  74519. }
  74520. }
  74521. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  74522. return false;
  74523. }
  74524. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  74525. return false;
  74526. }
  74527. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  74528. return false;
  74529. }
  74530. return true;
  74531. };
  74532. /**
  74533. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  74534. * @param defines Defines of the material we want to update
  74535. * @param lightIndex Index of the light in the enabled light list of the material
  74536. */
  74537. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  74538. var scene = this._scene;
  74539. var light = this._light;
  74540. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  74541. return;
  74542. }
  74543. defines["SHADOW" + lightIndex] = true;
  74544. if (this.useContactHardeningShadow) {
  74545. defines["SHADOWPCSS" + lightIndex] = true;
  74546. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  74547. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  74548. }
  74549. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  74550. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  74551. }
  74552. // else default to high.
  74553. }
  74554. if (this.usePercentageCloserFiltering) {
  74555. defines["SHADOWPCF" + lightIndex] = true;
  74556. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  74557. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  74558. }
  74559. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  74560. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  74561. }
  74562. // else default to high.
  74563. }
  74564. else if (this.usePoissonSampling) {
  74565. defines["SHADOWPOISSON" + lightIndex] = true;
  74566. }
  74567. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  74568. defines["SHADOWESM" + lightIndex] = true;
  74569. }
  74570. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  74571. defines["SHADOWCLOSEESM" + lightIndex] = true;
  74572. }
  74573. if (light.needCube()) {
  74574. defines["SHADOWCUBE" + lightIndex] = true;
  74575. }
  74576. };
  74577. /**
  74578. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  74579. * defined in the generator but impacting the effect).
  74580. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  74581. * @param effect The effect we are binfing the information for
  74582. */
  74583. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  74584. var light = this._light;
  74585. var scene = this._scene;
  74586. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  74587. return;
  74588. }
  74589. var camera = scene.activeCamera;
  74590. if (!camera) {
  74591. return;
  74592. }
  74593. var shadowMap = this.getShadowMap();
  74594. if (!shadowMap) {
  74595. return;
  74596. }
  74597. if (!light.needCube()) {
  74598. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  74599. }
  74600. // Only PCF uses depth stencil texture.
  74601. if (this._filter === ShadowGenerator.FILTER_PCF) {
  74602. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74603. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  74604. }
  74605. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  74606. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74607. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  74608. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  74609. }
  74610. else {
  74611. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74612. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  74613. }
  74614. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  74615. };
  74616. /**
  74617. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  74618. * (eq to shadow prjection matrix * light transform matrix)
  74619. * @returns The transform matrix used to create the shadow map
  74620. */
  74621. ShadowGenerator.prototype.getTransformMatrix = function () {
  74622. var scene = this._scene;
  74623. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  74624. return this._transformMatrix;
  74625. }
  74626. this._currentRenderID = scene.getRenderId();
  74627. this._currentFaceIndexCache = this._currentFaceIndex;
  74628. var lightPosition = this._light.position;
  74629. if (this._light.computeTransformedInformation()) {
  74630. lightPosition = this._light.transformedPosition;
  74631. }
  74632. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  74633. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  74634. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  74635. }
  74636. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  74637. this._cachedPosition.copyFrom(lightPosition);
  74638. this._cachedDirection.copyFrom(this._lightDirection);
  74639. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  74640. var shadowMap = this.getShadowMap();
  74641. if (shadowMap) {
  74642. var renderList = shadowMap.renderList;
  74643. if (renderList) {
  74644. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  74645. }
  74646. }
  74647. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  74648. }
  74649. return this._transformMatrix;
  74650. };
  74651. /**
  74652. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  74653. * Cube and 2D textures for instance.
  74654. */
  74655. ShadowGenerator.prototype.recreateShadowMap = function () {
  74656. var shadowMap = this._shadowMap;
  74657. if (!shadowMap) {
  74658. return;
  74659. }
  74660. // Track render list.
  74661. var renderList = shadowMap.renderList;
  74662. // Clean up existing data.
  74663. this._disposeRTTandPostProcesses();
  74664. // Reinitializes.
  74665. this._initializeGenerator();
  74666. // Reaffect the filter to ensure a correct fallback if necessary.
  74667. this.filter = this.filter;
  74668. // Reaffect the filter.
  74669. this._applyFilterValues();
  74670. // Reaffect Render List.
  74671. this._shadowMap.renderList = renderList;
  74672. };
  74673. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  74674. if (this._shadowMap2) {
  74675. this._shadowMap2.dispose();
  74676. this._shadowMap2 = null;
  74677. }
  74678. if (this._boxBlurPostprocess) {
  74679. this._boxBlurPostprocess.dispose();
  74680. this._boxBlurPostprocess = null;
  74681. }
  74682. if (this._kernelBlurXPostprocess) {
  74683. this._kernelBlurXPostprocess.dispose();
  74684. this._kernelBlurXPostprocess = null;
  74685. }
  74686. if (this._kernelBlurYPostprocess) {
  74687. this._kernelBlurYPostprocess.dispose();
  74688. this._kernelBlurYPostprocess = null;
  74689. }
  74690. this._blurPostProcesses = [];
  74691. };
  74692. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  74693. if (this._shadowMap) {
  74694. this._shadowMap.dispose();
  74695. this._shadowMap = null;
  74696. }
  74697. this._disposeBlurPostProcesses();
  74698. };
  74699. /**
  74700. * Disposes the ShadowGenerator.
  74701. * Returns nothing.
  74702. */
  74703. ShadowGenerator.prototype.dispose = function () {
  74704. this._disposeRTTandPostProcesses();
  74705. if (this._light) {
  74706. this._light._shadowGenerator = null;
  74707. this._light._markMeshesAsLightDirty();
  74708. }
  74709. };
  74710. /**
  74711. * Serializes the shadow generator setup to a json object.
  74712. * @returns The serialized JSON object
  74713. */
  74714. ShadowGenerator.prototype.serialize = function () {
  74715. var serializationObject = {};
  74716. var shadowMap = this.getShadowMap();
  74717. if (!shadowMap) {
  74718. return serializationObject;
  74719. }
  74720. serializationObject.lightId = this._light.id;
  74721. serializationObject.mapSize = shadowMap.getRenderSize();
  74722. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  74723. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  74724. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  74725. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  74726. serializationObject.usePoissonSampling = this.usePoissonSampling;
  74727. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  74728. serializationObject.depthScale = this.depthScale;
  74729. serializationObject.darkness = this.getDarkness();
  74730. serializationObject.blurBoxOffset = this.blurBoxOffset;
  74731. serializationObject.blurKernel = this.blurKernel;
  74732. serializationObject.blurScale = this.blurScale;
  74733. serializationObject.useKernelBlur = this.useKernelBlur;
  74734. serializationObject.transparencyShadow = this._transparencyShadow;
  74735. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  74736. serializationObject.bias = this.bias;
  74737. serializationObject.normalBias = this.normalBias;
  74738. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  74739. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  74740. serializationObject.filteringQuality = this.filteringQuality;
  74741. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  74742. serializationObject.renderList = [];
  74743. if (shadowMap.renderList) {
  74744. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  74745. var mesh = shadowMap.renderList[meshIndex];
  74746. serializationObject.renderList.push(mesh.id);
  74747. }
  74748. }
  74749. return serializationObject;
  74750. };
  74751. /**
  74752. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  74753. * @param parsedShadowGenerator The JSON object to parse
  74754. * @param scene The scene to create the shadow map for
  74755. * @returns The parsed shadow generator
  74756. */
  74757. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  74758. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  74759. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  74760. var shadowMap = shadowGenerator.getShadowMap();
  74761. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  74762. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  74763. meshes.forEach(function (mesh) {
  74764. if (!shadowMap) {
  74765. return;
  74766. }
  74767. if (!shadowMap.renderList) {
  74768. shadowMap.renderList = [];
  74769. }
  74770. shadowMap.renderList.push(mesh);
  74771. });
  74772. }
  74773. if (parsedShadowGenerator.usePoissonSampling) {
  74774. shadowGenerator.usePoissonSampling = true;
  74775. }
  74776. else if (parsedShadowGenerator.useExponentialShadowMap) {
  74777. shadowGenerator.useExponentialShadowMap = true;
  74778. }
  74779. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  74780. shadowGenerator.useBlurExponentialShadowMap = true;
  74781. }
  74782. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  74783. shadowGenerator.useCloseExponentialShadowMap = true;
  74784. }
  74785. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  74786. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  74787. }
  74788. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  74789. shadowGenerator.usePercentageCloserFiltering = true;
  74790. }
  74791. else if (parsedShadowGenerator.useContactHardeningShadow) {
  74792. shadowGenerator.useContactHardeningShadow = true;
  74793. }
  74794. if (parsedShadowGenerator.filteringQuality) {
  74795. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  74796. }
  74797. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  74798. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  74799. }
  74800. // Backward compat
  74801. else if (parsedShadowGenerator.useVarianceShadowMap) {
  74802. shadowGenerator.useExponentialShadowMap = true;
  74803. }
  74804. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  74805. shadowGenerator.useBlurExponentialShadowMap = true;
  74806. }
  74807. if (parsedShadowGenerator.depthScale) {
  74808. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  74809. }
  74810. if (parsedShadowGenerator.blurScale) {
  74811. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  74812. }
  74813. if (parsedShadowGenerator.blurBoxOffset) {
  74814. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  74815. }
  74816. if (parsedShadowGenerator.useKernelBlur) {
  74817. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  74818. }
  74819. if (parsedShadowGenerator.blurKernel) {
  74820. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  74821. }
  74822. if (parsedShadowGenerator.bias !== undefined) {
  74823. shadowGenerator.bias = parsedShadowGenerator.bias;
  74824. }
  74825. if (parsedShadowGenerator.normalBias !== undefined) {
  74826. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  74827. }
  74828. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  74829. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  74830. }
  74831. if (parsedShadowGenerator.darkness) {
  74832. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  74833. }
  74834. if (parsedShadowGenerator.transparencyShadow) {
  74835. shadowGenerator.setTransparencyShadow(true);
  74836. }
  74837. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  74838. return shadowGenerator;
  74839. };
  74840. /**
  74841. * Shadow generator mode None: no filtering applied.
  74842. */
  74843. ShadowGenerator.FILTER_NONE = 0;
  74844. /**
  74845. * Shadow generator mode ESM: Exponential Shadow Mapping.
  74846. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74847. */
  74848. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  74849. /**
  74850. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  74851. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  74852. */
  74853. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  74854. /**
  74855. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  74856. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74857. */
  74858. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  74859. /**
  74860. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  74861. * edge artifacts on steep falloff.
  74862. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74863. */
  74864. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  74865. /**
  74866. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  74867. * edge artifacts on steep falloff.
  74868. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74869. */
  74870. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  74871. /**
  74872. * Shadow generator mode PCF: Percentage Closer Filtering
  74873. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  74874. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  74875. */
  74876. ShadowGenerator.FILTER_PCF = 6;
  74877. /**
  74878. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  74879. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  74880. * Contact Hardening
  74881. */
  74882. ShadowGenerator.FILTER_PCSS = 7;
  74883. /**
  74884. * Reserved for PCF and PCSS
  74885. * Highest Quality.
  74886. *
  74887. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  74888. *
  74889. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  74890. */
  74891. ShadowGenerator.QUALITY_HIGH = 0;
  74892. /**
  74893. * Reserved for PCF and PCSS
  74894. * Good tradeoff for quality/perf cross devices
  74895. *
  74896. * Execute PCF on a 3*3 kernel.
  74897. *
  74898. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  74899. */
  74900. ShadowGenerator.QUALITY_MEDIUM = 1;
  74901. /**
  74902. * Reserved for PCF and PCSS
  74903. * The lowest quality but the fastest.
  74904. *
  74905. * Execute PCF on a 1*1 kernel.
  74906. *
  74907. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  74908. */
  74909. ShadowGenerator.QUALITY_LOW = 2;
  74910. return ShadowGenerator;
  74911. }());
  74912. BABYLON.ShadowGenerator = ShadowGenerator;
  74913. })(BABYLON || (BABYLON = {}));
  74914. //# sourceMappingURL=babylon.shadowGenerator.js.map
  74915. var BABYLON;
  74916. (function (BABYLON) {
  74917. // Adds the parser to the scene parsers.
  74918. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  74919. // Shadows
  74920. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  74921. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  74922. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  74923. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  74924. // SG would be available on their associated lights
  74925. }
  74926. }
  74927. });
  74928. /**
  74929. * Defines the shadow generator component responsible to manage any shadow generators
  74930. * in a given scene.
  74931. */
  74932. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  74933. /**
  74934. * Creates a new instance of the component for the given scene
  74935. * @param scene Defines the scene to register the component in
  74936. */
  74937. function ShadowGeneratorSceneComponent(scene) {
  74938. /**
  74939. * The component name helpfull to identify the component in the list of scene components.
  74940. */
  74941. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  74942. this.scene = scene;
  74943. }
  74944. /**
  74945. * Registers the component in a given scene
  74946. */
  74947. ShadowGeneratorSceneComponent.prototype.register = function () {
  74948. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  74949. };
  74950. /**
  74951. * Rebuilds the elements related to this component in case of
  74952. * context lost for instance.
  74953. */
  74954. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  74955. // Nothing To Do Here.
  74956. };
  74957. /**
  74958. * Serializes the component data to the specified json object
  74959. * @param serializationObject The object to serialize to
  74960. */
  74961. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  74962. // Shadows
  74963. serializationObject.shadowGenerators = [];
  74964. var lights = this.scene.lights;
  74965. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  74966. var light = lights_1[_i];
  74967. var shadowGenerator = light.getShadowGenerator();
  74968. if (shadowGenerator) {
  74969. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  74970. }
  74971. }
  74972. };
  74973. /**
  74974. * Adds all the element from the container to the scene
  74975. * @param container the container holding the elements
  74976. */
  74977. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  74978. // Nothing To Do Here. (directly attached to a light)
  74979. };
  74980. /**
  74981. * Removes all the elements in the container from the scene
  74982. * @param container contains the elements to remove
  74983. */
  74984. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  74985. // Nothing To Do Here. (directly attached to a light)
  74986. };
  74987. /**
  74988. * Rebuilds the elements related to this component in case of
  74989. * context lost for instance.
  74990. */
  74991. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  74992. // Nothing To Do Here.
  74993. };
  74994. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  74995. // Shadows
  74996. var scene = this.scene;
  74997. if (this.scene.shadowsEnabled) {
  74998. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  74999. var light = scene.lights[lightIndex];
  75000. var shadowGenerator = light.getShadowGenerator();
  75001. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  75002. var shadowMap = (shadowGenerator.getShadowMap());
  75003. if (scene.textures.indexOf(shadowMap) !== -1) {
  75004. renderTargets.push(shadowMap);
  75005. }
  75006. }
  75007. }
  75008. }
  75009. };
  75010. return ShadowGeneratorSceneComponent;
  75011. }());
  75012. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  75013. })(BABYLON || (BABYLON = {}));
  75014. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  75015. var BABYLON;
  75016. (function (BABYLON) {
  75017. var DefaultLoadingScreen = /** @class */ (function () {
  75018. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  75019. if (_loadingText === void 0) { _loadingText = ""; }
  75020. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  75021. var _this = this;
  75022. this._renderingCanvas = _renderingCanvas;
  75023. this._loadingText = _loadingText;
  75024. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  75025. // Resize
  75026. this._resizeLoadingUI = function () {
  75027. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  75028. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  75029. if (!_this._loadingDiv) {
  75030. return;
  75031. }
  75032. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  75033. _this._loadingDiv.style.left = canvasRect.left + "px";
  75034. _this._loadingDiv.style.top = canvasRect.top + "px";
  75035. _this._loadingDiv.style.width = canvasRect.width + "px";
  75036. _this._loadingDiv.style.height = canvasRect.height + "px";
  75037. };
  75038. }
  75039. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  75040. if (this._loadingDiv) {
  75041. // Do not add a loading screen if there is already one
  75042. return;
  75043. }
  75044. this._loadingDiv = document.createElement("div");
  75045. this._loadingDiv.id = "babylonjsLoadingDiv";
  75046. this._loadingDiv.style.opacity = "0";
  75047. this._loadingDiv.style.transition = "opacity 1.5s ease";
  75048. this._loadingDiv.style.pointerEvents = "none";
  75049. // Loading text
  75050. this._loadingTextDiv = document.createElement("div");
  75051. this._loadingTextDiv.style.position = "absolute";
  75052. this._loadingTextDiv.style.left = "0";
  75053. this._loadingTextDiv.style.top = "50%";
  75054. this._loadingTextDiv.style.marginTop = "80px";
  75055. this._loadingTextDiv.style.width = "100%";
  75056. this._loadingTextDiv.style.height = "20px";
  75057. this._loadingTextDiv.style.fontFamily = "Arial";
  75058. this._loadingTextDiv.style.fontSize = "14px";
  75059. this._loadingTextDiv.style.color = "white";
  75060. this._loadingTextDiv.style.textAlign = "center";
  75061. this._loadingTextDiv.innerHTML = "Loading";
  75062. this._loadingDiv.appendChild(this._loadingTextDiv);
  75063. //set the predefined text
  75064. this._loadingTextDiv.innerHTML = this._loadingText;
  75065. // Generating keyframes
  75066. var style = document.createElement('style');
  75067. style.type = 'text/css';
  75068. 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 }";
  75069. style.innerHTML = keyFrames;
  75070. document.getElementsByTagName('head')[0].appendChild(style);
  75071. // Loading img
  75072. var imgBack = new Image();
  75073. 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";
  75074. imgBack.style.position = "absolute";
  75075. imgBack.style.left = "50%";
  75076. imgBack.style.top = "50%";
  75077. imgBack.style.marginLeft = "-60px";
  75078. imgBack.style.marginTop = "-60px";
  75079. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  75080. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  75081. imgBack.style.transformOrigin = "50% 50%";
  75082. imgBack.style.webkitTransformOrigin = "50% 50%";
  75083. this._loadingDiv.appendChild(imgBack);
  75084. this._resizeLoadingUI();
  75085. window.addEventListener("resize", this._resizeLoadingUI);
  75086. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75087. document.body.appendChild(this._loadingDiv);
  75088. this._loadingDiv.style.opacity = "1";
  75089. };
  75090. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  75091. var _this = this;
  75092. if (!this._loadingDiv) {
  75093. return;
  75094. }
  75095. var onTransitionEnd = function () {
  75096. if (!_this._loadingDiv) {
  75097. return;
  75098. }
  75099. document.body.removeChild(_this._loadingDiv);
  75100. window.removeEventListener("resize", _this._resizeLoadingUI);
  75101. _this._loadingDiv = null;
  75102. };
  75103. this._loadingDiv.style.opacity = "0";
  75104. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  75105. };
  75106. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  75107. set: function (text) {
  75108. this._loadingText = text;
  75109. if (this._loadingTextDiv) {
  75110. this._loadingTextDiv.innerHTML = this._loadingText;
  75111. }
  75112. },
  75113. enumerable: true,
  75114. configurable: true
  75115. });
  75116. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  75117. get: function () {
  75118. return this._loadingDivBackgroundColor;
  75119. },
  75120. set: function (color) {
  75121. this._loadingDivBackgroundColor = color;
  75122. if (!this._loadingDiv) {
  75123. return;
  75124. }
  75125. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75126. },
  75127. enumerable: true,
  75128. configurable: true
  75129. });
  75130. return DefaultLoadingScreen;
  75131. }());
  75132. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  75133. })(BABYLON || (BABYLON = {}));
  75134. //# sourceMappingURL=babylon.loadingScreen.js.map
  75135. var BABYLON;
  75136. (function (BABYLON) {
  75137. var SceneLoaderProgressEvent = /** @class */ (function () {
  75138. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  75139. this.lengthComputable = lengthComputable;
  75140. this.loaded = loaded;
  75141. this.total = total;
  75142. }
  75143. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  75144. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  75145. };
  75146. return SceneLoaderProgressEvent;
  75147. }());
  75148. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  75149. var SceneLoader = /** @class */ (function () {
  75150. function SceneLoader() {
  75151. }
  75152. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  75153. get: function () {
  75154. return 0;
  75155. },
  75156. enumerable: true,
  75157. configurable: true
  75158. });
  75159. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  75160. get: function () {
  75161. return 1;
  75162. },
  75163. enumerable: true,
  75164. configurable: true
  75165. });
  75166. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  75167. get: function () {
  75168. return 2;
  75169. },
  75170. enumerable: true,
  75171. configurable: true
  75172. });
  75173. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  75174. get: function () {
  75175. return 3;
  75176. },
  75177. enumerable: true,
  75178. configurable: true
  75179. });
  75180. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  75181. get: function () {
  75182. return SceneLoader._ForceFullSceneLoadingForIncremental;
  75183. },
  75184. set: function (value) {
  75185. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  75186. },
  75187. enumerable: true,
  75188. configurable: true
  75189. });
  75190. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  75191. get: function () {
  75192. return SceneLoader._ShowLoadingScreen;
  75193. },
  75194. set: function (value) {
  75195. SceneLoader._ShowLoadingScreen = value;
  75196. },
  75197. enumerable: true,
  75198. configurable: true
  75199. });
  75200. Object.defineProperty(SceneLoader, "loggingLevel", {
  75201. get: function () {
  75202. return SceneLoader._loggingLevel;
  75203. },
  75204. set: function (value) {
  75205. SceneLoader._loggingLevel = value;
  75206. },
  75207. enumerable: true,
  75208. configurable: true
  75209. });
  75210. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  75211. get: function () {
  75212. return SceneLoader._CleanBoneMatrixWeights;
  75213. },
  75214. set: function (value) {
  75215. SceneLoader._CleanBoneMatrixWeights = value;
  75216. },
  75217. enumerable: true,
  75218. configurable: true
  75219. });
  75220. SceneLoader._getDefaultPlugin = function () {
  75221. return SceneLoader._registeredPlugins[".babylon"];
  75222. };
  75223. SceneLoader._getPluginForExtension = function (extension) {
  75224. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  75225. if (registeredPlugin) {
  75226. return registeredPlugin;
  75227. }
  75228. 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");
  75229. return SceneLoader._getDefaultPlugin();
  75230. };
  75231. SceneLoader._getPluginForDirectLoad = function (data) {
  75232. for (var extension in SceneLoader._registeredPlugins) {
  75233. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  75234. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  75235. return SceneLoader._registeredPlugins[extension];
  75236. }
  75237. }
  75238. return SceneLoader._getDefaultPlugin();
  75239. };
  75240. SceneLoader._getPluginForFilename = function (sceneFilename) {
  75241. var queryStringPosition = sceneFilename.indexOf("?");
  75242. if (queryStringPosition !== -1) {
  75243. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  75244. }
  75245. var dotPosition = sceneFilename.lastIndexOf(".");
  75246. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  75247. return SceneLoader._getPluginForExtension(extension);
  75248. };
  75249. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  75250. SceneLoader._getDirectLoad = function (sceneFilename) {
  75251. if (sceneFilename.substr(0, 5) === "data:") {
  75252. return sceneFilename.substr(5);
  75253. }
  75254. return null;
  75255. };
  75256. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  75257. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  75258. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  75259. var plugin;
  75260. if (registeredPlugin.plugin.createPlugin) {
  75261. plugin = registeredPlugin.plugin.createPlugin();
  75262. }
  75263. else {
  75264. plugin = registeredPlugin.plugin;
  75265. }
  75266. var useArrayBuffer = registeredPlugin.isBinary;
  75267. var database;
  75268. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  75269. var dataCallback = function (data, responseURL) {
  75270. if (scene.isDisposed) {
  75271. onError("Scene has been disposed");
  75272. return;
  75273. }
  75274. scene.database = database;
  75275. onSuccess(plugin, data, responseURL);
  75276. };
  75277. var request = null;
  75278. var pluginDisposed = false;
  75279. var onDisposeObservable = plugin.onDisposeObservable;
  75280. if (onDisposeObservable) {
  75281. onDisposeObservable.add(function () {
  75282. pluginDisposed = true;
  75283. if (request) {
  75284. request.abort();
  75285. request = null;
  75286. }
  75287. onDispose();
  75288. });
  75289. }
  75290. var manifestChecked = function () {
  75291. if (pluginDisposed) {
  75292. return;
  75293. }
  75294. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  75295. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  75296. } : undefined, database, useArrayBuffer, function (request, exception) {
  75297. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  75298. });
  75299. };
  75300. if (directLoad) {
  75301. dataCallback(directLoad);
  75302. return plugin;
  75303. }
  75304. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  75305. var engine = scene.getEngine();
  75306. var canUseOfflineSupport = engine.enableOfflineSupport;
  75307. if (canUseOfflineSupport) {
  75308. // Also check for exceptions
  75309. var exceptionFound = false;
  75310. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  75311. var regex = _a[_i];
  75312. if (regex.test(fileInfo.url)) {
  75313. exceptionFound = true;
  75314. break;
  75315. }
  75316. }
  75317. canUseOfflineSupport = !exceptionFound;
  75318. }
  75319. if (canUseOfflineSupport) {
  75320. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  75321. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  75322. }
  75323. else {
  75324. manifestChecked();
  75325. }
  75326. }
  75327. // Loading file from disk via input file or drag'n'drop
  75328. else {
  75329. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  75330. if (file) {
  75331. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  75332. }
  75333. else {
  75334. onError("Unable to find file named " + fileInfo.name);
  75335. }
  75336. }
  75337. return plugin;
  75338. };
  75339. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  75340. var url;
  75341. var name;
  75342. if (!sceneFilename) {
  75343. url = rootUrl;
  75344. name = BABYLON.Tools.GetFilename(rootUrl);
  75345. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  75346. }
  75347. else {
  75348. if (sceneFilename.substr(0, 1) === "/") {
  75349. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  75350. return null;
  75351. }
  75352. url = rootUrl + sceneFilename;
  75353. name = sceneFilename;
  75354. }
  75355. ;
  75356. return {
  75357. url: url,
  75358. rootUrl: rootUrl,
  75359. name: name
  75360. };
  75361. };
  75362. // Public functions
  75363. SceneLoader.GetPluginForExtension = function (extension) {
  75364. return SceneLoader._getPluginForExtension(extension).plugin;
  75365. };
  75366. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  75367. return !!SceneLoader._registeredPlugins[extension];
  75368. };
  75369. SceneLoader.RegisterPlugin = function (plugin) {
  75370. if (typeof plugin.extensions === "string") {
  75371. var extension = plugin.extensions;
  75372. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  75373. plugin: plugin,
  75374. isBinary: false
  75375. };
  75376. }
  75377. else {
  75378. var extensions = plugin.extensions;
  75379. Object.keys(extensions).forEach(function (extension) {
  75380. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  75381. plugin: plugin,
  75382. isBinary: extensions[extension].isBinary
  75383. };
  75384. });
  75385. }
  75386. };
  75387. /**
  75388. * Import meshes into a scene
  75389. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  75390. * @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)
  75391. * @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)
  75392. * @param scene the instance of BABYLON.Scene to append to
  75393. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  75394. * @param onProgress a callback with a progress event for each file being loaded
  75395. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75396. * @param pluginExtension the extension used to determine the plugin
  75397. * @returns The loaded plugin
  75398. */
  75399. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75400. if (sceneFilename === void 0) { sceneFilename = ""; }
  75401. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75402. if (onSuccess === void 0) { onSuccess = null; }
  75403. if (onProgress === void 0) { onProgress = null; }
  75404. if (onError === void 0) { onError = null; }
  75405. if (pluginExtension === void 0) { pluginExtension = null; }
  75406. if (!scene) {
  75407. BABYLON.Tools.Error("No scene available to import mesh to");
  75408. return null;
  75409. }
  75410. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75411. if (!fileInfo) {
  75412. return null;
  75413. }
  75414. var loadingToken = {};
  75415. scene._addPendingData(loadingToken);
  75416. var disposeHandler = function () {
  75417. scene._removePendingData(loadingToken);
  75418. };
  75419. var errorHandler = function (message, exception) {
  75420. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  75421. if (onError) {
  75422. onError(scene, errorMessage, exception);
  75423. }
  75424. else {
  75425. BABYLON.Tools.Error(errorMessage);
  75426. // should the exception be thrown?
  75427. }
  75428. disposeHandler();
  75429. };
  75430. var progressHandler = onProgress ? function (event) {
  75431. try {
  75432. onProgress(event);
  75433. }
  75434. catch (e) {
  75435. errorHandler("Error in onProgress callback", e);
  75436. }
  75437. } : undefined;
  75438. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  75439. scene.importedMeshesFiles.push(fileInfo.url);
  75440. if (onSuccess) {
  75441. try {
  75442. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  75443. }
  75444. catch (e) {
  75445. errorHandler("Error in onSuccess callback", e);
  75446. }
  75447. }
  75448. scene._removePendingData(loadingToken);
  75449. };
  75450. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75451. if (plugin.rewriteRootURL) {
  75452. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  75453. }
  75454. if (plugin.importMesh) {
  75455. var syncedPlugin = plugin;
  75456. var meshes = new Array();
  75457. var particleSystems = new Array();
  75458. var skeletons = new Array();
  75459. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  75460. return;
  75461. }
  75462. scene.loadingPluginName = plugin.name;
  75463. successHandler(meshes, particleSystems, skeletons, []);
  75464. }
  75465. else {
  75466. var asyncedPlugin = plugin;
  75467. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  75468. scene.loadingPluginName = plugin.name;
  75469. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  75470. }).catch(function (error) {
  75471. errorHandler(error.message, error);
  75472. });
  75473. }
  75474. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75475. };
  75476. /**
  75477. * Import meshes into a scene
  75478. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  75479. * @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)
  75480. * @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)
  75481. * @param scene the instance of BABYLON.Scene to append to
  75482. * @param onProgress a callback with a progress event for each file being loaded
  75483. * @param pluginExtension the extension used to determine the plugin
  75484. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  75485. */
  75486. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75487. if (sceneFilename === void 0) { sceneFilename = ""; }
  75488. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75489. if (onProgress === void 0) { onProgress = null; }
  75490. if (pluginExtension === void 0) { pluginExtension = null; }
  75491. return new Promise(function (resolve, reject) {
  75492. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  75493. resolve({
  75494. meshes: meshes,
  75495. particleSystems: particleSystems,
  75496. skeletons: skeletons,
  75497. animationGroups: animationGroups
  75498. });
  75499. }, onProgress, function (scene, message, exception) {
  75500. reject(exception || new Error(message));
  75501. }, pluginExtension);
  75502. });
  75503. };
  75504. /**
  75505. * Load a scene
  75506. * @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)
  75507. * @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)
  75508. * @param engine is the instance of BABYLON.Engine to use to create the scene
  75509. * @param onSuccess a callback with the scene when import succeeds
  75510. * @param onProgress a callback with a progress event for each file being loaded
  75511. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75512. * @param pluginExtension the extension used to determine the plugin
  75513. * @returns The loaded plugin
  75514. */
  75515. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  75516. if (onSuccess === void 0) { onSuccess = null; }
  75517. if (onProgress === void 0) { onProgress = null; }
  75518. if (onError === void 0) { onError = null; }
  75519. if (pluginExtension === void 0) { pluginExtension = null; }
  75520. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  75521. };
  75522. /**
  75523. * Load a scene
  75524. * @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)
  75525. * @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)
  75526. * @param engine is the instance of BABYLON.Engine to use to create the scene
  75527. * @param onProgress a callback with a progress event for each file being loaded
  75528. * @param pluginExtension the extension used to determine the plugin
  75529. * @returns The loaded scene
  75530. */
  75531. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  75532. if (onProgress === void 0) { onProgress = null; }
  75533. if (pluginExtension === void 0) { pluginExtension = null; }
  75534. return new Promise(function (resolve, reject) {
  75535. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  75536. resolve(scene);
  75537. }, onProgress, function (scene, message, exception) {
  75538. reject(exception || new Error(message));
  75539. }, pluginExtension);
  75540. });
  75541. };
  75542. /**
  75543. * Append a scene
  75544. * @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)
  75545. * @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)
  75546. * @param scene is the instance of BABYLON.Scene to append to
  75547. * @param onSuccess a callback with the scene when import succeeds
  75548. * @param onProgress a callback with a progress event for each file being loaded
  75549. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75550. * @param pluginExtension the extension used to determine the plugin
  75551. * @returns The loaded plugin
  75552. */
  75553. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75554. if (sceneFilename === void 0) { sceneFilename = ""; }
  75555. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75556. if (onSuccess === void 0) { onSuccess = null; }
  75557. if (onProgress === void 0) { onProgress = null; }
  75558. if (onError === void 0) { onError = null; }
  75559. if (pluginExtension === void 0) { pluginExtension = null; }
  75560. if (!scene) {
  75561. BABYLON.Tools.Error("No scene available to append to");
  75562. return null;
  75563. }
  75564. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75565. if (!fileInfo) {
  75566. return null;
  75567. }
  75568. if (SceneLoader.ShowLoadingScreen) {
  75569. scene.getEngine().displayLoadingUI();
  75570. }
  75571. var loadingToken = {};
  75572. scene._addPendingData(loadingToken);
  75573. var disposeHandler = function () {
  75574. scene._removePendingData(loadingToken);
  75575. scene.getEngine().hideLoadingUI();
  75576. };
  75577. var errorHandler = function (message, exception) {
  75578. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  75579. if (onError) {
  75580. onError(scene, errorMessage, exception);
  75581. }
  75582. else {
  75583. BABYLON.Tools.Error(errorMessage);
  75584. // should the exception be thrown?
  75585. }
  75586. disposeHandler();
  75587. };
  75588. var progressHandler = onProgress ? function (event) {
  75589. try {
  75590. onProgress(event);
  75591. }
  75592. catch (e) {
  75593. errorHandler("Error in onProgress callback", e);
  75594. }
  75595. } : undefined;
  75596. var successHandler = function () {
  75597. if (onSuccess) {
  75598. try {
  75599. onSuccess(scene);
  75600. }
  75601. catch (e) {
  75602. errorHandler("Error in onSuccess callback", e);
  75603. }
  75604. }
  75605. scene._removePendingData(loadingToken);
  75606. };
  75607. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75608. if (plugin.load) {
  75609. var syncedPlugin = plugin;
  75610. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  75611. return;
  75612. }
  75613. scene.loadingPluginName = plugin.name;
  75614. successHandler();
  75615. }
  75616. else {
  75617. var asyncedPlugin = plugin;
  75618. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  75619. scene.loadingPluginName = plugin.name;
  75620. successHandler();
  75621. }).catch(function (error) {
  75622. errorHandler(error.message, error);
  75623. });
  75624. }
  75625. if (SceneLoader.ShowLoadingScreen) {
  75626. scene.executeWhenReady(function () {
  75627. scene.getEngine().hideLoadingUI();
  75628. });
  75629. }
  75630. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75631. };
  75632. /**
  75633. * Append a scene
  75634. * @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)
  75635. * @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)
  75636. * @param scene is the instance of BABYLON.Scene to append to
  75637. * @param onProgress a callback with a progress event for each file being loaded
  75638. * @param pluginExtension the extension used to determine the plugin
  75639. * @returns The given scene
  75640. */
  75641. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75642. if (sceneFilename === void 0) { sceneFilename = ""; }
  75643. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75644. if (onProgress === void 0) { onProgress = null; }
  75645. if (pluginExtension === void 0) { pluginExtension = null; }
  75646. return new Promise(function (resolve, reject) {
  75647. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  75648. resolve(scene);
  75649. }, onProgress, function (scene, message, exception) {
  75650. reject(exception || new Error(message));
  75651. }, pluginExtension);
  75652. });
  75653. };
  75654. /**
  75655. * Load a scene into an asset container
  75656. * @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)
  75657. * @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)
  75658. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  75659. * @param onSuccess a callback with the scene when import succeeds
  75660. * @param onProgress a callback with a progress event for each file being loaded
  75661. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75662. * @param pluginExtension the extension used to determine the plugin
  75663. * @returns The loaded plugin
  75664. */
  75665. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75666. if (sceneFilename === void 0) { sceneFilename = ""; }
  75667. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75668. if (onSuccess === void 0) { onSuccess = null; }
  75669. if (onProgress === void 0) { onProgress = null; }
  75670. if (onError === void 0) { onError = null; }
  75671. if (pluginExtension === void 0) { pluginExtension = null; }
  75672. if (!scene) {
  75673. BABYLON.Tools.Error("No scene available to load asset container to");
  75674. return null;
  75675. }
  75676. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75677. if (!fileInfo) {
  75678. return null;
  75679. }
  75680. var loadingToken = {};
  75681. scene._addPendingData(loadingToken);
  75682. var disposeHandler = function () {
  75683. scene._removePendingData(loadingToken);
  75684. };
  75685. var errorHandler = function (message, exception) {
  75686. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  75687. if (onError) {
  75688. onError(scene, errorMessage, exception);
  75689. }
  75690. else {
  75691. BABYLON.Tools.Error(errorMessage);
  75692. // should the exception be thrown?
  75693. }
  75694. disposeHandler();
  75695. };
  75696. var progressHandler = onProgress ? function (event) {
  75697. try {
  75698. onProgress(event);
  75699. }
  75700. catch (e) {
  75701. errorHandler("Error in onProgress callback", e);
  75702. }
  75703. } : undefined;
  75704. var successHandler = function (assets) {
  75705. if (onSuccess) {
  75706. try {
  75707. onSuccess(assets);
  75708. }
  75709. catch (e) {
  75710. errorHandler("Error in onSuccess callback", e);
  75711. }
  75712. }
  75713. scene._removePendingData(loadingToken);
  75714. };
  75715. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75716. if (plugin.loadAssetContainer) {
  75717. var syncedPlugin = plugin;
  75718. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  75719. if (!assetContainer) {
  75720. return;
  75721. }
  75722. scene.loadingPluginName = plugin.name;
  75723. successHandler(assetContainer);
  75724. }
  75725. else if (plugin.loadAssetContainerAsync) {
  75726. var asyncedPlugin = plugin;
  75727. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  75728. scene.loadingPluginName = plugin.name;
  75729. successHandler(assetContainer);
  75730. }).catch(function (error) {
  75731. errorHandler(error.message, error);
  75732. });
  75733. }
  75734. else {
  75735. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  75736. }
  75737. if (SceneLoader.ShowLoadingScreen) {
  75738. scene.executeWhenReady(function () {
  75739. scene.getEngine().hideLoadingUI();
  75740. });
  75741. }
  75742. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75743. };
  75744. /**
  75745. * Load a scene into an asset container
  75746. * @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)
  75747. * @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)
  75748. * @param scene is the instance of BABYLON.Scene to append to
  75749. * @param onProgress a callback with a progress event for each file being loaded
  75750. * @param pluginExtension the extension used to determine the plugin
  75751. * @returns The loaded asset container
  75752. */
  75753. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75754. if (sceneFilename === void 0) { sceneFilename = ""; }
  75755. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75756. if (onProgress === void 0) { onProgress = null; }
  75757. if (pluginExtension === void 0) { pluginExtension = null; }
  75758. return new Promise(function (resolve, reject) {
  75759. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  75760. resolve(assetContainer);
  75761. }, onProgress, function (scene, message, exception) {
  75762. reject(exception || new Error(message));
  75763. }, pluginExtension);
  75764. });
  75765. };
  75766. // Flags
  75767. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  75768. SceneLoader._ShowLoadingScreen = true;
  75769. SceneLoader._CleanBoneMatrixWeights = false;
  75770. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  75771. // Members
  75772. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  75773. SceneLoader._registeredPlugins = {};
  75774. return SceneLoader;
  75775. }());
  75776. BABYLON.SceneLoader = SceneLoader;
  75777. ;
  75778. })(BABYLON || (BABYLON = {}));
  75779. //# sourceMappingURL=babylon.sceneLoader.js.map
  75780. var BABYLON;
  75781. (function (BABYLON) {
  75782. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  75783. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  75784. var parsedMaterial = parsedData.materials[index];
  75785. if (parsedMaterial.id === id) {
  75786. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  75787. }
  75788. }
  75789. return null;
  75790. };
  75791. var isDescendantOf = function (mesh, names, hierarchyIds) {
  75792. for (var i in names) {
  75793. if (mesh.name === names[i]) {
  75794. hierarchyIds.push(mesh.id);
  75795. return true;
  75796. }
  75797. }
  75798. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  75799. hierarchyIds.push(mesh.id);
  75800. return true;
  75801. }
  75802. return false;
  75803. };
  75804. var logOperation = function (operation, producer) {
  75805. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  75806. };
  75807. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  75808. if (addToScene === void 0) { addToScene = false; }
  75809. var container = new BABYLON.AssetContainer(scene);
  75810. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  75811. // when SceneLoader.debugLogging = true (default), or exception encountered.
  75812. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  75813. // and avoid problems with multiple concurrent .babylon loads.
  75814. var log = "importScene has failed JSON parse";
  75815. try {
  75816. var parsedData = JSON.parse(data);
  75817. log = "";
  75818. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  75819. var index;
  75820. var cache;
  75821. // Lights
  75822. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  75823. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  75824. var parsedLight = parsedData.lights[index];
  75825. var light = BABYLON.Light.Parse(parsedLight, scene);
  75826. if (light) {
  75827. container.lights.push(light);
  75828. log += (index === 0 ? "\n\tLights:" : "");
  75829. log += "\n\t\t" + light.toString(fullDetails);
  75830. }
  75831. }
  75832. }
  75833. // Animations
  75834. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  75835. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  75836. var parsedAnimation = parsedData.animations[index];
  75837. var animation = BABYLON.Animation.Parse(parsedAnimation);
  75838. scene.animations.push(animation);
  75839. container.animations.push(animation);
  75840. log += (index === 0 ? "\n\tAnimations:" : "");
  75841. log += "\n\t\t" + animation.toString(fullDetails);
  75842. }
  75843. }
  75844. // Materials
  75845. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  75846. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  75847. var parsedMaterial = parsedData.materials[index];
  75848. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  75849. container.materials.push(mat);
  75850. log += (index === 0 ? "\n\tMaterials:" : "");
  75851. log += "\n\t\t" + mat.toString(fullDetails);
  75852. }
  75853. }
  75854. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  75855. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  75856. var parsedMultiMaterial = parsedData.multiMaterials[index];
  75857. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  75858. container.multiMaterials.push(mmat);
  75859. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  75860. log += "\n\t\t" + mmat.toString(fullDetails);
  75861. }
  75862. }
  75863. // Morph targets
  75864. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  75865. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  75866. var managerData = _a[_i];
  75867. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  75868. }
  75869. }
  75870. // Skeletons
  75871. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  75872. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  75873. var parsedSkeleton = parsedData.skeletons[index];
  75874. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  75875. container.skeletons.push(skeleton);
  75876. log += (index === 0 ? "\n\tSkeletons:" : "");
  75877. log += "\n\t\t" + skeleton.toString(fullDetails);
  75878. }
  75879. }
  75880. // Geometries
  75881. var geometries = parsedData.geometries;
  75882. if (geometries !== undefined && geometries !== null) {
  75883. var addedGeometry = new Array();
  75884. // Boxes
  75885. var boxes = geometries.boxes;
  75886. if (boxes !== undefined && boxes !== null) {
  75887. for (index = 0, cache = boxes.length; index < cache; index++) {
  75888. var parsedBox = boxes[index];
  75889. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  75890. }
  75891. }
  75892. // Spheres
  75893. var spheres = geometries.spheres;
  75894. if (spheres !== undefined && spheres !== null) {
  75895. for (index = 0, cache = spheres.length; index < cache; index++) {
  75896. var parsedSphere = spheres[index];
  75897. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  75898. }
  75899. }
  75900. // Cylinders
  75901. var cylinders = geometries.cylinders;
  75902. if (cylinders !== undefined && cylinders !== null) {
  75903. for (index = 0, cache = cylinders.length; index < cache; index++) {
  75904. var parsedCylinder = cylinders[index];
  75905. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  75906. }
  75907. }
  75908. // Toruses
  75909. var toruses = geometries.toruses;
  75910. if (toruses !== undefined && toruses !== null) {
  75911. for (index = 0, cache = toruses.length; index < cache; index++) {
  75912. var parsedTorus = toruses[index];
  75913. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  75914. }
  75915. }
  75916. // Grounds
  75917. var grounds = geometries.grounds;
  75918. if (grounds !== undefined && grounds !== null) {
  75919. for (index = 0, cache = grounds.length; index < cache; index++) {
  75920. var parsedGround = grounds[index];
  75921. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  75922. }
  75923. }
  75924. // Planes
  75925. var planes = geometries.planes;
  75926. if (planes !== undefined && planes !== null) {
  75927. for (index = 0, cache = planes.length; index < cache; index++) {
  75928. var parsedPlane = planes[index];
  75929. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  75930. }
  75931. }
  75932. // TorusKnots
  75933. var torusKnots = geometries.torusKnots;
  75934. if (torusKnots !== undefined && torusKnots !== null) {
  75935. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  75936. var parsedTorusKnot = torusKnots[index];
  75937. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  75938. }
  75939. }
  75940. // VertexData
  75941. var vertexData = geometries.vertexData;
  75942. if (vertexData !== undefined && vertexData !== null) {
  75943. for (index = 0, cache = vertexData.length; index < cache; index++) {
  75944. var parsedVertexData = vertexData[index];
  75945. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  75946. }
  75947. }
  75948. addedGeometry.forEach(function (g) {
  75949. if (g) {
  75950. container.geometries.push(g);
  75951. }
  75952. });
  75953. }
  75954. // Transform nodes
  75955. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  75956. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  75957. var parsedTransformNode = parsedData.transformNodes[index];
  75958. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  75959. container.transformNodes.push(node);
  75960. }
  75961. }
  75962. // Meshes
  75963. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  75964. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  75965. var parsedMesh = parsedData.meshes[index];
  75966. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  75967. container.meshes.push(mesh);
  75968. log += (index === 0 ? "\n\tMeshes:" : "");
  75969. log += "\n\t\t" + mesh.toString(fullDetails);
  75970. }
  75971. }
  75972. // Cameras
  75973. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  75974. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  75975. var parsedCamera = parsedData.cameras[index];
  75976. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  75977. container.cameras.push(camera);
  75978. log += (index === 0 ? "\n\tCameras:" : "");
  75979. log += "\n\t\t" + camera.toString(fullDetails);
  75980. }
  75981. }
  75982. // Animation Groups
  75983. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  75984. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  75985. var parsedAnimationGroup = parsedData.animationGroups[index];
  75986. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  75987. container.animationGroups.push(animationGroup);
  75988. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  75989. log += "\n\t\t" + animationGroup.toString(fullDetails);
  75990. }
  75991. }
  75992. // Browsing all the graph to connect the dots
  75993. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  75994. var camera = scene.cameras[index];
  75995. if (camera._waitingParentId) {
  75996. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  75997. camera._waitingParentId = null;
  75998. }
  75999. }
  76000. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76001. var light_1 = scene.lights[index];
  76002. if (light_1 && light_1._waitingParentId) {
  76003. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  76004. light_1._waitingParentId = null;
  76005. }
  76006. }
  76007. // Connect parents & children and parse actions
  76008. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  76009. var transformNode = scene.transformNodes[index];
  76010. if (transformNode._waitingParentId) {
  76011. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  76012. transformNode._waitingParentId = null;
  76013. }
  76014. }
  76015. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76016. var mesh = scene.meshes[index];
  76017. if (mesh._waitingParentId) {
  76018. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  76019. mesh._waitingParentId = null;
  76020. }
  76021. }
  76022. // freeze world matrix application
  76023. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76024. var currentMesh = scene.meshes[index];
  76025. if (currentMesh._waitingFreezeWorldMatrix) {
  76026. currentMesh.freezeWorldMatrix();
  76027. currentMesh._waitingFreezeWorldMatrix = null;
  76028. }
  76029. else {
  76030. currentMesh.computeWorldMatrix(true);
  76031. }
  76032. }
  76033. // Lights exclusions / inclusions
  76034. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76035. var light_2 = scene.lights[index];
  76036. // Excluded check
  76037. if (light_2._excludedMeshesIds.length > 0) {
  76038. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  76039. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  76040. if (excludedMesh) {
  76041. light_2.excludedMeshes.push(excludedMesh);
  76042. }
  76043. }
  76044. light_2._excludedMeshesIds = [];
  76045. }
  76046. // Included check
  76047. if (light_2._includedOnlyMeshesIds.length > 0) {
  76048. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  76049. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  76050. if (includedOnlyMesh) {
  76051. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  76052. }
  76053. }
  76054. light_2._includedOnlyMeshesIds = [];
  76055. }
  76056. }
  76057. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  76058. // Actions (scene) Done last as it can access other objects.
  76059. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76060. var mesh = scene.meshes[index];
  76061. if (mesh._waitingActions) {
  76062. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  76063. mesh._waitingActions = null;
  76064. }
  76065. }
  76066. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  76067. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  76068. }
  76069. if (!addToScene) {
  76070. container.removeAllFromScene();
  76071. }
  76072. }
  76073. catch (err) {
  76074. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  76075. if (onError) {
  76076. onError(msg, err);
  76077. }
  76078. else {
  76079. BABYLON.Tools.Log(msg);
  76080. throw err;
  76081. }
  76082. }
  76083. finally {
  76084. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76085. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76086. }
  76087. }
  76088. return container;
  76089. };
  76090. BABYLON.SceneLoader.RegisterPlugin({
  76091. name: "babylon.js",
  76092. extensions: ".babylon",
  76093. canDirectLoad: function (data) {
  76094. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  76095. return true;
  76096. }
  76097. return false;
  76098. },
  76099. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  76100. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76101. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76102. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76103. // and avoid problems with multiple concurrent .babylon loads.
  76104. var log = "importMesh has failed JSON parse";
  76105. try {
  76106. var parsedData = JSON.parse(data);
  76107. log = "";
  76108. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  76109. if (!meshesNames) {
  76110. meshesNames = null;
  76111. }
  76112. else if (!Array.isArray(meshesNames)) {
  76113. meshesNames = [meshesNames];
  76114. }
  76115. var hierarchyIds = new Array();
  76116. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  76117. var loadedSkeletonsIds = [];
  76118. var loadedMaterialsIds = [];
  76119. var index;
  76120. var cache;
  76121. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  76122. var parsedMesh = parsedData.meshes[index];
  76123. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  76124. if (meshesNames !== null) {
  76125. // Remove found mesh name from list.
  76126. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  76127. }
  76128. //Geometry?
  76129. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  76130. //does the file contain geometries?
  76131. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  76132. //find the correct geometry and add it to the scene
  76133. var found = false;
  76134. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  76135. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  76136. return;
  76137. }
  76138. else {
  76139. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  76140. if (parsedGeometryData.id === parsedMesh.geometryId) {
  76141. switch (geometryType) {
  76142. case "boxes":
  76143. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  76144. break;
  76145. case "spheres":
  76146. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  76147. break;
  76148. case "cylinders":
  76149. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  76150. break;
  76151. case "toruses":
  76152. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  76153. break;
  76154. case "grounds":
  76155. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  76156. break;
  76157. case "planes":
  76158. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  76159. break;
  76160. case "torusKnots":
  76161. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  76162. break;
  76163. case "vertexData":
  76164. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  76165. break;
  76166. }
  76167. found = true;
  76168. }
  76169. });
  76170. }
  76171. });
  76172. if (found === false) {
  76173. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  76174. }
  76175. }
  76176. }
  76177. // Material ?
  76178. if (parsedMesh.materialId) {
  76179. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  76180. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  76181. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  76182. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  76183. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  76184. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  76185. var subMatId = parsedMultiMaterial.materials[matIndex];
  76186. loadedMaterialsIds.push(subMatId);
  76187. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  76188. if (mat) {
  76189. log += "\n\tMaterial " + mat.toString(fullDetails);
  76190. }
  76191. }
  76192. loadedMaterialsIds.push(parsedMultiMaterial.id);
  76193. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  76194. if (mmat) {
  76195. materialFound = true;
  76196. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  76197. }
  76198. break;
  76199. }
  76200. }
  76201. }
  76202. if (materialFound === false) {
  76203. loadedMaterialsIds.push(parsedMesh.materialId);
  76204. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  76205. if (!mat) {
  76206. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  76207. }
  76208. else {
  76209. log += "\n\tMaterial " + mat.toString(fullDetails);
  76210. }
  76211. }
  76212. }
  76213. // Skeleton ?
  76214. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  76215. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  76216. if (skeletonAlreadyLoaded === false) {
  76217. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  76218. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  76219. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  76220. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  76221. skeletons.push(skeleton);
  76222. loadedSkeletonsIds.push(parsedSkeleton.id);
  76223. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  76224. }
  76225. }
  76226. }
  76227. }
  76228. // Morph targets ?
  76229. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  76230. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  76231. var managerData = _a[_i];
  76232. BABYLON.MorphTargetManager.Parse(managerData, scene);
  76233. }
  76234. }
  76235. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  76236. meshes.push(mesh);
  76237. log += "\n\tMesh " + mesh.toString(fullDetails);
  76238. }
  76239. }
  76240. // Connecting parents
  76241. var currentMesh;
  76242. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76243. currentMesh = scene.meshes[index];
  76244. if (currentMesh._waitingParentId) {
  76245. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  76246. currentMesh._waitingParentId = null;
  76247. }
  76248. }
  76249. // freeze and compute world matrix application
  76250. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76251. currentMesh = scene.meshes[index];
  76252. if (currentMesh._waitingFreezeWorldMatrix) {
  76253. currentMesh.freezeWorldMatrix();
  76254. currentMesh._waitingFreezeWorldMatrix = null;
  76255. }
  76256. else {
  76257. currentMesh.computeWorldMatrix(true);
  76258. }
  76259. }
  76260. }
  76261. // Particles
  76262. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  76263. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  76264. if (parser) {
  76265. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  76266. var parsedParticleSystem = parsedData.particleSystems[index];
  76267. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  76268. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  76269. }
  76270. }
  76271. }
  76272. }
  76273. return true;
  76274. }
  76275. catch (err) {
  76276. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  76277. if (onError) {
  76278. onError(msg, err);
  76279. }
  76280. else {
  76281. BABYLON.Tools.Log(msg);
  76282. throw err;
  76283. }
  76284. }
  76285. finally {
  76286. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76287. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76288. }
  76289. }
  76290. return false;
  76291. },
  76292. load: function (scene, data, rootUrl, onError) {
  76293. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76294. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76295. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76296. // and avoid problems with multiple concurrent .babylon loads.
  76297. var log = "importScene has failed JSON parse";
  76298. try {
  76299. var parsedData = JSON.parse(data);
  76300. log = "";
  76301. // Scene
  76302. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  76303. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  76304. }
  76305. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  76306. scene.autoClear = parsedData.autoClear;
  76307. }
  76308. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  76309. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  76310. }
  76311. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  76312. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  76313. }
  76314. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  76315. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  76316. }
  76317. // Fog
  76318. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  76319. scene.fogMode = parsedData.fogMode;
  76320. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  76321. scene.fogStart = parsedData.fogStart;
  76322. scene.fogEnd = parsedData.fogEnd;
  76323. scene.fogDensity = parsedData.fogDensity;
  76324. log += "\tFog mode for scene: ";
  76325. switch (scene.fogMode) {
  76326. // getters not compiling, so using hardcoded
  76327. case 1:
  76328. log += "exp\n";
  76329. break;
  76330. case 2:
  76331. log += "exp2\n";
  76332. break;
  76333. case 3:
  76334. log += "linear\n";
  76335. break;
  76336. }
  76337. }
  76338. //Physics
  76339. if (parsedData.physicsEnabled) {
  76340. var physicsPlugin;
  76341. if (parsedData.physicsEngine === "cannon") {
  76342. physicsPlugin = new BABYLON.CannonJSPlugin();
  76343. }
  76344. else if (parsedData.physicsEngine === "oimo") {
  76345. physicsPlugin = new BABYLON.OimoJSPlugin();
  76346. }
  76347. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  76348. //else - default engine, which is currently oimo
  76349. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  76350. scene.enablePhysics(physicsGravity, physicsPlugin);
  76351. }
  76352. // Metadata
  76353. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  76354. scene.metadata = parsedData.metadata;
  76355. }
  76356. //collisions, if defined. otherwise, default is true
  76357. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  76358. scene.collisionsEnabled = parsedData.collisionsEnabled;
  76359. }
  76360. scene.workerCollisions = !!parsedData.workerCollisions;
  76361. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  76362. if (!container) {
  76363. return false;
  76364. }
  76365. if (parsedData.autoAnimate) {
  76366. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  76367. }
  76368. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  76369. scene.setActiveCameraByID(parsedData.activeCameraID);
  76370. }
  76371. // Environment texture
  76372. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  76373. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  76374. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  76375. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  76376. if (parsedData.environmentTextureRotationY) {
  76377. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  76378. }
  76379. scene.environmentTexture = hdrTexture;
  76380. }
  76381. else {
  76382. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  76383. if (parsedData.environmentTextureRotationY) {
  76384. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  76385. }
  76386. scene.environmentTexture = cubeTexture;
  76387. }
  76388. if (parsedData.createDefaultSkybox === true) {
  76389. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  76390. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  76391. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  76392. }
  76393. }
  76394. // Finish
  76395. return true;
  76396. }
  76397. catch (err) {
  76398. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  76399. if (onError) {
  76400. onError(msg, err);
  76401. }
  76402. else {
  76403. BABYLON.Tools.Log(msg);
  76404. throw err;
  76405. }
  76406. }
  76407. finally {
  76408. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76409. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76410. }
  76411. }
  76412. return false;
  76413. },
  76414. loadAssetContainer: function (scene, data, rootUrl, onError) {
  76415. var container = loadAssetContainer(scene, data, rootUrl, onError);
  76416. return container;
  76417. }
  76418. });
  76419. })(BABYLON || (BABYLON = {}));
  76420. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  76421. var BABYLON;
  76422. (function (BABYLON) {
  76423. /**
  76424. * Class used to help managing file picking and drag'n'drop
  76425. */
  76426. var FilesInput = /** @class */ (function () {
  76427. /**
  76428. * Creates a new FilesInput
  76429. * @param engine defines the rendering engine
  76430. * @param scene defines the hosting scene
  76431. * @param sceneLoadedCallback callback called when scene is loaded
  76432. * @param progressCallback callback called to track progress
  76433. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  76434. * @param textureLoadingCallback callback called when a texture is loading
  76435. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  76436. * @param onReloadCallback callback called when a reload is requested
  76437. * @param errorCallback callback call if an error occurs
  76438. */
  76439. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  76440. /**
  76441. * Callback called when a file is processed
  76442. */
  76443. this.onProcessFileCallback = function () { return true; };
  76444. this._engine = engine;
  76445. this._currentScene = scene;
  76446. this._sceneLoadedCallback = sceneLoadedCallback;
  76447. this._progressCallback = progressCallback;
  76448. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  76449. this._textureLoadingCallback = textureLoadingCallback;
  76450. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  76451. this._onReloadCallback = onReloadCallback;
  76452. this._errorCallback = errorCallback;
  76453. }
  76454. /**
  76455. * Calls this function to listen to drag'n'drop events on a specific DOM element
  76456. * @param elementToMonitor defines the DOM element to track
  76457. */
  76458. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  76459. var _this = this;
  76460. if (elementToMonitor) {
  76461. this._elementToMonitor = elementToMonitor;
  76462. this._dragEnterHandler = function (e) { _this.drag(e); };
  76463. this._dragOverHandler = function (e) { _this.drag(e); };
  76464. this._dropHandler = function (e) { _this.drop(e); };
  76465. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  76466. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  76467. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  76468. }
  76469. };
  76470. /**
  76471. * Release all associated resources
  76472. */
  76473. FilesInput.prototype.dispose = function () {
  76474. if (!this._elementToMonitor) {
  76475. return;
  76476. }
  76477. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  76478. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  76479. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  76480. };
  76481. FilesInput.prototype.renderFunction = function () {
  76482. if (this._additionalRenderLoopLogicCallback) {
  76483. this._additionalRenderLoopLogicCallback();
  76484. }
  76485. if (this._currentScene) {
  76486. if (this._textureLoadingCallback) {
  76487. var remaining = this._currentScene.getWaitingItemsCount();
  76488. if (remaining > 0) {
  76489. this._textureLoadingCallback(remaining);
  76490. }
  76491. }
  76492. this._currentScene.render();
  76493. }
  76494. };
  76495. FilesInput.prototype.drag = function (e) {
  76496. e.stopPropagation();
  76497. e.preventDefault();
  76498. };
  76499. FilesInput.prototype.drop = function (eventDrop) {
  76500. eventDrop.stopPropagation();
  76501. eventDrop.preventDefault();
  76502. this.loadFiles(eventDrop);
  76503. };
  76504. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  76505. var _this = this;
  76506. var reader = folder.createReader();
  76507. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  76508. reader.readEntries(function (entries) {
  76509. remaining.count += entries.length;
  76510. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  76511. var entry = entries_1[_i];
  76512. if (entry.isFile) {
  76513. entry.file(function (file) {
  76514. file.correctName = relativePath + file.name;
  76515. files.push(file);
  76516. if (--remaining.count === 0) {
  76517. callback();
  76518. }
  76519. });
  76520. }
  76521. else if (entry.isDirectory) {
  76522. _this._traverseFolder(entry, files, remaining, callback);
  76523. }
  76524. }
  76525. if (--remaining.count) {
  76526. callback();
  76527. }
  76528. });
  76529. };
  76530. FilesInput.prototype._processFiles = function (files) {
  76531. for (var i = 0; i < files.length; i++) {
  76532. var name = files[i].correctName.toLowerCase();
  76533. var extension = name.split('.').pop();
  76534. if (!this.onProcessFileCallback(files[i], name, extension)) {
  76535. continue;
  76536. }
  76537. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  76538. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  76539. this._sceneFileToLoad = files[i];
  76540. }
  76541. FilesInput.FilesToLoad[name] = files[i];
  76542. }
  76543. };
  76544. /**
  76545. * Load files from a drop event
  76546. * @param event defines the drop event to use as source
  76547. */
  76548. FilesInput.prototype.loadFiles = function (event) {
  76549. var _this = this;
  76550. // Handling data transfer via drag'n'drop
  76551. if (event && event.dataTransfer && event.dataTransfer.files) {
  76552. this._filesToLoad = event.dataTransfer.files;
  76553. }
  76554. // Handling files from input files
  76555. if (event && event.target && event.target.files) {
  76556. this._filesToLoad = event.target.files;
  76557. }
  76558. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  76559. return;
  76560. }
  76561. if (this._startingProcessingFilesCallback) {
  76562. this._startingProcessingFilesCallback(this._filesToLoad);
  76563. }
  76564. if (this._filesToLoad && this._filesToLoad.length > 0) {
  76565. var files_1 = new Array();
  76566. var folders = [];
  76567. var items = event.dataTransfer ? event.dataTransfer.items : null;
  76568. for (var i = 0; i < this._filesToLoad.length; i++) {
  76569. var fileToLoad = this._filesToLoad[i];
  76570. var name_1 = fileToLoad.name.toLowerCase();
  76571. var entry = void 0;
  76572. fileToLoad.correctName = name_1;
  76573. if (items) {
  76574. var item = items[i];
  76575. if (item.getAsEntry) {
  76576. entry = item.getAsEntry();
  76577. }
  76578. else if (item.webkitGetAsEntry) {
  76579. entry = item.webkitGetAsEntry();
  76580. }
  76581. }
  76582. if (!entry) {
  76583. files_1.push(fileToLoad);
  76584. }
  76585. else {
  76586. if (entry.isDirectory) {
  76587. folders.push(entry);
  76588. }
  76589. else {
  76590. files_1.push(fileToLoad);
  76591. }
  76592. }
  76593. }
  76594. if (folders.length === 0) {
  76595. this._processFiles(files_1);
  76596. this._processReload();
  76597. }
  76598. else {
  76599. var remaining = { count: folders.length };
  76600. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  76601. var folder = folders_1[_i];
  76602. this._traverseFolder(folder, files_1, remaining, function () {
  76603. _this._processFiles(files_1);
  76604. if (remaining.count === 0) {
  76605. _this._processReload();
  76606. }
  76607. });
  76608. }
  76609. }
  76610. }
  76611. };
  76612. FilesInput.prototype._processReload = function () {
  76613. if (this._onReloadCallback) {
  76614. this._onReloadCallback(this._sceneFileToLoad);
  76615. }
  76616. else {
  76617. this.reload();
  76618. }
  76619. };
  76620. /**
  76621. * Reload the current scene from the loaded files
  76622. */
  76623. FilesInput.prototype.reload = function () {
  76624. var _this = this;
  76625. // If a scene file has been provided
  76626. if (this._sceneFileToLoad) {
  76627. if (this._currentScene) {
  76628. if (BABYLON.Tools.errorsCount > 0) {
  76629. BABYLON.Tools.ClearLogCache();
  76630. }
  76631. this._engine.stopRenderLoop();
  76632. }
  76633. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  76634. if (_this._progressCallback) {
  76635. _this._progressCallback(progress);
  76636. }
  76637. }).then(function (scene) {
  76638. if (_this._currentScene) {
  76639. _this._currentScene.dispose();
  76640. }
  76641. _this._currentScene = scene;
  76642. if (_this._sceneLoadedCallback) {
  76643. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  76644. }
  76645. // Wait for textures and shaders to be ready
  76646. _this._currentScene.executeWhenReady(function () {
  76647. _this._engine.runRenderLoop(function () {
  76648. _this.renderFunction();
  76649. });
  76650. });
  76651. }).catch(function (error) {
  76652. if (_this._errorCallback) {
  76653. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  76654. }
  76655. });
  76656. }
  76657. else {
  76658. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  76659. }
  76660. };
  76661. /**
  76662. * List of files ready to be loaded
  76663. */
  76664. FilesInput.FilesToLoad = {};
  76665. return FilesInput;
  76666. }());
  76667. BABYLON.FilesInput = FilesInput;
  76668. })(BABYLON || (BABYLON = {}));
  76669. //# sourceMappingURL=babylon.filesInput.js.map
  76670. var BABYLON;
  76671. (function (BABYLON) {
  76672. /**
  76673. * Class used to store custom tags
  76674. */
  76675. var Tags = /** @class */ (function () {
  76676. function Tags() {
  76677. }
  76678. /**
  76679. * Adds support for tags on the given object
  76680. * @param obj defines the object to use
  76681. */
  76682. Tags.EnableFor = function (obj) {
  76683. obj._tags = obj._tags || {};
  76684. obj.hasTags = function () {
  76685. return Tags.HasTags(obj);
  76686. };
  76687. obj.addTags = function (tagsString) {
  76688. return Tags.AddTagsTo(obj, tagsString);
  76689. };
  76690. obj.removeTags = function (tagsString) {
  76691. return Tags.RemoveTagsFrom(obj, tagsString);
  76692. };
  76693. obj.matchesTagsQuery = function (tagsQuery) {
  76694. return Tags.MatchesQuery(obj, tagsQuery);
  76695. };
  76696. };
  76697. /**
  76698. * Removes tags support
  76699. * @param obj defines the object to use
  76700. */
  76701. Tags.DisableFor = function (obj) {
  76702. delete obj._tags;
  76703. delete obj.hasTags;
  76704. delete obj.addTags;
  76705. delete obj.removeTags;
  76706. delete obj.matchesTagsQuery;
  76707. };
  76708. /**
  76709. * Gets a boolean indicating if the given object has tags
  76710. * @param obj defines the object to use
  76711. * @returns a boolean
  76712. */
  76713. Tags.HasTags = function (obj) {
  76714. if (!obj._tags) {
  76715. return false;
  76716. }
  76717. return !BABYLON.Tools.IsEmpty(obj._tags);
  76718. };
  76719. /**
  76720. * Gets the tags available on a given object
  76721. * @param obj defines the object to use
  76722. * @param asString defines if the tags must be returned as a string instead of an array of strings
  76723. * @returns the tags
  76724. */
  76725. Tags.GetTags = function (obj, asString) {
  76726. if (asString === void 0) { asString = true; }
  76727. if (!obj._tags) {
  76728. return null;
  76729. }
  76730. if (asString) {
  76731. var tagsArray = [];
  76732. for (var tag in obj._tags) {
  76733. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  76734. tagsArray.push(tag);
  76735. }
  76736. }
  76737. return tagsArray.join(" ");
  76738. }
  76739. else {
  76740. return obj._tags;
  76741. }
  76742. };
  76743. /**
  76744. * Adds tags to an object
  76745. * @param obj defines the object to use
  76746. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  76747. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  76748. */
  76749. Tags.AddTagsTo = function (obj, tagsString) {
  76750. if (!tagsString) {
  76751. return;
  76752. }
  76753. if (typeof tagsString !== "string") {
  76754. return;
  76755. }
  76756. var tags = tagsString.split(" ");
  76757. tags.forEach(function (tag, index, array) {
  76758. Tags._AddTagTo(obj, tag);
  76759. });
  76760. };
  76761. /**
  76762. * @hidden
  76763. */
  76764. Tags._AddTagTo = function (obj, tag) {
  76765. tag = tag.trim();
  76766. if (tag === "" || tag === "true" || tag === "false") {
  76767. return;
  76768. }
  76769. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  76770. return;
  76771. }
  76772. Tags.EnableFor(obj);
  76773. obj._tags[tag] = true;
  76774. };
  76775. /**
  76776. * Removes specific tags from a specific object
  76777. * @param obj defines the object to use
  76778. * @param tagsString defines the tags to remove
  76779. */
  76780. Tags.RemoveTagsFrom = function (obj, tagsString) {
  76781. if (!Tags.HasTags(obj)) {
  76782. return;
  76783. }
  76784. var tags = tagsString.split(" ");
  76785. for (var t in tags) {
  76786. Tags._RemoveTagFrom(obj, tags[t]);
  76787. }
  76788. };
  76789. /**
  76790. * @hidden
  76791. */
  76792. Tags._RemoveTagFrom = function (obj, tag) {
  76793. delete obj._tags[tag];
  76794. };
  76795. /**
  76796. * Defines if tags hosted on an object match a given query
  76797. * @param obj defines the object to use
  76798. * @param tagsQuery defines the tag query
  76799. * @returns a boolean
  76800. */
  76801. Tags.MatchesQuery = function (obj, tagsQuery) {
  76802. if (tagsQuery === undefined) {
  76803. return true;
  76804. }
  76805. if (tagsQuery === "") {
  76806. return Tags.HasTags(obj);
  76807. }
  76808. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  76809. };
  76810. return Tags;
  76811. }());
  76812. BABYLON.Tags = Tags;
  76813. })(BABYLON || (BABYLON = {}));
  76814. //# sourceMappingURL=babylon.tags.js.map
  76815. var BABYLON;
  76816. (function (BABYLON) {
  76817. /**
  76818. * Class used to evalaute queries containing `and` and `or` operators
  76819. */
  76820. var AndOrNotEvaluator = /** @class */ (function () {
  76821. function AndOrNotEvaluator() {
  76822. }
  76823. /**
  76824. * Evaluate a query
  76825. * @param query defines the query to evaluate
  76826. * @param evaluateCallback defines the callback used to filter result
  76827. * @returns true if the query matches
  76828. */
  76829. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  76830. if (!query.match(/\([^\(\)]*\)/g)) {
  76831. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  76832. }
  76833. else {
  76834. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  76835. // remove parenthesis
  76836. r = r.slice(1, r.length - 1);
  76837. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  76838. });
  76839. }
  76840. if (query === "true") {
  76841. return true;
  76842. }
  76843. if (query === "false") {
  76844. return false;
  76845. }
  76846. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  76847. };
  76848. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  76849. evaluateCallback = evaluateCallback || (function (r) {
  76850. return r === "true" ? true : false;
  76851. });
  76852. var result;
  76853. var or = parenthesisContent.split("||");
  76854. for (var i in or) {
  76855. if (or.hasOwnProperty(i)) {
  76856. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  76857. var and = ori.split("&&");
  76858. if (and.length > 1) {
  76859. for (var j = 0; j < and.length; ++j) {
  76860. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  76861. if (andj !== "true" && andj !== "false") {
  76862. if (andj[0] === "!") {
  76863. result = !evaluateCallback(andj.substring(1));
  76864. }
  76865. else {
  76866. result = evaluateCallback(andj);
  76867. }
  76868. }
  76869. else {
  76870. result = andj === "true" ? true : false;
  76871. }
  76872. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  76873. ori = "false";
  76874. break;
  76875. }
  76876. }
  76877. }
  76878. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  76879. result = true;
  76880. break;
  76881. }
  76882. // result equals false (or undefined)
  76883. if (ori !== "true" && ori !== "false") {
  76884. if (ori[0] === "!") {
  76885. result = !evaluateCallback(ori.substring(1));
  76886. }
  76887. else {
  76888. result = evaluateCallback(ori);
  76889. }
  76890. }
  76891. else {
  76892. result = ori === "true" ? true : false;
  76893. }
  76894. }
  76895. }
  76896. // the whole parenthesis scope is replaced by 'true' or 'false'
  76897. return result ? "true" : "false";
  76898. };
  76899. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  76900. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  76901. // remove whitespaces
  76902. r = r.replace(/[\s]/g, function () { return ""; });
  76903. return r.length % 2 ? "!" : "";
  76904. });
  76905. booleanString = booleanString.trim();
  76906. if (booleanString === "!true") {
  76907. booleanString = "false";
  76908. }
  76909. else if (booleanString === "!false") {
  76910. booleanString = "true";
  76911. }
  76912. return booleanString;
  76913. };
  76914. return AndOrNotEvaluator;
  76915. }());
  76916. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  76917. })(BABYLON || (BABYLON = {}));
  76918. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  76919. var BABYLON;
  76920. (function (BABYLON) {
  76921. /**
  76922. * Class used to enable access to IndexedDB
  76923. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  76924. */
  76925. var Database = /** @class */ (function () {
  76926. /**
  76927. * Creates a new Database
  76928. * @param urlToScene defines the url to load the scene
  76929. * @param callbackManifestChecked defines the callback to use when manifest is checked
  76930. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  76931. */
  76932. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  76933. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  76934. var _this = this;
  76935. // Handling various flavors of prefixed version of IndexedDB
  76936. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  76937. this.callbackManifestChecked = callbackManifestChecked;
  76938. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  76939. this.db = null;
  76940. this._enableSceneOffline = false;
  76941. this._enableTexturesOffline = false;
  76942. this.manifestVersionFound = 0;
  76943. this.mustUpdateRessources = false;
  76944. this.hasReachedQuota = false;
  76945. if (!Database.IDBStorageEnabled) {
  76946. this.callbackManifestChecked(true);
  76947. }
  76948. else {
  76949. if (disableManifestCheck) {
  76950. this._enableSceneOffline = true;
  76951. this._enableTexturesOffline = true;
  76952. this.manifestVersionFound = 1;
  76953. BABYLON.Tools.SetImmediate(function () {
  76954. _this.callbackManifestChecked(true);
  76955. });
  76956. }
  76957. else {
  76958. this._checkManifestFile();
  76959. }
  76960. }
  76961. }
  76962. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  76963. /**
  76964. * Gets a boolean indicating if scene must be saved in the database
  76965. */
  76966. get: function () {
  76967. return this._enableSceneOffline;
  76968. },
  76969. enumerable: true,
  76970. configurable: true
  76971. });
  76972. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  76973. /**
  76974. * Gets a boolean indicating if textures must be saved in the database
  76975. */
  76976. get: function () {
  76977. return this._enableTexturesOffline;
  76978. },
  76979. enumerable: true,
  76980. configurable: true
  76981. });
  76982. Database.prototype._checkManifestFile = function () {
  76983. var _this = this;
  76984. var noManifestFile = function () {
  76985. _this._enableSceneOffline = false;
  76986. _this._enableTexturesOffline = false;
  76987. _this.callbackManifestChecked(false);
  76988. };
  76989. var timeStampUsed = false;
  76990. var manifestURL = this.currentSceneUrl + ".manifest";
  76991. var xhr = new XMLHttpRequest();
  76992. if (navigator.onLine) {
  76993. // Adding a timestamp to by-pass browsers' cache
  76994. timeStampUsed = true;
  76995. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  76996. }
  76997. xhr.open("GET", manifestURL, true);
  76998. xhr.addEventListener("load", function () {
  76999. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  77000. try {
  77001. var manifestFile = JSON.parse(xhr.response);
  77002. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  77003. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  77004. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  77005. _this.manifestVersionFound = manifestFile.version;
  77006. }
  77007. if (_this.callbackManifestChecked) {
  77008. _this.callbackManifestChecked(true);
  77009. }
  77010. }
  77011. catch (ex) {
  77012. noManifestFile();
  77013. }
  77014. }
  77015. else {
  77016. noManifestFile();
  77017. }
  77018. }, false);
  77019. xhr.addEventListener("error", function (event) {
  77020. if (timeStampUsed) {
  77021. timeStampUsed = false;
  77022. // Let's retry without the timeStamp
  77023. // It could fail when coupled with HTML5 Offline API
  77024. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  77025. xhr.open("GET", retryManifestURL, true);
  77026. xhr.send();
  77027. }
  77028. else {
  77029. noManifestFile();
  77030. }
  77031. }, false);
  77032. try {
  77033. xhr.send();
  77034. }
  77035. catch (ex) {
  77036. BABYLON.Tools.Error("Error on XHR send request.");
  77037. this.callbackManifestChecked(false);
  77038. }
  77039. };
  77040. /**
  77041. * Open the database and make it available
  77042. * @param successCallback defines the callback to call on success
  77043. * @param errorCallback defines the callback to call on error
  77044. */
  77045. Database.prototype.openAsync = function (successCallback, errorCallback) {
  77046. var _this = this;
  77047. var handleError = function () {
  77048. _this.isSupported = false;
  77049. if (errorCallback)
  77050. errorCallback();
  77051. };
  77052. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  77053. // Your browser doesn't support IndexedDB
  77054. this.isSupported = false;
  77055. if (errorCallback)
  77056. errorCallback();
  77057. }
  77058. else {
  77059. // If the DB hasn't been opened or created yet
  77060. if (!this.db) {
  77061. this.hasReachedQuota = false;
  77062. this.isSupported = true;
  77063. var request = this.idbFactory.open("babylonjs", 1);
  77064. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  77065. request.onerror = function (event) {
  77066. handleError();
  77067. };
  77068. // executes when a version change transaction cannot complete due to other active transactions
  77069. request.onblocked = function (event) {
  77070. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  77071. handleError();
  77072. };
  77073. // DB has been opened successfully
  77074. request.onsuccess = function (event) {
  77075. _this.db = request.result;
  77076. successCallback();
  77077. };
  77078. // Initialization of the DB. Creating Scenes & Textures stores
  77079. request.onupgradeneeded = function (event) {
  77080. _this.db = (event.target).result;
  77081. if (_this.db) {
  77082. try {
  77083. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  77084. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  77085. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  77086. }
  77087. catch (ex) {
  77088. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  77089. handleError();
  77090. }
  77091. }
  77092. };
  77093. }
  77094. // DB has already been created and opened
  77095. else {
  77096. if (successCallback)
  77097. successCallback();
  77098. }
  77099. }
  77100. };
  77101. /**
  77102. * Loads an image from the database
  77103. * @param url defines the url to load from
  77104. * @param image defines the target DOM image
  77105. */
  77106. Database.prototype.loadImageFromDB = function (url, image) {
  77107. var _this = this;
  77108. var completeURL = Database._ReturnFullUrlLocation(url);
  77109. var saveAndLoadImage = function () {
  77110. if (!_this.hasReachedQuota && _this.db !== null) {
  77111. // the texture is not yet in the DB, let's try to save it
  77112. _this._saveImageIntoDBAsync(completeURL, image);
  77113. }
  77114. // If the texture is not in the DB and we've reached the DB quota limit
  77115. // let's load it directly from the web
  77116. else {
  77117. image.src = url;
  77118. }
  77119. };
  77120. if (!this.mustUpdateRessources) {
  77121. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  77122. }
  77123. // First time we're download the images or update requested in the manifest file by a version change
  77124. else {
  77125. saveAndLoadImage();
  77126. }
  77127. };
  77128. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  77129. if (this.isSupported && this.db !== null) {
  77130. var texture;
  77131. var transaction = this.db.transaction(["textures"]);
  77132. transaction.onabort = function (event) {
  77133. image.src = url;
  77134. };
  77135. transaction.oncomplete = function (event) {
  77136. var blobTextureURL;
  77137. if (texture) {
  77138. var URL = window.URL || window.webkitURL;
  77139. blobTextureURL = URL.createObjectURL(texture.data);
  77140. image.onerror = function () {
  77141. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  77142. image.src = url;
  77143. };
  77144. image.src = blobTextureURL;
  77145. }
  77146. else {
  77147. notInDBCallback();
  77148. }
  77149. };
  77150. var getRequest = transaction.objectStore("textures").get(url);
  77151. getRequest.onsuccess = function (event) {
  77152. texture = (event.target).result;
  77153. };
  77154. getRequest.onerror = function (event) {
  77155. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  77156. image.src = url;
  77157. };
  77158. }
  77159. else {
  77160. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77161. image.src = url;
  77162. }
  77163. };
  77164. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  77165. var _this = this;
  77166. if (this.isSupported) {
  77167. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  77168. var generateBlobUrl = function () {
  77169. var blobTextureURL;
  77170. if (blob) {
  77171. var URL = window.URL || window.webkitURL;
  77172. try {
  77173. blobTextureURL = URL.createObjectURL(blob);
  77174. }
  77175. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  77176. catch (ex) {
  77177. blobTextureURL = URL.createObjectURL(blob);
  77178. }
  77179. }
  77180. if (blobTextureURL) {
  77181. image.src = blobTextureURL;
  77182. }
  77183. };
  77184. if (Database.IsUASupportingBlobStorage) { // Create XHR
  77185. var xhr = new XMLHttpRequest(), blob;
  77186. xhr.open("GET", url, true);
  77187. xhr.responseType = "blob";
  77188. xhr.addEventListener("load", function () {
  77189. if (xhr.status === 200 && _this.db) {
  77190. // Blob as response (XHR2)
  77191. blob = xhr.response;
  77192. var transaction = _this.db.transaction(["textures"], "readwrite");
  77193. // the transaction could abort because of a QuotaExceededError error
  77194. transaction.onabort = function (event) {
  77195. try {
  77196. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77197. var srcElement = (event.srcElement || event.target);
  77198. var error = srcElement.error;
  77199. if (error && error.name === "QuotaExceededError") {
  77200. _this.hasReachedQuota = true;
  77201. }
  77202. }
  77203. catch (ex) { }
  77204. generateBlobUrl();
  77205. };
  77206. transaction.oncomplete = function (event) {
  77207. generateBlobUrl();
  77208. };
  77209. var newTexture = { textureUrl: url, data: blob };
  77210. try {
  77211. // Put the blob into the dabase
  77212. var addRequest = transaction.objectStore("textures").put(newTexture);
  77213. addRequest.onsuccess = function (event) {
  77214. };
  77215. addRequest.onerror = function (event) {
  77216. generateBlobUrl();
  77217. };
  77218. }
  77219. catch (ex) {
  77220. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  77221. if (ex.code === 25) {
  77222. Database.IsUASupportingBlobStorage = false;
  77223. }
  77224. image.src = url;
  77225. }
  77226. }
  77227. else {
  77228. image.src = url;
  77229. }
  77230. }, false);
  77231. xhr.addEventListener("error", function (event) {
  77232. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  77233. image.src = url;
  77234. }, false);
  77235. xhr.send();
  77236. }
  77237. else {
  77238. image.src = url;
  77239. }
  77240. }
  77241. else {
  77242. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77243. image.src = url;
  77244. }
  77245. };
  77246. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  77247. var _this = this;
  77248. var updateVersion = function () {
  77249. // the version is not yet in the DB or we need to update it
  77250. _this._saveVersionIntoDBAsync(url, versionLoaded);
  77251. };
  77252. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  77253. };
  77254. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  77255. var _this = this;
  77256. if (this.isSupported && this.db) {
  77257. var version;
  77258. try {
  77259. var transaction = this.db.transaction(["versions"]);
  77260. transaction.oncomplete = function (event) {
  77261. if (version) {
  77262. // If the version in the JSON file is different from the version in DB
  77263. if (_this.manifestVersionFound !== version.data) {
  77264. _this.mustUpdateRessources = true;
  77265. updateInDBCallback();
  77266. }
  77267. else {
  77268. callback(version.data);
  77269. }
  77270. }
  77271. // version was not found in DB
  77272. else {
  77273. _this.mustUpdateRessources = true;
  77274. updateInDBCallback();
  77275. }
  77276. };
  77277. transaction.onabort = function (event) {
  77278. callback(-1);
  77279. };
  77280. var getRequest = transaction.objectStore("versions").get(url);
  77281. getRequest.onsuccess = function (event) {
  77282. version = (event.target).result;
  77283. };
  77284. getRequest.onerror = function (event) {
  77285. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  77286. callback(-1);
  77287. };
  77288. }
  77289. catch (ex) {
  77290. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  77291. callback(-1);
  77292. }
  77293. }
  77294. else {
  77295. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77296. callback(-1);
  77297. }
  77298. };
  77299. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  77300. var _this = this;
  77301. if (this.isSupported && !this.hasReachedQuota && this.db) {
  77302. try {
  77303. // Open a transaction to the database
  77304. var transaction = this.db.transaction(["versions"], "readwrite");
  77305. // the transaction could abort because of a QuotaExceededError error
  77306. transaction.onabort = function (event) {
  77307. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77308. var error = event.srcElement['error'];
  77309. if (error && error.name === "QuotaExceededError") {
  77310. _this.hasReachedQuota = true;
  77311. }
  77312. }
  77313. catch (ex) { }
  77314. callback(-1);
  77315. };
  77316. transaction.oncomplete = function (event) {
  77317. callback(_this.manifestVersionFound);
  77318. };
  77319. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  77320. // Put the scene into the database
  77321. var addRequest = transaction.objectStore("versions").put(newVersion);
  77322. addRequest.onsuccess = function (event) {
  77323. };
  77324. addRequest.onerror = function (event) {
  77325. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  77326. };
  77327. }
  77328. catch (ex) {
  77329. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  77330. callback(-1);
  77331. }
  77332. }
  77333. else {
  77334. callback(-1);
  77335. }
  77336. };
  77337. /**
  77338. * Loads a file from database
  77339. * @param url defines the URL to load from
  77340. * @param sceneLoaded defines a callback to call on success
  77341. * @param progressCallBack defines a callback to call when progress changed
  77342. * @param errorCallback defines a callback to call on error
  77343. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  77344. */
  77345. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  77346. var _this = this;
  77347. var completeUrl = Database._ReturnFullUrlLocation(url);
  77348. var saveAndLoadFile = function () {
  77349. // the scene is not yet in the DB, let's try to save it
  77350. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  77351. };
  77352. this._checkVersionFromDB(completeUrl, function (version) {
  77353. if (version !== -1) {
  77354. if (!_this.mustUpdateRessources) {
  77355. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  77356. }
  77357. else {
  77358. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  77359. }
  77360. }
  77361. else {
  77362. if (errorCallback) {
  77363. errorCallback();
  77364. }
  77365. }
  77366. });
  77367. };
  77368. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  77369. if (this.isSupported && this.db) {
  77370. var targetStore;
  77371. if (url.indexOf(".babylon") !== -1) {
  77372. targetStore = "scenes";
  77373. }
  77374. else {
  77375. targetStore = "textures";
  77376. }
  77377. var file;
  77378. var transaction = this.db.transaction([targetStore]);
  77379. transaction.oncomplete = function (event) {
  77380. if (file) {
  77381. callback(file.data);
  77382. }
  77383. // file was not found in DB
  77384. else {
  77385. notInDBCallback();
  77386. }
  77387. };
  77388. transaction.onabort = function (event) {
  77389. notInDBCallback();
  77390. };
  77391. var getRequest = transaction.objectStore(targetStore).get(url);
  77392. getRequest.onsuccess = function (event) {
  77393. file = (event.target).result;
  77394. };
  77395. getRequest.onerror = function (event) {
  77396. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  77397. notInDBCallback();
  77398. };
  77399. }
  77400. else {
  77401. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77402. callback();
  77403. }
  77404. };
  77405. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  77406. var _this = this;
  77407. if (this.isSupported) {
  77408. var targetStore;
  77409. if (url.indexOf(".babylon") !== -1) {
  77410. targetStore = "scenes";
  77411. }
  77412. else {
  77413. targetStore = "textures";
  77414. }
  77415. // Create XHR
  77416. var xhr = new XMLHttpRequest();
  77417. var fileData;
  77418. xhr.open("GET", url + "?" + Date.now(), true);
  77419. if (useArrayBuffer) {
  77420. xhr.responseType = "arraybuffer";
  77421. }
  77422. if (progressCallback) {
  77423. xhr.onprogress = progressCallback;
  77424. }
  77425. xhr.addEventListener("load", function () {
  77426. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  77427. // Blob as response (XHR2)
  77428. //fileData = xhr.responseText;
  77429. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  77430. if (!_this.hasReachedQuota && _this.db) {
  77431. // Open a transaction to the database
  77432. var transaction = _this.db.transaction([targetStore], "readwrite");
  77433. // the transaction could abort because of a QuotaExceededError error
  77434. transaction.onabort = function (event) {
  77435. try {
  77436. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77437. var error = event.srcElement['error'];
  77438. if (error && error.name === "QuotaExceededError") {
  77439. _this.hasReachedQuota = true;
  77440. }
  77441. }
  77442. catch (ex) { }
  77443. callback(fileData);
  77444. };
  77445. transaction.oncomplete = function (event) {
  77446. callback(fileData);
  77447. };
  77448. var newFile;
  77449. if (targetStore === "scenes") {
  77450. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  77451. }
  77452. else {
  77453. newFile = { textureUrl: url, data: fileData };
  77454. }
  77455. try {
  77456. // Put the scene into the database
  77457. var addRequest = transaction.objectStore(targetStore).put(newFile);
  77458. addRequest.onsuccess = function (event) {
  77459. };
  77460. addRequest.onerror = function (event) {
  77461. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  77462. };
  77463. }
  77464. catch (ex) {
  77465. callback(fileData);
  77466. }
  77467. }
  77468. else {
  77469. callback(fileData);
  77470. }
  77471. }
  77472. else {
  77473. if (xhr.status >= 400 && errorCallback) {
  77474. errorCallback(xhr);
  77475. }
  77476. else {
  77477. callback();
  77478. }
  77479. }
  77480. }, false);
  77481. xhr.addEventListener("error", function (event) {
  77482. BABYLON.Tools.Error("error on XHR request.");
  77483. callback();
  77484. }, false);
  77485. xhr.send();
  77486. }
  77487. else {
  77488. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77489. callback();
  77490. }
  77491. };
  77492. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  77493. Database.IsUASupportingBlobStorage = true;
  77494. /** Gets a boolean indicating if Database storate is enabled */
  77495. Database.IDBStorageEnabled = true;
  77496. Database._ParseURL = function (url) {
  77497. var a = document.createElement('a');
  77498. a.href = url;
  77499. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  77500. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  77501. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  77502. return absLocation;
  77503. };
  77504. Database._ReturnFullUrlLocation = function (url) {
  77505. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  77506. return (Database._ParseURL(window.location.href) + url);
  77507. }
  77508. else {
  77509. return url;
  77510. }
  77511. };
  77512. return Database;
  77513. }());
  77514. BABYLON.Database = Database;
  77515. })(BABYLON || (BABYLON = {}));
  77516. //# sourceMappingURL=babylon.database.js.map
  77517. var BABYLON;
  77518. (function (BABYLON) {
  77519. /**
  77520. * This represents all the required information to add a fresnel effect on a material:
  77521. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  77522. */
  77523. var FresnelParameters = /** @class */ (function () {
  77524. function FresnelParameters() {
  77525. this._isEnabled = true;
  77526. /**
  77527. * Define the color used on edges (grazing angle)
  77528. */
  77529. this.leftColor = BABYLON.Color3.White();
  77530. /**
  77531. * Define the color used on center
  77532. */
  77533. this.rightColor = BABYLON.Color3.Black();
  77534. /**
  77535. * Define bias applied to computed fresnel term
  77536. */
  77537. this.bias = 0;
  77538. /**
  77539. * Defined the power exponent applied to fresnel term
  77540. */
  77541. this.power = 1;
  77542. }
  77543. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  77544. /**
  77545. * Define if the fresnel effect is enable or not.
  77546. */
  77547. get: function () {
  77548. return this._isEnabled;
  77549. },
  77550. set: function (value) {
  77551. if (this._isEnabled === value) {
  77552. return;
  77553. }
  77554. this._isEnabled = value;
  77555. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  77556. },
  77557. enumerable: true,
  77558. configurable: true
  77559. });
  77560. /**
  77561. * Clones the current fresnel and its valuues
  77562. * @returns a clone fresnel configuration
  77563. */
  77564. FresnelParameters.prototype.clone = function () {
  77565. var newFresnelParameters = new FresnelParameters();
  77566. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  77567. return newFresnelParameters;
  77568. };
  77569. /**
  77570. * Serializes the current fresnel parameters to a JSON representation.
  77571. * @return the JSON serialization
  77572. */
  77573. FresnelParameters.prototype.serialize = function () {
  77574. var serializationObject = {};
  77575. serializationObject.isEnabled = this.isEnabled;
  77576. serializationObject.leftColor = this.leftColor.asArray();
  77577. serializationObject.rightColor = this.rightColor.asArray();
  77578. serializationObject.bias = this.bias;
  77579. serializationObject.power = this.power;
  77580. return serializationObject;
  77581. };
  77582. /**
  77583. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  77584. * @param parsedFresnelParameters Define the JSON representation
  77585. * @returns the parsed parameters
  77586. */
  77587. FresnelParameters.Parse = function (parsedFresnelParameters) {
  77588. var fresnelParameters = new FresnelParameters();
  77589. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  77590. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  77591. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  77592. fresnelParameters.bias = parsedFresnelParameters.bias;
  77593. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  77594. return fresnelParameters;
  77595. };
  77596. return FresnelParameters;
  77597. }());
  77598. BABYLON.FresnelParameters = FresnelParameters;
  77599. })(BABYLON || (BABYLON = {}));
  77600. //# sourceMappingURL=babylon.fresnelParameters.js.map
  77601. var BABYLON;
  77602. (function (BABYLON) {
  77603. /**
  77604. * A multi-material is used to apply different materials to different parts of the same object without the need of
  77605. * separate meshes. This can be use to improve performances.
  77606. * @see http://doc.babylonjs.com/how_to/multi_materials
  77607. */
  77608. var MultiMaterial = /** @class */ (function (_super) {
  77609. __extends(MultiMaterial, _super);
  77610. /**
  77611. * Instantiates a new Multi Material
  77612. * A multi-material is used to apply different materials to different parts of the same object without the need of
  77613. * separate meshes. This can be use to improve performances.
  77614. * @see http://doc.babylonjs.com/how_to/multi_materials
  77615. * @param name Define the name in the scene
  77616. * @param scene Define the scene the material belongs to
  77617. */
  77618. function MultiMaterial(name, scene) {
  77619. var _this = _super.call(this, name, scene, true) || this;
  77620. scene.multiMaterials.push(_this);
  77621. _this.subMaterials = new Array();
  77622. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  77623. return _this;
  77624. }
  77625. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  77626. /**
  77627. * Gets or Sets the list of Materials used within the multi material.
  77628. * They need to be ordered according to the submeshes order in the associated mesh
  77629. */
  77630. get: function () {
  77631. return this._subMaterials;
  77632. },
  77633. set: function (value) {
  77634. this._subMaterials = value;
  77635. this._hookArray(value);
  77636. },
  77637. enumerable: true,
  77638. configurable: true
  77639. });
  77640. MultiMaterial.prototype._hookArray = function (array) {
  77641. var _this = this;
  77642. var oldPush = array.push;
  77643. array.push = function () {
  77644. var items = [];
  77645. for (var _i = 0; _i < arguments.length; _i++) {
  77646. items[_i] = arguments[_i];
  77647. }
  77648. var result = oldPush.apply(array, items);
  77649. _this._markAllSubMeshesAsTexturesDirty();
  77650. return result;
  77651. };
  77652. var oldSplice = array.splice;
  77653. array.splice = function (index, deleteCount) {
  77654. var deleted = oldSplice.apply(array, [index, deleteCount]);
  77655. _this._markAllSubMeshesAsTexturesDirty();
  77656. return deleted;
  77657. };
  77658. };
  77659. /**
  77660. * Get one of the submaterial by its index in the submaterials array
  77661. * @param index The index to look the sub material at
  77662. * @returns The Material if the index has been defined
  77663. */
  77664. MultiMaterial.prototype.getSubMaterial = function (index) {
  77665. if (index < 0 || index >= this.subMaterials.length) {
  77666. return this.getScene().defaultMaterial;
  77667. }
  77668. return this.subMaterials[index];
  77669. };
  77670. /**
  77671. * Get the list of active textures for the whole sub materials list.
  77672. * @returns All the textures that will be used during the rendering
  77673. */
  77674. MultiMaterial.prototype.getActiveTextures = function () {
  77675. var _a;
  77676. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  77677. if (subMaterial) {
  77678. return subMaterial.getActiveTextures();
  77679. }
  77680. else {
  77681. return [];
  77682. }
  77683. }));
  77684. };
  77685. /**
  77686. * Gets the current class name of the material e.g. "MultiMaterial"
  77687. * Mainly use in serialization.
  77688. * @returns the class name
  77689. */
  77690. MultiMaterial.prototype.getClassName = function () {
  77691. return "MultiMaterial";
  77692. };
  77693. /**
  77694. * Checks if the material is ready to render the requested sub mesh
  77695. * @param mesh Define the mesh the submesh belongs to
  77696. * @param subMesh Define the sub mesh to look readyness for
  77697. * @param useInstances Define whether or not the material is used with instances
  77698. * @returns true if ready, otherwise false
  77699. */
  77700. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  77701. for (var index = 0; index < this.subMaterials.length; index++) {
  77702. var subMaterial = this.subMaterials[index];
  77703. if (subMaterial) {
  77704. if (subMaterial.storeEffectOnSubMeshes) {
  77705. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  77706. return false;
  77707. }
  77708. continue;
  77709. }
  77710. if (!subMaterial.isReady(mesh)) {
  77711. return false;
  77712. }
  77713. }
  77714. }
  77715. return true;
  77716. };
  77717. /**
  77718. * Clones the current material and its related sub materials
  77719. * @param name Define the name of the newly cloned material
  77720. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  77721. * @returns the cloned material
  77722. */
  77723. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  77724. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  77725. for (var index = 0; index < this.subMaterials.length; index++) {
  77726. var subMaterial = null;
  77727. var current = this.subMaterials[index];
  77728. if (cloneChildren && current) {
  77729. subMaterial = current.clone(name + "-" + current.name);
  77730. }
  77731. else {
  77732. subMaterial = this.subMaterials[index];
  77733. }
  77734. newMultiMaterial.subMaterials.push(subMaterial);
  77735. }
  77736. return newMultiMaterial;
  77737. };
  77738. /**
  77739. * Serializes the materials into a JSON representation.
  77740. * @returns the JSON representation
  77741. */
  77742. MultiMaterial.prototype.serialize = function () {
  77743. var serializationObject = {};
  77744. serializationObject.name = this.name;
  77745. serializationObject.id = this.id;
  77746. if (BABYLON.Tags) {
  77747. serializationObject.tags = BABYLON.Tags.GetTags(this);
  77748. }
  77749. serializationObject.materials = [];
  77750. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  77751. var subMat = this.subMaterials[matIndex];
  77752. if (subMat) {
  77753. serializationObject.materials.push(subMat.id);
  77754. }
  77755. else {
  77756. serializationObject.materials.push(null);
  77757. }
  77758. }
  77759. return serializationObject;
  77760. };
  77761. /**
  77762. * Dispose the material and release its associated resources
  77763. * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
  77764. * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
  77765. */
  77766. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  77767. var scene = this.getScene();
  77768. if (!scene) {
  77769. return;
  77770. }
  77771. var index = scene.multiMaterials.indexOf(this);
  77772. if (index >= 0) {
  77773. scene.multiMaterials.splice(index, 1);
  77774. }
  77775. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  77776. };
  77777. return MultiMaterial;
  77778. }(BABYLON.Material));
  77779. BABYLON.MultiMaterial = MultiMaterial;
  77780. })(BABYLON || (BABYLON = {}));
  77781. //# sourceMappingURL=babylon.multiMaterial.js.map
  77782. var BABYLON;
  77783. (function (BABYLON) {
  77784. /**
  77785. * Manage the touch inputs to control the movement of a free camera.
  77786. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77787. */
  77788. var FreeCameraTouchInput = /** @class */ (function () {
  77789. function FreeCameraTouchInput() {
  77790. /**
  77791. * Defines the touch sensibility for rotation.
  77792. * The higher the faster.
  77793. */
  77794. this.touchAngularSensibility = 200000.0;
  77795. /**
  77796. * Defines the touch sensibility for move.
  77797. * The higher the faster.
  77798. */
  77799. this.touchMoveSensibility = 250.0;
  77800. this._offsetX = null;
  77801. this._offsetY = null;
  77802. this._pointerPressed = new Array();
  77803. }
  77804. /**
  77805. * Attach the input controls to a specific dom element to get the input from.
  77806. * @param element Defines the element the controls should be listened from
  77807. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77808. */
  77809. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  77810. var _this = this;
  77811. var previousPosition = null;
  77812. if (this._pointerInput === undefined) {
  77813. this._onLostFocus = function (evt) {
  77814. _this._offsetX = null;
  77815. _this._offsetY = null;
  77816. };
  77817. this._pointerInput = function (p, s) {
  77818. var evt = p.event;
  77819. if (evt.pointerType === "mouse") {
  77820. return;
  77821. }
  77822. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77823. if (!noPreventDefault) {
  77824. evt.preventDefault();
  77825. }
  77826. _this._pointerPressed.push(evt.pointerId);
  77827. if (_this._pointerPressed.length !== 1) {
  77828. return;
  77829. }
  77830. previousPosition = {
  77831. x: evt.clientX,
  77832. y: evt.clientY
  77833. };
  77834. }
  77835. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  77836. if (!noPreventDefault) {
  77837. evt.preventDefault();
  77838. }
  77839. var index = _this._pointerPressed.indexOf(evt.pointerId);
  77840. if (index === -1) {
  77841. return;
  77842. }
  77843. _this._pointerPressed.splice(index, 1);
  77844. if (index != 0) {
  77845. return;
  77846. }
  77847. previousPosition = null;
  77848. _this._offsetX = null;
  77849. _this._offsetY = null;
  77850. }
  77851. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  77852. if (!noPreventDefault) {
  77853. evt.preventDefault();
  77854. }
  77855. if (!previousPosition) {
  77856. return;
  77857. }
  77858. var index = _this._pointerPressed.indexOf(evt.pointerId);
  77859. if (index != 0) {
  77860. return;
  77861. }
  77862. _this._offsetX = evt.clientX - previousPosition.x;
  77863. _this._offsetY = -(evt.clientY - previousPosition.y);
  77864. }
  77865. };
  77866. }
  77867. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  77868. if (this._onLostFocus) {
  77869. element.addEventListener("blur", this._onLostFocus);
  77870. }
  77871. };
  77872. /**
  77873. * Detach the current controls from the specified dom element.
  77874. * @param element Defines the element to stop listening the inputs from
  77875. */
  77876. FreeCameraTouchInput.prototype.detachControl = function (element) {
  77877. if (this._pointerInput && element) {
  77878. if (this._observer) {
  77879. this.camera.getScene().onPointerObservable.remove(this._observer);
  77880. this._observer = null;
  77881. }
  77882. if (this._onLostFocus) {
  77883. element.removeEventListener("blur", this._onLostFocus);
  77884. this._onLostFocus = null;
  77885. }
  77886. this._pointerPressed = [];
  77887. this._offsetX = null;
  77888. this._offsetY = null;
  77889. }
  77890. };
  77891. /**
  77892. * Update the current camera state depending on the inputs that have been used this frame.
  77893. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77894. */
  77895. FreeCameraTouchInput.prototype.checkInputs = function () {
  77896. if (this._offsetX && this._offsetY) {
  77897. var camera = this.camera;
  77898. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  77899. if (this._pointerPressed.length > 1) {
  77900. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  77901. }
  77902. else {
  77903. var speed = camera._computeLocalCameraSpeed();
  77904. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  77905. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  77906. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  77907. }
  77908. }
  77909. };
  77910. /**
  77911. * Gets the class name of the current intput.
  77912. * @returns the class name
  77913. */
  77914. FreeCameraTouchInput.prototype.getClassName = function () {
  77915. return "FreeCameraTouchInput";
  77916. };
  77917. /**
  77918. * Get the friendly name associated with the input class.
  77919. * @returns the input friendly name
  77920. */
  77921. FreeCameraTouchInput.prototype.getSimpleName = function () {
  77922. return "touch";
  77923. };
  77924. __decorate([
  77925. BABYLON.serialize()
  77926. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  77927. __decorate([
  77928. BABYLON.serialize()
  77929. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  77930. return FreeCameraTouchInput;
  77931. }());
  77932. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  77933. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  77934. })(BABYLON || (BABYLON = {}));
  77935. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  77936. var BABYLON;
  77937. (function (BABYLON) {
  77938. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  77939. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  77940. });
  77941. /**
  77942. * This represents a FPS type of camera controlled by touch.
  77943. * This is like a universal camera minus the Gamepad controls.
  77944. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  77945. */
  77946. var TouchCamera = /** @class */ (function (_super) {
  77947. __extends(TouchCamera, _super);
  77948. /**
  77949. * Instantiates a new touch camera.
  77950. * This represents a FPS type of camera controlled by touch.
  77951. * This is like a universal camera minus the Gamepad controls.
  77952. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  77953. * @param name Define the name of the camera in the scene
  77954. * @param position Define the start position of the camera in the scene
  77955. * @param scene Define the scene the camera belongs to
  77956. */
  77957. function TouchCamera(name, position, scene) {
  77958. var _this = _super.call(this, name, position, scene) || this;
  77959. _this.inputs.addTouch();
  77960. _this._setupInputs();
  77961. return _this;
  77962. }
  77963. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  77964. /**
  77965. * Defines the touch sensibility for rotation.
  77966. * The higher the faster.
  77967. */
  77968. get: function () {
  77969. var touch = this.inputs.attached["touch"];
  77970. if (touch)
  77971. return touch.touchAngularSensibility;
  77972. return 0;
  77973. },
  77974. set: function (value) {
  77975. var touch = this.inputs.attached["touch"];
  77976. if (touch)
  77977. touch.touchAngularSensibility = value;
  77978. },
  77979. enumerable: true,
  77980. configurable: true
  77981. });
  77982. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  77983. /**
  77984. * Defines the touch sensibility for move.
  77985. * The higher the faster.
  77986. */
  77987. get: function () {
  77988. var touch = this.inputs.attached["touch"];
  77989. if (touch)
  77990. return touch.touchMoveSensibility;
  77991. return 0;
  77992. },
  77993. set: function (value) {
  77994. var touch = this.inputs.attached["touch"];
  77995. if (touch)
  77996. touch.touchMoveSensibility = value;
  77997. },
  77998. enumerable: true,
  77999. configurable: true
  78000. });
  78001. /**
  78002. * Gets the current object class name.
  78003. * @return the class name
  78004. */
  78005. TouchCamera.prototype.getClassName = function () {
  78006. return "TouchCamera";
  78007. };
  78008. /** @hidden */
  78009. TouchCamera.prototype._setupInputs = function () {
  78010. var mouse = this.inputs.attached["mouse"];
  78011. if (mouse) {
  78012. mouse.touchEnabled = false;
  78013. }
  78014. };
  78015. return TouchCamera;
  78016. }(BABYLON.FreeCamera));
  78017. BABYLON.TouchCamera = TouchCamera;
  78018. })(BABYLON || (BABYLON = {}));
  78019. //# sourceMappingURL=babylon.touchCamera.js.map
  78020. var BABYLON;
  78021. (function (BABYLON) {
  78022. /**
  78023. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78024. * This is the base class of any Procedural texture and contains most of the shareable code.
  78025. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78026. */
  78027. var ProceduralTexture = /** @class */ (function (_super) {
  78028. __extends(ProceduralTexture, _super);
  78029. /**
  78030. * Instantiates a new procedural texture.
  78031. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78032. * This is the base class of any Procedural texture and contains most of the shareable code.
  78033. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78034. * @param name Define the name of the texture
  78035. * @param size Define the size of the texture to create
  78036. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  78037. * @param scene Define the scene the texture belongs to
  78038. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  78039. * @param generateMipMaps Define if the texture should creates mip maps or not
  78040. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  78041. */
  78042. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  78043. if (fallbackTexture === void 0) { fallbackTexture = null; }
  78044. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78045. if (isCube === void 0) { isCube = false; }
  78046. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  78047. _this.isCube = isCube;
  78048. /**
  78049. * Define if the texture is enabled or not (disabled texture will not render)
  78050. */
  78051. _this.isEnabled = true;
  78052. /**
  78053. * Event raised when the texture is generated
  78054. */
  78055. _this.onGeneratedObservable = new BABYLON.Observable();
  78056. /** @hidden */
  78057. _this._textures = {};
  78058. _this._currentRefreshId = -1;
  78059. _this._refreshRate = 1;
  78060. _this._vertexBuffers = {};
  78061. _this._uniforms = new Array();
  78062. _this._samplers = new Array();
  78063. _this._floats = {};
  78064. _this._ints = {};
  78065. _this._floatsArrays = {};
  78066. _this._colors3 = {};
  78067. _this._colors4 = {};
  78068. _this._vectors2 = {};
  78069. _this._vectors3 = {};
  78070. _this._matrices = {};
  78071. _this._fallbackTextureUsed = false;
  78072. _this._cachedDefines = "";
  78073. _this._contentUpdateId = -1;
  78074. scene = _this.getScene();
  78075. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  78076. if (!component) {
  78077. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  78078. scene._addComponent(component);
  78079. }
  78080. scene.proceduralTextures.push(_this);
  78081. _this._engine = scene.getEngine();
  78082. _this.name = name;
  78083. _this.isRenderTarget = true;
  78084. _this._size = size;
  78085. _this._generateMipMaps = generateMipMaps;
  78086. _this.setFragment(fragment);
  78087. _this._fallbackTexture = fallbackTexture;
  78088. if (isCube) {
  78089. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  78090. _this.setFloat("face", 0);
  78091. }
  78092. else {
  78093. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  78094. }
  78095. // VBO
  78096. var vertices = [];
  78097. vertices.push(1, 1);
  78098. vertices.push(-1, 1);
  78099. vertices.push(-1, -1);
  78100. vertices.push(1, -1);
  78101. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78102. _this._createIndexBuffer();
  78103. return _this;
  78104. }
  78105. /**
  78106. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  78107. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  78108. */
  78109. ProceduralTexture.prototype.getContent = function () {
  78110. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  78111. return this._contentData;
  78112. }
  78113. this._contentData = this.readPixels(0, 0, this._contentData);
  78114. this._contentUpdateId = this._currentRefreshId;
  78115. return this._contentData;
  78116. };
  78117. ProceduralTexture.prototype._createIndexBuffer = function () {
  78118. var engine = this._engine;
  78119. // Indices
  78120. var indices = [];
  78121. indices.push(0);
  78122. indices.push(1);
  78123. indices.push(2);
  78124. indices.push(0);
  78125. indices.push(2);
  78126. indices.push(3);
  78127. this._indexBuffer = engine.createIndexBuffer(indices);
  78128. };
  78129. /** @hidden */
  78130. ProceduralTexture.prototype._rebuild = function () {
  78131. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78132. if (vb) {
  78133. vb._rebuild();
  78134. }
  78135. this._createIndexBuffer();
  78136. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  78137. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  78138. }
  78139. };
  78140. /**
  78141. * Resets the texture in order to recreate its associated resources.
  78142. * This can be called in case of context loss
  78143. */
  78144. ProceduralTexture.prototype.reset = function () {
  78145. if (this._effect === undefined) {
  78146. return;
  78147. }
  78148. var engine = this._engine;
  78149. engine._releaseEffect(this._effect);
  78150. };
  78151. ProceduralTexture.prototype._getDefines = function () {
  78152. return "";
  78153. };
  78154. /**
  78155. * Is the texture ready to be used ? (rendered at least once)
  78156. * @returns true if ready, otherwise, false.
  78157. */
  78158. ProceduralTexture.prototype.isReady = function () {
  78159. var _this = this;
  78160. var engine = this._engine;
  78161. var shaders;
  78162. if (!this._fragment) {
  78163. return false;
  78164. }
  78165. if (this._fallbackTextureUsed) {
  78166. return true;
  78167. }
  78168. var defines = this._getDefines();
  78169. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  78170. return true;
  78171. }
  78172. if (this._fragment.fragmentElement !== undefined) {
  78173. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  78174. }
  78175. else {
  78176. shaders = { vertex: "procedural", fragment: this._fragment };
  78177. }
  78178. this._cachedDefines = defines;
  78179. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  78180. _this.releaseInternalTexture();
  78181. if (_this._fallbackTexture) {
  78182. _this._texture = _this._fallbackTexture._texture;
  78183. if (_this._texture) {
  78184. _this._texture.incrementReferences();
  78185. }
  78186. }
  78187. _this._fallbackTextureUsed = true;
  78188. });
  78189. return this._effect.isReady();
  78190. };
  78191. /**
  78192. * Resets the refresh counter of the texture and start bak from scratch.
  78193. * Could be usefull to regenerate the texture if it is setup to render only once.
  78194. */
  78195. ProceduralTexture.prototype.resetRefreshCounter = function () {
  78196. this._currentRefreshId = -1;
  78197. };
  78198. /**
  78199. * Set the fragment shader to use in order to render the texture.
  78200. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  78201. */
  78202. ProceduralTexture.prototype.setFragment = function (fragment) {
  78203. this._fragment = fragment;
  78204. };
  78205. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  78206. /**
  78207. * Define the refresh rate of the texture or the rendering frequency.
  78208. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  78209. */
  78210. get: function () {
  78211. return this._refreshRate;
  78212. },
  78213. set: function (value) {
  78214. this._refreshRate = value;
  78215. this.resetRefreshCounter();
  78216. },
  78217. enumerable: true,
  78218. configurable: true
  78219. });
  78220. /** @hidden */
  78221. ProceduralTexture.prototype._shouldRender = function () {
  78222. if (!this.isEnabled || !this.isReady() || !this._texture) {
  78223. if (this._texture) {
  78224. this._texture.isReady = false;
  78225. }
  78226. return false;
  78227. }
  78228. if (this._fallbackTextureUsed) {
  78229. return false;
  78230. }
  78231. if (this._currentRefreshId === -1) { // At least render once
  78232. this._currentRefreshId = 1;
  78233. return true;
  78234. }
  78235. if (this.refreshRate === this._currentRefreshId) {
  78236. this._currentRefreshId = 1;
  78237. return true;
  78238. }
  78239. this._currentRefreshId++;
  78240. return false;
  78241. };
  78242. /**
  78243. * Get the size the texture is rendering at.
  78244. * @returns the size (texture is always squared)
  78245. */
  78246. ProceduralTexture.prototype.getRenderSize = function () {
  78247. return this._size;
  78248. };
  78249. /**
  78250. * Resize the texture to new value.
  78251. * @param size Define the new size the texture should have
  78252. * @param generateMipMaps Define whether the new texture should create mip maps
  78253. */
  78254. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  78255. if (this._fallbackTextureUsed) {
  78256. return;
  78257. }
  78258. this.releaseInternalTexture();
  78259. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  78260. // Update properties
  78261. this._size = size;
  78262. this._generateMipMaps = generateMipMaps;
  78263. };
  78264. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  78265. if (this._uniforms.indexOf(uniformName) === -1) {
  78266. this._uniforms.push(uniformName);
  78267. }
  78268. };
  78269. /**
  78270. * Set a texture in the shader program used to render.
  78271. * @param name Define the name of the uniform samplers as defined in the shader
  78272. * @param texture Define the texture to bind to this sampler
  78273. * @return the texture itself allowing "fluent" like uniform updates
  78274. */
  78275. ProceduralTexture.prototype.setTexture = function (name, texture) {
  78276. if (this._samplers.indexOf(name) === -1) {
  78277. this._samplers.push(name);
  78278. }
  78279. this._textures[name] = texture;
  78280. return this;
  78281. };
  78282. /**
  78283. * Set a float in the shader.
  78284. * @param name Define the name of the uniform as defined in the shader
  78285. * @param value Define the value to give to the uniform
  78286. * @return the texture itself allowing "fluent" like uniform updates
  78287. */
  78288. ProceduralTexture.prototype.setFloat = function (name, value) {
  78289. this._checkUniform(name);
  78290. this._floats[name] = value;
  78291. return this;
  78292. };
  78293. /**
  78294. * Set a int in the shader.
  78295. * @param name Define the name of the uniform as defined in the shader
  78296. * @param value Define the value to give to the uniform
  78297. * @return the texture itself allowing "fluent" like uniform updates
  78298. */
  78299. ProceduralTexture.prototype.setInt = function (name, value) {
  78300. this._checkUniform(name);
  78301. this._ints[name] = value;
  78302. return this;
  78303. };
  78304. /**
  78305. * Set an array of floats in the shader.
  78306. * @param name Define the name of the uniform as defined in the shader
  78307. * @param value Define the value to give to the uniform
  78308. * @return the texture itself allowing "fluent" like uniform updates
  78309. */
  78310. ProceduralTexture.prototype.setFloats = function (name, value) {
  78311. this._checkUniform(name);
  78312. this._floatsArrays[name] = value;
  78313. return this;
  78314. };
  78315. /**
  78316. * Set a vec3 in the shader from a Color3.
  78317. * @param name Define the name of the uniform as defined in the shader
  78318. * @param value Define the value to give to the uniform
  78319. * @return the texture itself allowing "fluent" like uniform updates
  78320. */
  78321. ProceduralTexture.prototype.setColor3 = function (name, value) {
  78322. this._checkUniform(name);
  78323. this._colors3[name] = value;
  78324. return this;
  78325. };
  78326. /**
  78327. * Set a vec4 in the shader from a Color4.
  78328. * @param name Define the name of the uniform as defined in the shader
  78329. * @param value Define the value to give to the uniform
  78330. * @return the texture itself allowing "fluent" like uniform updates
  78331. */
  78332. ProceduralTexture.prototype.setColor4 = function (name, value) {
  78333. this._checkUniform(name);
  78334. this._colors4[name] = value;
  78335. return this;
  78336. };
  78337. /**
  78338. * Set a vec2 in the shader from a Vector2.
  78339. * @param name Define the name of the uniform as defined in the shader
  78340. * @param value Define the value to give to the uniform
  78341. * @return the texture itself allowing "fluent" like uniform updates
  78342. */
  78343. ProceduralTexture.prototype.setVector2 = function (name, value) {
  78344. this._checkUniform(name);
  78345. this._vectors2[name] = value;
  78346. return this;
  78347. };
  78348. /**
  78349. * Set a vec3 in the shader from a Vector3.
  78350. * @param name Define the name of the uniform as defined in the shader
  78351. * @param value Define the value to give to the uniform
  78352. * @return the texture itself allowing "fluent" like uniform updates
  78353. */
  78354. ProceduralTexture.prototype.setVector3 = function (name, value) {
  78355. this._checkUniform(name);
  78356. this._vectors3[name] = value;
  78357. return this;
  78358. };
  78359. /**
  78360. * Set a mat4 in the shader from a MAtrix.
  78361. * @param name Define the name of the uniform as defined in the shader
  78362. * @param value Define the value to give to the uniform
  78363. * @return the texture itself allowing "fluent" like uniform updates
  78364. */
  78365. ProceduralTexture.prototype.setMatrix = function (name, value) {
  78366. this._checkUniform(name);
  78367. this._matrices[name] = value;
  78368. return this;
  78369. };
  78370. /**
  78371. * Render the texture to its associated render target.
  78372. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  78373. */
  78374. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  78375. var scene = this.getScene();
  78376. if (!scene) {
  78377. return;
  78378. }
  78379. var engine = this._engine;
  78380. // Render
  78381. engine.enableEffect(this._effect);
  78382. engine.setState(false);
  78383. // Texture
  78384. for (var name in this._textures) {
  78385. this._effect.setTexture(name, this._textures[name]);
  78386. }
  78387. // Float
  78388. for (name in this._ints) {
  78389. this._effect.setInt(name, this._ints[name]);
  78390. }
  78391. // Float
  78392. for (name in this._floats) {
  78393. this._effect.setFloat(name, this._floats[name]);
  78394. }
  78395. // Floats
  78396. for (name in this._floatsArrays) {
  78397. this._effect.setArray(name, this._floatsArrays[name]);
  78398. }
  78399. // Color3
  78400. for (name in this._colors3) {
  78401. this._effect.setColor3(name, this._colors3[name]);
  78402. }
  78403. // Color4
  78404. for (name in this._colors4) {
  78405. var color = this._colors4[name];
  78406. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  78407. }
  78408. // Vector2
  78409. for (name in this._vectors2) {
  78410. this._effect.setVector2(name, this._vectors2[name]);
  78411. }
  78412. // Vector3
  78413. for (name in this._vectors3) {
  78414. this._effect.setVector3(name, this._vectors3[name]);
  78415. }
  78416. // Matrix
  78417. for (name in this._matrices) {
  78418. this._effect.setMatrix(name, this._matrices[name]);
  78419. }
  78420. if (!this._texture) {
  78421. return;
  78422. }
  78423. if (this.isCube) {
  78424. for (var face = 0; face < 6; face++) {
  78425. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  78426. // VBOs
  78427. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  78428. this._effect.setFloat("face", face);
  78429. // Clear
  78430. engine.clear(scene.clearColor, true, true, true);
  78431. // Draw order
  78432. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78433. // Mipmaps
  78434. if (face === 5) {
  78435. engine.generateMipMapsForCubemap(this._texture);
  78436. }
  78437. }
  78438. }
  78439. else {
  78440. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  78441. // VBOs
  78442. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  78443. // Clear
  78444. engine.clear(scene.clearColor, true, true, true);
  78445. // Draw order
  78446. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78447. }
  78448. // Unbind
  78449. engine.unBindFramebuffer(this._texture, this.isCube);
  78450. if (this.onGenerated) {
  78451. this.onGenerated();
  78452. }
  78453. this.onGeneratedObservable.notifyObservers(this);
  78454. };
  78455. /**
  78456. * Clone the texture.
  78457. * @returns the cloned texture
  78458. */
  78459. ProceduralTexture.prototype.clone = function () {
  78460. var textureSize = this.getSize();
  78461. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  78462. // Base texture
  78463. newTexture.hasAlpha = this.hasAlpha;
  78464. newTexture.level = this.level;
  78465. // RenderTarget Texture
  78466. newTexture.coordinatesMode = this.coordinatesMode;
  78467. return newTexture;
  78468. };
  78469. /**
  78470. * Dispose the texture and release its asoociated resources.
  78471. */
  78472. ProceduralTexture.prototype.dispose = function () {
  78473. var scene = this.getScene();
  78474. if (!scene) {
  78475. return;
  78476. }
  78477. var index = scene.proceduralTextures.indexOf(this);
  78478. if (index >= 0) {
  78479. scene.proceduralTextures.splice(index, 1);
  78480. }
  78481. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78482. if (vertexBuffer) {
  78483. vertexBuffer.dispose();
  78484. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78485. }
  78486. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  78487. this._indexBuffer = null;
  78488. }
  78489. _super.prototype.dispose.call(this);
  78490. };
  78491. __decorate([
  78492. BABYLON.serialize()
  78493. ], ProceduralTexture.prototype, "isEnabled", void 0);
  78494. __decorate([
  78495. BABYLON.serialize()
  78496. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  78497. __decorate([
  78498. BABYLON.serialize()
  78499. ], ProceduralTexture.prototype, "_size", void 0);
  78500. __decorate([
  78501. BABYLON.serialize()
  78502. ], ProceduralTexture.prototype, "refreshRate", null);
  78503. return ProceduralTexture;
  78504. }(BABYLON.Texture));
  78505. BABYLON.ProceduralTexture = ProceduralTexture;
  78506. })(BABYLON || (BABYLON = {}));
  78507. //# sourceMappingURL=babylon.proceduralTexture.js.map
  78508. var BABYLON;
  78509. (function (BABYLON) {
  78510. /**
  78511. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  78512. * in a given scene.
  78513. */
  78514. var ProceduralTextureSceneComponent = /** @class */ (function () {
  78515. /**
  78516. * Creates a new instance of the component for the given scene
  78517. * @param scene Defines the scene to register the component in
  78518. */
  78519. function ProceduralTextureSceneComponent(scene) {
  78520. /**
  78521. * The component name helpfull to identify the component in the list of scene components.
  78522. */
  78523. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  78524. this.scene = scene;
  78525. this.scene.proceduralTextures = new Array();
  78526. scene.layers = new Array();
  78527. }
  78528. /**
  78529. * Registers the component in a given scene
  78530. */
  78531. ProceduralTextureSceneComponent.prototype.register = function () {
  78532. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  78533. };
  78534. /**
  78535. * Rebuilds the elements related to this component in case of
  78536. * context lost for instance.
  78537. */
  78538. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  78539. // Nothing to do here.
  78540. };
  78541. /**
  78542. * Disposes the component and the associated ressources.
  78543. */
  78544. ProceduralTextureSceneComponent.prototype.dispose = function () {
  78545. // Nothing to do here.
  78546. };
  78547. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  78548. if (this.scene.proceduralTexturesEnabled) {
  78549. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  78550. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  78551. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  78552. if (proceduralTexture._shouldRender()) {
  78553. proceduralTexture.render();
  78554. }
  78555. }
  78556. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  78557. }
  78558. };
  78559. return ProceduralTextureSceneComponent;
  78560. }());
  78561. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  78562. })(BABYLON || (BABYLON = {}));
  78563. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  78564. var BABYLON;
  78565. (function (BABYLON) {
  78566. /**
  78567. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78568. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  78569. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  78570. */
  78571. var CustomProceduralTexture = /** @class */ (function (_super) {
  78572. __extends(CustomProceduralTexture, _super);
  78573. /**
  78574. * Instantiates a new Custom Procedural Texture.
  78575. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78576. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  78577. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  78578. * @param name Define the name of the texture
  78579. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  78580. * @param size Define the size of the texture to create
  78581. * @param scene Define the scene the texture belongs to
  78582. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  78583. * @param generateMipMaps Define if the texture should creates mip maps or not
  78584. */
  78585. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  78586. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  78587. _this._animate = true;
  78588. _this._time = 0;
  78589. _this._texturePath = texturePath;
  78590. //Try to load json
  78591. _this._loadJson(texturePath);
  78592. _this.refreshRate = 1;
  78593. return _this;
  78594. }
  78595. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  78596. var _this = this;
  78597. var noConfigFile = function () {
  78598. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  78599. try {
  78600. _this.setFragment(_this._texturePath);
  78601. }
  78602. catch (ex) {
  78603. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  78604. }
  78605. };
  78606. var configFileUrl = jsonUrl + "/config.json";
  78607. var xhr = new XMLHttpRequest();
  78608. xhr.open("GET", configFileUrl, true);
  78609. xhr.addEventListener("load", function () {
  78610. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  78611. try {
  78612. _this._config = JSON.parse(xhr.response);
  78613. _this.updateShaderUniforms();
  78614. _this.updateTextures();
  78615. _this.setFragment(_this._texturePath + "/custom");
  78616. _this._animate = _this._config.animate;
  78617. _this.refreshRate = _this._config.refreshrate;
  78618. }
  78619. catch (ex) {
  78620. noConfigFile();
  78621. }
  78622. }
  78623. else {
  78624. noConfigFile();
  78625. }
  78626. }, false);
  78627. xhr.addEventListener("error", function () {
  78628. noConfigFile();
  78629. }, false);
  78630. try {
  78631. xhr.send();
  78632. }
  78633. catch (ex) {
  78634. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  78635. }
  78636. };
  78637. /**
  78638. * Is the texture ready to be used ? (rendered at least once)
  78639. * @returns true if ready, otherwise, false.
  78640. */
  78641. CustomProceduralTexture.prototype.isReady = function () {
  78642. if (!_super.prototype.isReady.call(this)) {
  78643. return false;
  78644. }
  78645. for (var name in this._textures) {
  78646. var texture = this._textures[name];
  78647. if (!texture.isReady()) {
  78648. return false;
  78649. }
  78650. }
  78651. return true;
  78652. };
  78653. /**
  78654. * Render the texture to its associated render target.
  78655. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  78656. */
  78657. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  78658. var scene = this.getScene();
  78659. if (this._animate && scene) {
  78660. this._time += scene.getAnimationRatio() * 0.03;
  78661. this.updateShaderUniforms();
  78662. }
  78663. _super.prototype.render.call(this, useCameraPostProcess);
  78664. };
  78665. /**
  78666. * Update the list of dependant textures samplers in the shader.
  78667. */
  78668. CustomProceduralTexture.prototype.updateTextures = function () {
  78669. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  78670. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  78671. }
  78672. };
  78673. /**
  78674. * Update the uniform values of the procedural texture in the shader.
  78675. */
  78676. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  78677. if (this._config) {
  78678. for (var j = 0; j < this._config.uniforms.length; j++) {
  78679. var uniform = this._config.uniforms[j];
  78680. switch (uniform.type) {
  78681. case "float":
  78682. this.setFloat(uniform.name, uniform.value);
  78683. break;
  78684. case "color3":
  78685. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  78686. break;
  78687. case "color4":
  78688. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  78689. break;
  78690. case "vector2":
  78691. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  78692. break;
  78693. case "vector3":
  78694. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  78695. break;
  78696. }
  78697. }
  78698. }
  78699. this.setFloat("time", this._time);
  78700. };
  78701. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  78702. /**
  78703. * Define if the texture animates or not.
  78704. */
  78705. get: function () {
  78706. return this._animate;
  78707. },
  78708. set: function (value) {
  78709. this._animate = value;
  78710. },
  78711. enumerable: true,
  78712. configurable: true
  78713. });
  78714. return CustomProceduralTexture;
  78715. }(BABYLON.ProceduralTexture));
  78716. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  78717. })(BABYLON || (BABYLON = {}));
  78718. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  78719. var BABYLON;
  78720. (function (BABYLON) {
  78721. /**
  78722. * Manage the gamepad inputs to control a free camera.
  78723. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78724. */
  78725. var FreeCameraGamepadInput = /** @class */ (function () {
  78726. function FreeCameraGamepadInput() {
  78727. /**
  78728. * Defines the gamepad rotation sensiblity.
  78729. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78730. */
  78731. this.gamepadAngularSensibility = 200;
  78732. /**
  78733. * Defines the gamepad move sensiblity.
  78734. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78735. */
  78736. this.gamepadMoveSensibility = 40;
  78737. this._cameraTransform = BABYLON.Matrix.Identity();
  78738. this._deltaTransform = BABYLON.Vector3.Zero();
  78739. this._vector3 = BABYLON.Vector3.Zero();
  78740. this._vector2 = BABYLON.Vector2.Zero();
  78741. }
  78742. /**
  78743. * Attach the input controls to a specific dom element to get the input from.
  78744. * @param element Defines the element the controls should be listened from
  78745. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78746. */
  78747. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  78748. var _this = this;
  78749. var manager = this.camera.getScene().gamepadManager;
  78750. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78751. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78752. // prioritize XBOX gamepads.
  78753. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  78754. _this.gamepad = gamepad;
  78755. }
  78756. }
  78757. });
  78758. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78759. if (_this.gamepad === gamepad) {
  78760. _this.gamepad = null;
  78761. }
  78762. });
  78763. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  78764. };
  78765. /**
  78766. * Detach the current controls from the specified dom element.
  78767. * @param element Defines the element to stop listening the inputs from
  78768. */
  78769. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  78770. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78771. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78772. this.gamepad = null;
  78773. };
  78774. /**
  78775. * Update the current camera state depending on the inputs that have been used this frame.
  78776. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78777. */
  78778. FreeCameraGamepadInput.prototype.checkInputs = function () {
  78779. if (this.gamepad && this.gamepad.leftStick) {
  78780. var camera = this.camera;
  78781. var LSValues = this.gamepad.leftStick;
  78782. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  78783. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  78784. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  78785. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  78786. var RSValues = this.gamepad.rightStick;
  78787. if (RSValues) {
  78788. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  78789. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  78790. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  78791. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  78792. }
  78793. else {
  78794. RSValues = { x: 0, y: 0 };
  78795. }
  78796. if (!camera.rotationQuaternion) {
  78797. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  78798. }
  78799. else {
  78800. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  78801. }
  78802. var speed = camera._computeLocalCameraSpeed() * 50.0;
  78803. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  78804. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  78805. camera.cameraDirection.addInPlace(this._deltaTransform);
  78806. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  78807. camera.cameraRotation.addInPlace(this._vector2);
  78808. }
  78809. };
  78810. /**
  78811. * Gets the class name of the current intput.
  78812. * @returns the class name
  78813. */
  78814. FreeCameraGamepadInput.prototype.getClassName = function () {
  78815. return "FreeCameraGamepadInput";
  78816. };
  78817. /**
  78818. * Get the friendly name associated with the input class.
  78819. * @returns the input friendly name
  78820. */
  78821. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  78822. return "gamepad";
  78823. };
  78824. __decorate([
  78825. BABYLON.serialize()
  78826. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  78827. __decorate([
  78828. BABYLON.serialize()
  78829. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  78830. return FreeCameraGamepadInput;
  78831. }());
  78832. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  78833. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  78834. })(BABYLON || (BABYLON = {}));
  78835. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  78836. var BABYLON;
  78837. (function (BABYLON) {
  78838. /**
  78839. * Manage the gamepad inputs to control an arc rotate camera.
  78840. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78841. */
  78842. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  78843. function ArcRotateCameraGamepadInput() {
  78844. /**
  78845. * Defines the gamepad rotation sensiblity.
  78846. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78847. */
  78848. this.gamepadRotationSensibility = 80;
  78849. /**
  78850. * Defines the gamepad move sensiblity.
  78851. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78852. */
  78853. this.gamepadMoveSensibility = 40;
  78854. }
  78855. /**
  78856. * Attach the input controls to a specific dom element to get the input from.
  78857. * @param element Defines the element the controls should be listened from
  78858. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78859. */
  78860. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  78861. var _this = this;
  78862. var manager = this.camera.getScene().gamepadManager;
  78863. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78864. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78865. // prioritize XBOX gamepads.
  78866. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  78867. _this.gamepad = gamepad;
  78868. }
  78869. }
  78870. });
  78871. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78872. if (_this.gamepad === gamepad) {
  78873. _this.gamepad = null;
  78874. }
  78875. });
  78876. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  78877. };
  78878. /**
  78879. * Detach the current controls from the specified dom element.
  78880. * @param element Defines the element to stop listening the inputs from
  78881. */
  78882. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  78883. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78884. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78885. this.gamepad = null;
  78886. };
  78887. /**
  78888. * Update the current camera state depending on the inputs that have been used this frame.
  78889. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78890. */
  78891. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  78892. if (this.gamepad) {
  78893. var camera = this.camera;
  78894. var RSValues = this.gamepad.rightStick;
  78895. if (RSValues) {
  78896. if (RSValues.x != 0) {
  78897. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  78898. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  78899. camera.inertialAlphaOffset += normalizedRX;
  78900. }
  78901. }
  78902. if (RSValues.y != 0) {
  78903. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  78904. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  78905. camera.inertialBetaOffset += normalizedRY;
  78906. }
  78907. }
  78908. }
  78909. var LSValues = this.gamepad.leftStick;
  78910. if (LSValues && LSValues.y != 0) {
  78911. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  78912. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  78913. this.camera.inertialRadiusOffset -= normalizedLY;
  78914. }
  78915. }
  78916. }
  78917. };
  78918. /**
  78919. * Gets the class name of the current intput.
  78920. * @returns the class name
  78921. */
  78922. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  78923. return "ArcRotateCameraGamepadInput";
  78924. };
  78925. /**
  78926. * Get the friendly name associated with the input class.
  78927. * @returns the input friendly name
  78928. */
  78929. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  78930. return "gamepad";
  78931. };
  78932. __decorate([
  78933. BABYLON.serialize()
  78934. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  78935. __decorate([
  78936. BABYLON.serialize()
  78937. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  78938. return ArcRotateCameraGamepadInput;
  78939. }());
  78940. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  78941. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  78942. })(BABYLON || (BABYLON = {}));
  78943. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  78944. var BABYLON;
  78945. (function (BABYLON) {
  78946. /**
  78947. * Manager for handling gamepads
  78948. */
  78949. var GamepadManager = /** @class */ (function () {
  78950. /**
  78951. * Initializes the gamepad manager
  78952. * @param _scene BabylonJS scene
  78953. */
  78954. function GamepadManager(_scene) {
  78955. var _this = this;
  78956. this._scene = _scene;
  78957. this._babylonGamepads = [];
  78958. this._oneGamepadConnected = false;
  78959. /** @hidden */
  78960. this._isMonitoring = false;
  78961. /**
  78962. * observable to be triggered when the gamepad controller has been disconnected
  78963. */
  78964. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  78965. if (!BABYLON.Tools.IsWindowObjectExist()) {
  78966. this._gamepadEventSupported = false;
  78967. }
  78968. else {
  78969. this._gamepadEventSupported = 'GamepadEvent' in window;
  78970. this._gamepadSupport = (navigator.getGamepads ||
  78971. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  78972. }
  78973. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  78974. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  78975. for (var i in _this._babylonGamepads) {
  78976. var gamepad = _this._babylonGamepads[i];
  78977. if (gamepad && gamepad._isConnected) {
  78978. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  78979. }
  78980. }
  78981. });
  78982. this._onGamepadConnectedEvent = function (evt) {
  78983. var gamepad = evt.gamepad;
  78984. if (gamepad.index in _this._babylonGamepads) {
  78985. if (_this._babylonGamepads[gamepad.index].isConnected) {
  78986. return;
  78987. }
  78988. }
  78989. var newGamepad;
  78990. if (_this._babylonGamepads[gamepad.index]) {
  78991. newGamepad = _this._babylonGamepads[gamepad.index];
  78992. newGamepad.browserGamepad = gamepad;
  78993. newGamepad._isConnected = true;
  78994. }
  78995. else {
  78996. newGamepad = _this._addNewGamepad(gamepad);
  78997. }
  78998. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  78999. _this._startMonitoringGamepads();
  79000. };
  79001. this._onGamepadDisconnectedEvent = function (evt) {
  79002. var gamepad = evt.gamepad;
  79003. // Remove the gamepad from the list of gamepads to monitor.
  79004. for (var i in _this._babylonGamepads) {
  79005. if (_this._babylonGamepads[i].index === gamepad.index) {
  79006. var disconnectedGamepad = _this._babylonGamepads[i];
  79007. disconnectedGamepad._isConnected = false;
  79008. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  79009. break;
  79010. }
  79011. }
  79012. };
  79013. if (this._gamepadSupport) {
  79014. //first add already-connected gamepads
  79015. this._updateGamepadObjects();
  79016. if (this._babylonGamepads.length) {
  79017. this._startMonitoringGamepads();
  79018. }
  79019. // Checking if the gamepad connected event is supported (like in Firefox)
  79020. if (this._gamepadEventSupported) {
  79021. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  79022. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  79023. }
  79024. else {
  79025. this._startMonitoringGamepads();
  79026. }
  79027. }
  79028. }
  79029. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  79030. /**
  79031. * The gamepads in the game pad manager
  79032. */
  79033. get: function () {
  79034. return this._babylonGamepads;
  79035. },
  79036. enumerable: true,
  79037. configurable: true
  79038. });
  79039. /**
  79040. * Get the gamepad controllers based on type
  79041. * @param type The type of gamepad controller
  79042. * @returns Nullable gamepad
  79043. */
  79044. GamepadManager.prototype.getGamepadByType = function (type) {
  79045. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  79046. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  79047. var gamepad = _a[_i];
  79048. if (gamepad && gamepad.type === type) {
  79049. return gamepad;
  79050. }
  79051. }
  79052. return null;
  79053. };
  79054. /**
  79055. * Disposes the gamepad manager
  79056. */
  79057. GamepadManager.prototype.dispose = function () {
  79058. if (this._gamepadEventSupported) {
  79059. if (this._onGamepadConnectedEvent) {
  79060. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  79061. }
  79062. if (this._onGamepadDisconnectedEvent) {
  79063. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  79064. }
  79065. this._onGamepadConnectedEvent = null;
  79066. this._onGamepadDisconnectedEvent = null;
  79067. }
  79068. this._babylonGamepads.forEach(function (gamepad) {
  79069. gamepad.dispose();
  79070. });
  79071. this.onGamepadConnectedObservable.clear();
  79072. this.onGamepadDisconnectedObservable.clear();
  79073. this._oneGamepadConnected = false;
  79074. this._stopMonitoringGamepads();
  79075. this._babylonGamepads = [];
  79076. };
  79077. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  79078. if (!this._oneGamepadConnected) {
  79079. this._oneGamepadConnected = true;
  79080. }
  79081. var newGamepad;
  79082. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  79083. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  79084. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  79085. }
  79086. // if pose is supported, use the (WebVR) pose enabled controller
  79087. else if (gamepad.pose) {
  79088. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  79089. }
  79090. else {
  79091. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  79092. }
  79093. this._babylonGamepads[newGamepad.index] = newGamepad;
  79094. return newGamepad;
  79095. };
  79096. GamepadManager.prototype._startMonitoringGamepads = function () {
  79097. if (!this._isMonitoring) {
  79098. this._isMonitoring = true;
  79099. //back-comp
  79100. if (!this._scene) {
  79101. this._checkGamepadsStatus();
  79102. }
  79103. }
  79104. };
  79105. GamepadManager.prototype._stopMonitoringGamepads = function () {
  79106. this._isMonitoring = false;
  79107. };
  79108. /** @hidden */
  79109. GamepadManager.prototype._checkGamepadsStatus = function () {
  79110. var _this = this;
  79111. // Hack to be compatible Chrome
  79112. this._updateGamepadObjects();
  79113. for (var i in this._babylonGamepads) {
  79114. var gamepad = this._babylonGamepads[i];
  79115. if (!gamepad || !gamepad.isConnected) {
  79116. continue;
  79117. }
  79118. gamepad.update();
  79119. }
  79120. if (this._isMonitoring && !this._scene) {
  79121. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  79122. }
  79123. };
  79124. // This function is called only on Chrome, which does not properly support
  79125. // connection/disconnection events and forces you to recopy again the gamepad object
  79126. GamepadManager.prototype._updateGamepadObjects = function () {
  79127. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  79128. for (var i = 0; i < gamepads.length; i++) {
  79129. var gamepad = gamepads[i];
  79130. if (gamepad) {
  79131. if (!this._babylonGamepads[gamepad.index]) {
  79132. var newGamepad = this._addNewGamepad(gamepad);
  79133. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  79134. }
  79135. else {
  79136. // Forced to copy again this object for Chrome for unknown reason
  79137. this._babylonGamepads[i].browserGamepad = gamepad;
  79138. if (!this._babylonGamepads[i].isConnected) {
  79139. this._babylonGamepads[i]._isConnected = true;
  79140. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  79141. }
  79142. }
  79143. }
  79144. }
  79145. };
  79146. return GamepadManager;
  79147. }());
  79148. BABYLON.GamepadManager = GamepadManager;
  79149. })(BABYLON || (BABYLON = {}));
  79150. //# sourceMappingURL=babylon.gamepadManager.js.map
  79151. var BABYLON;
  79152. (function (BABYLON) {
  79153. /**
  79154. * Represents a gamepad control stick position
  79155. */
  79156. var StickValues = /** @class */ (function () {
  79157. /**
  79158. * Initializes the gamepad x and y control stick values
  79159. * @param x The x component of the gamepad control stick value
  79160. * @param y The y component of the gamepad control stick value
  79161. */
  79162. function StickValues(
  79163. /**
  79164. * The x component of the control stick
  79165. */
  79166. x,
  79167. /**
  79168. * The y component of the control stick
  79169. */
  79170. y) {
  79171. this.x = x;
  79172. this.y = y;
  79173. }
  79174. return StickValues;
  79175. }());
  79176. BABYLON.StickValues = StickValues;
  79177. /**
  79178. * Represents a gamepad
  79179. */
  79180. var Gamepad = /** @class */ (function () {
  79181. /**
  79182. * Initializes the gamepad
  79183. * @param id The id of the gamepad
  79184. * @param index The index of the gamepad
  79185. * @param browserGamepad The browser gamepad
  79186. * @param leftStickX The x component of the left joystick
  79187. * @param leftStickY The y component of the left joystick
  79188. * @param rightStickX The x component of the right joystick
  79189. * @param rightStickY The y component of the right joystick
  79190. */
  79191. function Gamepad(
  79192. /**
  79193. * The id of the gamepad
  79194. */
  79195. id,
  79196. /**
  79197. * The index of the gamepad
  79198. */
  79199. index,
  79200. /**
  79201. * The browser gamepad
  79202. */
  79203. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  79204. if (leftStickX === void 0) { leftStickX = 0; }
  79205. if (leftStickY === void 0) { leftStickY = 1; }
  79206. if (rightStickX === void 0) { rightStickX = 2; }
  79207. if (rightStickY === void 0) { rightStickY = 3; }
  79208. this.id = id;
  79209. this.index = index;
  79210. this.browserGamepad = browserGamepad;
  79211. this._leftStick = { x: 0, y: 0 };
  79212. this._rightStick = { x: 0, y: 0 };
  79213. /** @hidden */
  79214. this._isConnected = true;
  79215. /**
  79216. * Specifies whether the left control stick should be Y-inverted
  79217. */
  79218. this._invertLeftStickY = false;
  79219. this.type = Gamepad.GAMEPAD;
  79220. this._leftStickAxisX = leftStickX;
  79221. this._leftStickAxisY = leftStickY;
  79222. this._rightStickAxisX = rightStickX;
  79223. this._rightStickAxisY = rightStickY;
  79224. if (this.browserGamepad.axes.length >= 2) {
  79225. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  79226. }
  79227. if (this.browserGamepad.axes.length >= 4) {
  79228. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  79229. }
  79230. }
  79231. Object.defineProperty(Gamepad.prototype, "isConnected", {
  79232. /**
  79233. * Specifies if the gamepad has been connected
  79234. */
  79235. get: function () {
  79236. return this._isConnected;
  79237. },
  79238. enumerable: true,
  79239. configurable: true
  79240. });
  79241. /**
  79242. * Callback triggered when the left joystick has changed
  79243. * @param callback
  79244. */
  79245. Gamepad.prototype.onleftstickchanged = function (callback) {
  79246. this._onleftstickchanged = callback;
  79247. };
  79248. /**
  79249. * Callback triggered when the right joystick has changed
  79250. * @param callback
  79251. */
  79252. Gamepad.prototype.onrightstickchanged = function (callback) {
  79253. this._onrightstickchanged = callback;
  79254. };
  79255. Object.defineProperty(Gamepad.prototype, "leftStick", {
  79256. /**
  79257. * Gets the left joystick
  79258. */
  79259. get: function () {
  79260. return this._leftStick;
  79261. },
  79262. /**
  79263. * Sets the left joystick values
  79264. */
  79265. set: function (newValues) {
  79266. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  79267. this._onleftstickchanged(newValues);
  79268. }
  79269. this._leftStick = newValues;
  79270. },
  79271. enumerable: true,
  79272. configurable: true
  79273. });
  79274. Object.defineProperty(Gamepad.prototype, "rightStick", {
  79275. /**
  79276. * Gets the right joystick
  79277. */
  79278. get: function () {
  79279. return this._rightStick;
  79280. },
  79281. /**
  79282. * Sets the right joystick value
  79283. */
  79284. set: function (newValues) {
  79285. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  79286. this._onrightstickchanged(newValues);
  79287. }
  79288. this._rightStick = newValues;
  79289. },
  79290. enumerable: true,
  79291. configurable: true
  79292. });
  79293. /**
  79294. * Updates the gamepad joystick positions
  79295. */
  79296. Gamepad.prototype.update = function () {
  79297. if (this._leftStick) {
  79298. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  79299. if (this._invertLeftStickY) {
  79300. this.leftStick.y *= -1;
  79301. }
  79302. }
  79303. if (this._rightStick) {
  79304. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  79305. }
  79306. };
  79307. /**
  79308. * Disposes the gamepad
  79309. */
  79310. Gamepad.prototype.dispose = function () {
  79311. };
  79312. /**
  79313. * Represents a gamepad controller
  79314. */
  79315. Gamepad.GAMEPAD = 0;
  79316. /**
  79317. * Represents a generic controller
  79318. */
  79319. Gamepad.GENERIC = 1;
  79320. /**
  79321. * Represents an XBox controller
  79322. */
  79323. Gamepad.XBOX = 2;
  79324. /**
  79325. * Represents a pose-enabled controller
  79326. */
  79327. Gamepad.POSE_ENABLED = 3;
  79328. return Gamepad;
  79329. }());
  79330. BABYLON.Gamepad = Gamepad;
  79331. /**
  79332. * Represents a generic gamepad
  79333. */
  79334. var GenericPad = /** @class */ (function (_super) {
  79335. __extends(GenericPad, _super);
  79336. /**
  79337. * Initializes the generic gamepad
  79338. * @param id The id of the generic gamepad
  79339. * @param index The index of the generic gamepad
  79340. * @param browserGamepad The browser gamepad
  79341. */
  79342. function GenericPad(id, index, browserGamepad) {
  79343. var _this = _super.call(this, id, index, browserGamepad) || this;
  79344. /**
  79345. * Observable triggered when a button has been pressed
  79346. */
  79347. _this.onButtonDownObservable = new BABYLON.Observable();
  79348. /**
  79349. * Observable triggered when a button has been released
  79350. */
  79351. _this.onButtonUpObservable = new BABYLON.Observable();
  79352. _this.type = Gamepad.GENERIC;
  79353. _this._buttons = new Array(browserGamepad.buttons.length);
  79354. return _this;
  79355. }
  79356. /**
  79357. * Callback triggered when a button has been pressed
  79358. * @param callback Called when a button has been pressed
  79359. */
  79360. GenericPad.prototype.onbuttondown = function (callback) {
  79361. this._onbuttondown = callback;
  79362. };
  79363. /**
  79364. * Callback triggered when a button has been released
  79365. * @param callback Called when a button has been released
  79366. */
  79367. GenericPad.prototype.onbuttonup = function (callback) {
  79368. this._onbuttonup = callback;
  79369. };
  79370. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  79371. if (newValue !== currentValue) {
  79372. if (newValue === 1) {
  79373. if (this._onbuttondown) {
  79374. this._onbuttondown(buttonIndex);
  79375. }
  79376. this.onButtonDownObservable.notifyObservers(buttonIndex);
  79377. }
  79378. if (newValue === 0) {
  79379. if (this._onbuttonup) {
  79380. this._onbuttonup(buttonIndex);
  79381. }
  79382. this.onButtonUpObservable.notifyObservers(buttonIndex);
  79383. }
  79384. }
  79385. return newValue;
  79386. };
  79387. /**
  79388. * Updates the generic gamepad
  79389. */
  79390. GenericPad.prototype.update = function () {
  79391. _super.prototype.update.call(this);
  79392. for (var index = 0; index < this._buttons.length; index++) {
  79393. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  79394. }
  79395. };
  79396. /**
  79397. * Disposes the generic gamepad
  79398. */
  79399. GenericPad.prototype.dispose = function () {
  79400. _super.prototype.dispose.call(this);
  79401. this.onButtonDownObservable.clear();
  79402. this.onButtonUpObservable.clear();
  79403. };
  79404. return GenericPad;
  79405. }(Gamepad));
  79406. BABYLON.GenericPad = GenericPad;
  79407. })(BABYLON || (BABYLON = {}));
  79408. //# sourceMappingURL=babylon.gamepad.js.map
  79409. var BABYLON;
  79410. (function (BABYLON) {
  79411. /**
  79412. * Defines supported buttons for XBox360 compatible gamepads
  79413. */
  79414. var Xbox360Button;
  79415. (function (Xbox360Button) {
  79416. /** A */
  79417. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  79418. /** B */
  79419. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  79420. /** X */
  79421. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  79422. /** Y */
  79423. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  79424. /** Start */
  79425. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  79426. /** Back */
  79427. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  79428. /** Left button */
  79429. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  79430. /** Right button */
  79431. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  79432. /** Left stick */
  79433. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  79434. /** Right stick */
  79435. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  79436. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  79437. /** Defines values for XBox360 DPad */
  79438. var Xbox360Dpad;
  79439. (function (Xbox360Dpad) {
  79440. /** Up */
  79441. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  79442. /** Down */
  79443. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  79444. /** Left */
  79445. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  79446. /** Right */
  79447. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  79448. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  79449. /**
  79450. * Defines a XBox360 gamepad
  79451. */
  79452. var Xbox360Pad = /** @class */ (function (_super) {
  79453. __extends(Xbox360Pad, _super);
  79454. /**
  79455. * Creates a new XBox360 gamepad object
  79456. * @param id defines the id of this gamepad
  79457. * @param index defines its index
  79458. * @param gamepad defines the internal HTML gamepad object
  79459. * @param xboxOne defines if it is a XBox One gamepad
  79460. */
  79461. function Xbox360Pad(id, index, gamepad, xboxOne) {
  79462. if (xboxOne === void 0) { xboxOne = false; }
  79463. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  79464. _this._leftTrigger = 0;
  79465. _this._rightTrigger = 0;
  79466. /** Observable raised when a button is pressed */
  79467. _this.onButtonDownObservable = new BABYLON.Observable();
  79468. /** Observable raised when a button is released */
  79469. _this.onButtonUpObservable = new BABYLON.Observable();
  79470. /** Observable raised when a pad is pressed */
  79471. _this.onPadDownObservable = new BABYLON.Observable();
  79472. /** Observable raised when a pad is released */
  79473. _this.onPadUpObservable = new BABYLON.Observable();
  79474. _this._buttonA = 0;
  79475. _this._buttonB = 0;
  79476. _this._buttonX = 0;
  79477. _this._buttonY = 0;
  79478. _this._buttonBack = 0;
  79479. _this._buttonStart = 0;
  79480. _this._buttonLB = 0;
  79481. _this._buttonRB = 0;
  79482. _this._buttonLeftStick = 0;
  79483. _this._buttonRightStick = 0;
  79484. _this._dPadUp = 0;
  79485. _this._dPadDown = 0;
  79486. _this._dPadLeft = 0;
  79487. _this._dPadRight = 0;
  79488. _this._isXboxOnePad = false;
  79489. _this.type = BABYLON.Gamepad.XBOX;
  79490. _this._isXboxOnePad = xboxOne;
  79491. return _this;
  79492. }
  79493. /**
  79494. * Defines the callback to call when left trigger is pressed
  79495. * @param callback defines the callback to use
  79496. */
  79497. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  79498. this._onlefttriggerchanged = callback;
  79499. };
  79500. /**
  79501. * Defines the callback to call when right trigger is pressed
  79502. * @param callback defines the callback to use
  79503. */
  79504. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  79505. this._onrighttriggerchanged = callback;
  79506. };
  79507. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  79508. /**
  79509. * Gets the left trigger value
  79510. */
  79511. get: function () {
  79512. return this._leftTrigger;
  79513. },
  79514. /**
  79515. * Sets the left trigger value
  79516. */
  79517. set: function (newValue) {
  79518. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  79519. this._onlefttriggerchanged(newValue);
  79520. }
  79521. this._leftTrigger = newValue;
  79522. },
  79523. enumerable: true,
  79524. configurable: true
  79525. });
  79526. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  79527. /**
  79528. * Gets the right trigger value
  79529. */
  79530. get: function () {
  79531. return this._rightTrigger;
  79532. },
  79533. /**
  79534. * Sets the right trigger value
  79535. */
  79536. set: function (newValue) {
  79537. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  79538. this._onrighttriggerchanged(newValue);
  79539. }
  79540. this._rightTrigger = newValue;
  79541. },
  79542. enumerable: true,
  79543. configurable: true
  79544. });
  79545. /**
  79546. * Defines the callback to call when a button is pressed
  79547. * @param callback defines the callback to use
  79548. */
  79549. Xbox360Pad.prototype.onbuttondown = function (callback) {
  79550. this._onbuttondown = callback;
  79551. };
  79552. /**
  79553. * Defines the callback to call when a button is released
  79554. * @param callback defines the callback to use
  79555. */
  79556. Xbox360Pad.prototype.onbuttonup = function (callback) {
  79557. this._onbuttonup = callback;
  79558. };
  79559. /**
  79560. * Defines the callback to call when a pad is pressed
  79561. * @param callback defines the callback to use
  79562. */
  79563. Xbox360Pad.prototype.ondpaddown = function (callback) {
  79564. this._ondpaddown = callback;
  79565. };
  79566. /**
  79567. * Defines the callback to call when a pad is released
  79568. * @param callback defines the callback to use
  79569. */
  79570. Xbox360Pad.prototype.ondpadup = function (callback) {
  79571. this._ondpadup = callback;
  79572. };
  79573. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  79574. if (newValue !== currentValue) {
  79575. if (newValue === 1) {
  79576. if (this._onbuttondown) {
  79577. this._onbuttondown(buttonType);
  79578. }
  79579. this.onButtonDownObservable.notifyObservers(buttonType);
  79580. }
  79581. if (newValue === 0) {
  79582. if (this._onbuttonup) {
  79583. this._onbuttonup(buttonType);
  79584. }
  79585. this.onButtonUpObservable.notifyObservers(buttonType);
  79586. }
  79587. }
  79588. return newValue;
  79589. };
  79590. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  79591. if (newValue !== currentValue) {
  79592. if (newValue === 1) {
  79593. if (this._ondpaddown) {
  79594. this._ondpaddown(buttonType);
  79595. }
  79596. this.onPadDownObservable.notifyObservers(buttonType);
  79597. }
  79598. if (newValue === 0) {
  79599. if (this._ondpadup) {
  79600. this._ondpadup(buttonType);
  79601. }
  79602. this.onPadUpObservable.notifyObservers(buttonType);
  79603. }
  79604. }
  79605. return newValue;
  79606. };
  79607. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  79608. /**
  79609. * Gets the value of the `A` button
  79610. */
  79611. get: function () {
  79612. return this._buttonA;
  79613. },
  79614. /**
  79615. * Sets the value of the `A` button
  79616. */
  79617. set: function (value) {
  79618. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  79619. },
  79620. enumerable: true,
  79621. configurable: true
  79622. });
  79623. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  79624. /**
  79625. * Gets the value of the `B` button
  79626. */
  79627. get: function () {
  79628. return this._buttonB;
  79629. },
  79630. /**
  79631. * Sets the value of the `B` button
  79632. */
  79633. set: function (value) {
  79634. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  79635. },
  79636. enumerable: true,
  79637. configurable: true
  79638. });
  79639. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  79640. /**
  79641. * Gets the value of the `X` button
  79642. */
  79643. get: function () {
  79644. return this._buttonX;
  79645. },
  79646. /**
  79647. * Sets the value of the `X` button
  79648. */
  79649. set: function (value) {
  79650. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  79651. },
  79652. enumerable: true,
  79653. configurable: true
  79654. });
  79655. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  79656. /**
  79657. * Gets the value of the `Y` button
  79658. */
  79659. get: function () {
  79660. return this._buttonY;
  79661. },
  79662. /**
  79663. * Sets the value of the `Y` button
  79664. */
  79665. set: function (value) {
  79666. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  79667. },
  79668. enumerable: true,
  79669. configurable: true
  79670. });
  79671. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  79672. /**
  79673. * Gets the value of the `Start` button
  79674. */
  79675. get: function () {
  79676. return this._buttonStart;
  79677. },
  79678. /**
  79679. * Sets the value of the `Start` button
  79680. */
  79681. set: function (value) {
  79682. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  79683. },
  79684. enumerable: true,
  79685. configurable: true
  79686. });
  79687. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  79688. /**
  79689. * Gets the value of the `Back` button
  79690. */
  79691. get: function () {
  79692. return this._buttonBack;
  79693. },
  79694. /**
  79695. * Sets the value of the `Back` button
  79696. */
  79697. set: function (value) {
  79698. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  79699. },
  79700. enumerable: true,
  79701. configurable: true
  79702. });
  79703. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  79704. /**
  79705. * Gets the value of the `Left` button
  79706. */
  79707. get: function () {
  79708. return this._buttonLB;
  79709. },
  79710. /**
  79711. * Sets the value of the `Left` button
  79712. */
  79713. set: function (value) {
  79714. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  79715. },
  79716. enumerable: true,
  79717. configurable: true
  79718. });
  79719. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  79720. /**
  79721. * Gets the value of the `Right` button
  79722. */
  79723. get: function () {
  79724. return this._buttonRB;
  79725. },
  79726. /**
  79727. * Sets the value of the `Right` button
  79728. */
  79729. set: function (value) {
  79730. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  79731. },
  79732. enumerable: true,
  79733. configurable: true
  79734. });
  79735. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  79736. /**
  79737. * Gets the value of the Left joystick
  79738. */
  79739. get: function () {
  79740. return this._buttonLeftStick;
  79741. },
  79742. /**
  79743. * Sets the value of the Left joystick
  79744. */
  79745. set: function (value) {
  79746. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  79747. },
  79748. enumerable: true,
  79749. configurable: true
  79750. });
  79751. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  79752. /**
  79753. * Gets the value of the Right joystick
  79754. */
  79755. get: function () {
  79756. return this._buttonRightStick;
  79757. },
  79758. /**
  79759. * Sets the value of the Right joystick
  79760. */
  79761. set: function (value) {
  79762. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  79763. },
  79764. enumerable: true,
  79765. configurable: true
  79766. });
  79767. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  79768. /**
  79769. * Gets the value of D-pad up
  79770. */
  79771. get: function () {
  79772. return this._dPadUp;
  79773. },
  79774. /**
  79775. * Sets the value of D-pad up
  79776. */
  79777. set: function (value) {
  79778. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  79779. },
  79780. enumerable: true,
  79781. configurable: true
  79782. });
  79783. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  79784. /**
  79785. * Gets the value of D-pad down
  79786. */
  79787. get: function () {
  79788. return this._dPadDown;
  79789. },
  79790. /**
  79791. * Sets the value of D-pad down
  79792. */
  79793. set: function (value) {
  79794. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  79795. },
  79796. enumerable: true,
  79797. configurable: true
  79798. });
  79799. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  79800. /**
  79801. * Gets the value of D-pad left
  79802. */
  79803. get: function () {
  79804. return this._dPadLeft;
  79805. },
  79806. /**
  79807. * Sets the value of D-pad left
  79808. */
  79809. set: function (value) {
  79810. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  79811. },
  79812. enumerable: true,
  79813. configurable: true
  79814. });
  79815. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  79816. /**
  79817. * Gets the value of D-pad right
  79818. */
  79819. get: function () {
  79820. return this._dPadRight;
  79821. },
  79822. /**
  79823. * Sets the value of D-pad right
  79824. */
  79825. set: function (value) {
  79826. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  79827. },
  79828. enumerable: true,
  79829. configurable: true
  79830. });
  79831. /**
  79832. * Force the gamepad to synchronize with device values
  79833. */
  79834. Xbox360Pad.prototype.update = function () {
  79835. _super.prototype.update.call(this);
  79836. if (this._isXboxOnePad) {
  79837. this.buttonA = this.browserGamepad.buttons[0].value;
  79838. this.buttonB = this.browserGamepad.buttons[1].value;
  79839. this.buttonX = this.browserGamepad.buttons[2].value;
  79840. this.buttonY = this.browserGamepad.buttons[3].value;
  79841. this.buttonLB = this.browserGamepad.buttons[4].value;
  79842. this.buttonRB = this.browserGamepad.buttons[5].value;
  79843. this.leftTrigger = this.browserGamepad.axes[2];
  79844. this.rightTrigger = this.browserGamepad.axes[5];
  79845. this.buttonBack = this.browserGamepad.buttons[9].value;
  79846. this.buttonStart = this.browserGamepad.buttons[8].value;
  79847. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  79848. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  79849. this.dPadUp = this.browserGamepad.buttons[11].value;
  79850. this.dPadDown = this.browserGamepad.buttons[12].value;
  79851. this.dPadLeft = this.browserGamepad.buttons[13].value;
  79852. this.dPadRight = this.browserGamepad.buttons[14].value;
  79853. }
  79854. else {
  79855. this.buttonA = this.browserGamepad.buttons[0].value;
  79856. this.buttonB = this.browserGamepad.buttons[1].value;
  79857. this.buttonX = this.browserGamepad.buttons[2].value;
  79858. this.buttonY = this.browserGamepad.buttons[3].value;
  79859. this.buttonLB = this.browserGamepad.buttons[4].value;
  79860. this.buttonRB = this.browserGamepad.buttons[5].value;
  79861. this.leftTrigger = this.browserGamepad.buttons[6].value;
  79862. this.rightTrigger = this.browserGamepad.buttons[7].value;
  79863. this.buttonBack = this.browserGamepad.buttons[8].value;
  79864. this.buttonStart = this.browserGamepad.buttons[9].value;
  79865. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  79866. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  79867. this.dPadUp = this.browserGamepad.buttons[12].value;
  79868. this.dPadDown = this.browserGamepad.buttons[13].value;
  79869. this.dPadLeft = this.browserGamepad.buttons[14].value;
  79870. this.dPadRight = this.browserGamepad.buttons[15].value;
  79871. }
  79872. };
  79873. /**
  79874. * Disposes the gamepad
  79875. */
  79876. Xbox360Pad.prototype.dispose = function () {
  79877. _super.prototype.dispose.call(this);
  79878. this.onButtonDownObservable.clear();
  79879. this.onButtonUpObservable.clear();
  79880. this.onPadDownObservable.clear();
  79881. this.onPadUpObservable.clear();
  79882. };
  79883. return Xbox360Pad;
  79884. }(BABYLON.Gamepad));
  79885. BABYLON.Xbox360Pad = Xbox360Pad;
  79886. })(BABYLON || (BABYLON = {}));
  79887. //# sourceMappingURL=babylon.xboxGamepad.js.map
  79888. var BABYLON;
  79889. (function (BABYLON) {
  79890. /**
  79891. * Defines the types of pose enabled controllers that are supported
  79892. */
  79893. var PoseEnabledControllerType;
  79894. (function (PoseEnabledControllerType) {
  79895. /**
  79896. * HTC Vive
  79897. */
  79898. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  79899. /**
  79900. * Oculus Rift
  79901. */
  79902. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  79903. /**
  79904. * Windows mixed reality
  79905. */
  79906. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  79907. /**
  79908. * Samsung gear VR
  79909. */
  79910. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  79911. /**
  79912. * Google Daydream
  79913. */
  79914. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  79915. /**
  79916. * Generic
  79917. */
  79918. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  79919. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  79920. /**
  79921. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  79922. */
  79923. var PoseEnabledControllerHelper = /** @class */ (function () {
  79924. function PoseEnabledControllerHelper() {
  79925. }
  79926. /**
  79927. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  79928. * @param vrGamepad the gamepad to initialized
  79929. * @returns a vr controller of the type the gamepad identified as
  79930. */
  79931. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  79932. // Oculus Touch
  79933. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  79934. return new BABYLON.OculusTouchController(vrGamepad);
  79935. }
  79936. // Windows Mixed Reality controllers
  79937. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  79938. return new BABYLON.WindowsMotionController(vrGamepad);
  79939. }
  79940. // HTC Vive
  79941. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  79942. return new BABYLON.ViveController(vrGamepad);
  79943. }
  79944. // Samsung/Oculus Gear VR or Oculus Go
  79945. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  79946. return new BABYLON.GearVRController(vrGamepad);
  79947. }
  79948. // Google Daydream
  79949. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  79950. return new BABYLON.DaydreamController(vrGamepad);
  79951. }
  79952. // Generic
  79953. else {
  79954. return new BABYLON.GenericController(vrGamepad);
  79955. }
  79956. };
  79957. return PoseEnabledControllerHelper;
  79958. }());
  79959. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  79960. /**
  79961. * Defines the PoseEnabledController object that contains state of a vr capable controller
  79962. */
  79963. var PoseEnabledController = /** @class */ (function (_super) {
  79964. __extends(PoseEnabledController, _super);
  79965. /**
  79966. * Creates a new PoseEnabledController from a gamepad
  79967. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  79968. */
  79969. function PoseEnabledController(browserGamepad) {
  79970. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  79971. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79972. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79973. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  79974. /**
  79975. * The device position in babylon space
  79976. */
  79977. _this.devicePosition = BABYLON.Vector3.Zero();
  79978. /**
  79979. * The device rotation in babylon space
  79980. */
  79981. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  79982. /**
  79983. * The scale factor of the device in babylon space
  79984. */
  79985. _this.deviceScaleFactor = 1;
  79986. // Used to convert 6dof controllers to 3dof
  79987. _this._trackPosition = true;
  79988. _this._maxRotationDistFromHeadset = Math.PI / 5;
  79989. _this._draggedRoomRotation = 0;
  79990. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  79991. /**
  79992. * Internal, matrix used to convert room space to babylon space
  79993. * @hidden
  79994. */
  79995. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79996. /**
  79997. * Node to be used when casting a ray from the controller
  79998. * @hidden
  79999. */
  80000. _this._pointingPoseNode = null;
  80001. _this._workingMatrix = BABYLON.Matrix.Identity();
  80002. /**
  80003. * @hidden
  80004. */
  80005. _this._meshAttachedObservable = new BABYLON.Observable();
  80006. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  80007. _this.controllerType = PoseEnabledControllerType.GENERIC;
  80008. _this.position = BABYLON.Vector3.Zero();
  80009. _this.rotationQuaternion = new BABYLON.Quaternion();
  80010. _this._calculatedPosition = BABYLON.Vector3.Zero();
  80011. _this._calculatedRotation = new BABYLON.Quaternion();
  80012. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  80013. return _this;
  80014. }
  80015. /**
  80016. * @hidden
  80017. */
  80018. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  80019. if (this._trackPosition) {
  80020. this._calculatedPosition.copyFrom(fixedPosition);
  80021. this._trackPosition = false;
  80022. }
  80023. };
  80024. /**
  80025. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  80026. */
  80027. PoseEnabledController.prototype.update = function () {
  80028. _super.prototype.update.call(this);
  80029. this._updatePoseAndMesh();
  80030. };
  80031. /**
  80032. * Updates only the pose device and mesh without doing any button event checking
  80033. */
  80034. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  80035. var pose = this.browserGamepad.pose;
  80036. this.updateFromDevice(pose);
  80037. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  80038. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  80039. camera._computeDevicePosition();
  80040. this._deviceToWorld.setTranslation(camera.devicePosition);
  80041. if (camera.deviceRotationQuaternion) {
  80042. var camera = camera;
  80043. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  80044. // Find the radian distance away that the headset is from the controllers rotation
  80045. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  80046. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  80047. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  80048. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  80049. this._draggedRoomRotation += rotationAmount;
  80050. // Rotate controller around headset
  80051. var sin = Math.sin(-rotationAmount);
  80052. var cos = Math.cos(-rotationAmount);
  80053. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  80054. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  80055. }
  80056. }
  80057. }
  80058. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  80059. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  80060. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80061. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  80062. if (this._mesh) {
  80063. this._mesh.position.copyFrom(this.devicePosition);
  80064. if (this._mesh.rotationQuaternion) {
  80065. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  80066. }
  80067. }
  80068. };
  80069. /**
  80070. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  80071. * @param poseData raw pose fromthe device
  80072. */
  80073. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  80074. if (poseData) {
  80075. this.rawPose = poseData;
  80076. if (poseData.position) {
  80077. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  80078. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  80079. this._deviceRoomPosition.z *= -1;
  80080. }
  80081. if (this._trackPosition) {
  80082. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  80083. }
  80084. this._calculatedPosition.addInPlace(this.position);
  80085. }
  80086. var pose = this.rawPose;
  80087. if (poseData.orientation && pose.orientation) {
  80088. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  80089. if (this._mesh) {
  80090. if (this._mesh.getScene().useRightHandedSystem) {
  80091. this._deviceRoomRotationQuaternion.z *= -1;
  80092. this._deviceRoomRotationQuaternion.w *= -1;
  80093. }
  80094. else {
  80095. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  80096. }
  80097. }
  80098. // if the camera is set, rotate to the camera's rotation
  80099. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  80100. }
  80101. }
  80102. };
  80103. /**
  80104. * Attaches a mesh to the controller
  80105. * @param mesh the mesh to be attached
  80106. */
  80107. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  80108. if (this._mesh) {
  80109. this._mesh.parent = null;
  80110. }
  80111. this._mesh = mesh;
  80112. if (this._poseControlledCamera) {
  80113. this._mesh.parent = this._poseControlledCamera;
  80114. }
  80115. if (!this._mesh.rotationQuaternion) {
  80116. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  80117. }
  80118. // 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
  80119. this._updatePoseAndMesh();
  80120. if (this._pointingPoseNode) {
  80121. var parents = [];
  80122. var obj = this._pointingPoseNode;
  80123. while (obj.parent) {
  80124. parents.push(obj.parent);
  80125. obj = obj.parent;
  80126. }
  80127. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  80128. }
  80129. this._meshAttachedObservable.notifyObservers(mesh);
  80130. };
  80131. /**
  80132. * Attaches the controllers mesh to a camera
  80133. * @param camera the camera the mesh should be attached to
  80134. */
  80135. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  80136. this._poseControlledCamera = camera;
  80137. if (this._mesh) {
  80138. this._mesh.parent = this._poseControlledCamera;
  80139. }
  80140. };
  80141. /**
  80142. * Disposes of the controller
  80143. */
  80144. PoseEnabledController.prototype.dispose = function () {
  80145. if (this._mesh) {
  80146. this._mesh.dispose();
  80147. }
  80148. this._mesh = null;
  80149. _super.prototype.dispose.call(this);
  80150. };
  80151. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  80152. /**
  80153. * The mesh that is attached to the controller
  80154. */
  80155. get: function () {
  80156. return this._mesh;
  80157. },
  80158. enumerable: true,
  80159. configurable: true
  80160. });
  80161. /**
  80162. * Gets the ray of the controller in the direction the controller is pointing
  80163. * @param length the length the resulting ray should be
  80164. * @returns a ray in the direction the controller is pointing
  80165. */
  80166. PoseEnabledController.prototype.getForwardRay = function (length) {
  80167. if (length === void 0) { length = 100; }
  80168. if (!this.mesh) {
  80169. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  80170. }
  80171. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  80172. var origin = m.getTranslation();
  80173. var forward = new BABYLON.Vector3(0, 0, -1);
  80174. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  80175. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  80176. return new BABYLON.Ray(origin, direction, length);
  80177. };
  80178. /**
  80179. * Name of the child mesh that can be used to cast a ray from the controller
  80180. */
  80181. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  80182. return PoseEnabledController;
  80183. }(BABYLON.Gamepad));
  80184. BABYLON.PoseEnabledController = PoseEnabledController;
  80185. })(BABYLON || (BABYLON = {}));
  80186. //# sourceMappingURL=babylon.poseEnabledController.js.map
  80187. var BABYLON;
  80188. (function (BABYLON) {
  80189. /**
  80190. * Defines the WebVRController object that represents controllers tracked in 3D space
  80191. */
  80192. var WebVRController = /** @class */ (function (_super) {
  80193. __extends(WebVRController, _super);
  80194. /**
  80195. * Creates a new WebVRController from a gamepad
  80196. * @param vrGamepad the gamepad that the WebVRController should be created from
  80197. */
  80198. function WebVRController(vrGamepad) {
  80199. var _this = _super.call(this, vrGamepad) || this;
  80200. // Observables
  80201. /**
  80202. * Fired when the trigger state has changed
  80203. */
  80204. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  80205. /**
  80206. * Fired when the main button state has changed
  80207. */
  80208. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  80209. /**
  80210. * Fired when the secondary button state has changed
  80211. */
  80212. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  80213. /**
  80214. * Fired when the pad state has changed
  80215. */
  80216. _this.onPadStateChangedObservable = new BABYLON.Observable();
  80217. /**
  80218. * Fired when controllers stick values have changed
  80219. */
  80220. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  80221. /**
  80222. * X and Y axis corrisponding to the controllers joystick
  80223. */
  80224. _this.pad = { x: 0, y: 0 };
  80225. // avoid GC, store state in a tmp object
  80226. _this._changes = {
  80227. pressChanged: false,
  80228. touchChanged: false,
  80229. valueChanged: false,
  80230. changed: false
  80231. };
  80232. _this._buttons = new Array(vrGamepad.buttons.length);
  80233. _this.hand = vrGamepad.hand;
  80234. return _this;
  80235. }
  80236. /**
  80237. * Fired when a controller button's state has changed
  80238. * @param callback the callback containing the button that was modified
  80239. */
  80240. WebVRController.prototype.onButtonStateChange = function (callback) {
  80241. this._onButtonStateChange = callback;
  80242. };
  80243. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  80244. /**
  80245. * The default controller model for the controller
  80246. */
  80247. get: function () {
  80248. return this._defaultModel;
  80249. },
  80250. enumerable: true,
  80251. configurable: true
  80252. });
  80253. /**
  80254. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  80255. */
  80256. WebVRController.prototype.update = function () {
  80257. _super.prototype.update.call(this);
  80258. for (var index = 0; index < this._buttons.length; index++) {
  80259. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  80260. }
  80261. ;
  80262. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  80263. this.pad.x = this.leftStick.x;
  80264. this.pad.y = this.leftStick.y;
  80265. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  80266. }
  80267. };
  80268. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  80269. if (!newState) {
  80270. newState = {
  80271. pressed: false,
  80272. touched: false,
  80273. value: 0
  80274. };
  80275. }
  80276. if (!currentState) {
  80277. this._buttons[buttonIndex] = {
  80278. pressed: newState.pressed,
  80279. touched: newState.touched,
  80280. value: newState.value
  80281. };
  80282. return;
  80283. }
  80284. this._checkChanges(newState, currentState);
  80285. if (this._changes.changed) {
  80286. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  80287. this._handleButtonChange(buttonIndex, newState, this._changes);
  80288. }
  80289. this._buttons[buttonIndex].pressed = newState.pressed;
  80290. this._buttons[buttonIndex].touched = newState.touched;
  80291. // oculus triggers are never 0, thou not touched.
  80292. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  80293. };
  80294. WebVRController.prototype._checkChanges = function (newState, currentState) {
  80295. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  80296. this._changes.touchChanged = newState.touched !== currentState.touched;
  80297. this._changes.valueChanged = newState.value !== currentState.value;
  80298. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  80299. return this._changes;
  80300. };
  80301. /**
  80302. * Disposes of th webVRCOntroller
  80303. */
  80304. WebVRController.prototype.dispose = function () {
  80305. _super.prototype.dispose.call(this);
  80306. this.onTriggerStateChangedObservable.clear();
  80307. this.onMainButtonStateChangedObservable.clear();
  80308. this.onSecondaryButtonStateChangedObservable.clear();
  80309. this.onPadStateChangedObservable.clear();
  80310. this.onPadValuesChangedObservable.clear();
  80311. };
  80312. return WebVRController;
  80313. }(BABYLON.PoseEnabledController));
  80314. BABYLON.WebVRController = WebVRController;
  80315. })(BABYLON || (BABYLON = {}));
  80316. //# sourceMappingURL=babylon.webVRController.js.map
  80317. var BABYLON;
  80318. (function (BABYLON) {
  80319. /**
  80320. * Oculus Touch Controller
  80321. */
  80322. var OculusTouchController = /** @class */ (function (_super) {
  80323. __extends(OculusTouchController, _super);
  80324. /**
  80325. * Creates a new OculusTouchController from a gamepad
  80326. * @param vrGamepad the gamepad that the controller should be created from
  80327. */
  80328. function OculusTouchController(vrGamepad) {
  80329. var _this = _super.call(this, vrGamepad) || this;
  80330. /**
  80331. * Fired when the secondary trigger on this controller is modified
  80332. */
  80333. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  80334. /**
  80335. * Fired when the thumb rest on this controller is modified
  80336. */
  80337. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  80338. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  80339. return _this;
  80340. }
  80341. /**
  80342. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80343. * @param scene scene in which to add meshes
  80344. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80345. */
  80346. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80347. var _this = this;
  80348. var meshName;
  80349. // Hand
  80350. if (this.hand === 'left') {
  80351. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  80352. }
  80353. else { // Right is the default if no hand is specified
  80354. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  80355. }
  80356. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  80357. /*
  80358. Parent Mesh name: oculus_touch_left
  80359. - body
  80360. - trigger
  80361. - thumbstick
  80362. - grip
  80363. - button_y
  80364. - button_x
  80365. - button_enter
  80366. */
  80367. _this._defaultModel = newMeshes[1];
  80368. _this.attachToMesh(_this._defaultModel);
  80369. if (meshLoaded) {
  80370. meshLoaded(_this._defaultModel);
  80371. }
  80372. });
  80373. };
  80374. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  80375. /**
  80376. * Fired when the A button on this controller is modified
  80377. */
  80378. get: function () {
  80379. if (this.hand === 'right') {
  80380. return this.onMainButtonStateChangedObservable;
  80381. }
  80382. else {
  80383. throw new Error('No A button on left hand');
  80384. }
  80385. },
  80386. enumerable: true,
  80387. configurable: true
  80388. });
  80389. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  80390. /**
  80391. * Fired when the B button on this controller is modified
  80392. */
  80393. get: function () {
  80394. if (this.hand === 'right') {
  80395. return this.onSecondaryButtonStateChangedObservable;
  80396. }
  80397. else {
  80398. throw new Error('No B button on left hand');
  80399. }
  80400. },
  80401. enumerable: true,
  80402. configurable: true
  80403. });
  80404. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  80405. /**
  80406. * Fired when the X button on this controller is modified
  80407. */
  80408. get: function () {
  80409. if (this.hand === 'left') {
  80410. return this.onMainButtonStateChangedObservable;
  80411. }
  80412. else {
  80413. throw new Error('No X button on right hand');
  80414. }
  80415. },
  80416. enumerable: true,
  80417. configurable: true
  80418. });
  80419. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  80420. /**
  80421. * Fired when the Y button on this controller is modified
  80422. */
  80423. get: function () {
  80424. if (this.hand === 'left') {
  80425. return this.onSecondaryButtonStateChangedObservable;
  80426. }
  80427. else {
  80428. throw new Error('No Y button on right hand');
  80429. }
  80430. },
  80431. enumerable: true,
  80432. configurable: true
  80433. });
  80434. /**
  80435. * Called once for each button that changed state since the last frame
  80436. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  80437. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  80438. * 2) secondary trigger (same)
  80439. * 3) A (right) X (left), touch, pressed = value
  80440. * 4) B / Y
  80441. * 5) thumb rest
  80442. * @param buttonIdx Which button index changed
  80443. * @param state New state of the button
  80444. * @param changes Which properties on the state changed since last frame
  80445. */
  80446. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80447. var notifyObject = state; //{ state: state, changes: changes };
  80448. var triggerDirection = this.hand === 'right' ? -1 : 1;
  80449. switch (buttonIdx) {
  80450. case 0:
  80451. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  80452. return;
  80453. case 1: // index trigger
  80454. if (this._defaultModel) {
  80455. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  80456. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  80457. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  80458. }
  80459. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  80460. return;
  80461. case 2: // secondary trigger
  80462. if (this._defaultModel) {
  80463. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  80464. }
  80465. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  80466. return;
  80467. case 3:
  80468. if (this._defaultModel) {
  80469. if (notifyObject.pressed) {
  80470. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  80471. }
  80472. else {
  80473. (this._defaultModel.getChildren()[1]).position.y = 0;
  80474. }
  80475. }
  80476. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  80477. return;
  80478. case 4:
  80479. if (this._defaultModel) {
  80480. if (notifyObject.pressed) {
  80481. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  80482. }
  80483. else {
  80484. (this._defaultModel.getChildren()[2]).position.y = 0;
  80485. }
  80486. }
  80487. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  80488. return;
  80489. case 5:
  80490. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  80491. return;
  80492. }
  80493. };
  80494. /**
  80495. * Base Url for the controller model.
  80496. */
  80497. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  80498. /**
  80499. * File name for the left controller model.
  80500. */
  80501. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  80502. /**
  80503. * File name for the right controller model.
  80504. */
  80505. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  80506. return OculusTouchController;
  80507. }(BABYLON.WebVRController));
  80508. BABYLON.OculusTouchController = OculusTouchController;
  80509. })(BABYLON || (BABYLON = {}));
  80510. //# sourceMappingURL=babylon.oculusTouchController.js.map
  80511. var BABYLON;
  80512. (function (BABYLON) {
  80513. /**
  80514. * Vive Controller
  80515. */
  80516. var ViveController = /** @class */ (function (_super) {
  80517. __extends(ViveController, _super);
  80518. /**
  80519. * Creates a new ViveController from a gamepad
  80520. * @param vrGamepad the gamepad that the controller should be created from
  80521. */
  80522. function ViveController(vrGamepad) {
  80523. var _this = _super.call(this, vrGamepad) || this;
  80524. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  80525. _this._invertLeftStickY = true;
  80526. return _this;
  80527. }
  80528. /**
  80529. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80530. * @param scene scene in which to add meshes
  80531. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80532. */
  80533. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80534. var _this = this;
  80535. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  80536. /*
  80537. Parent Mesh name: ViveWand
  80538. - body
  80539. - r_gripper
  80540. - l_gripper
  80541. - menu_button
  80542. - system_button
  80543. - trackpad
  80544. - trigger
  80545. - LED
  80546. */
  80547. _this._defaultModel = newMeshes[1];
  80548. _this.attachToMesh(_this._defaultModel);
  80549. if (meshLoaded) {
  80550. meshLoaded(_this._defaultModel);
  80551. }
  80552. });
  80553. };
  80554. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  80555. /**
  80556. * Fired when the left button on this controller is modified
  80557. */
  80558. get: function () {
  80559. return this.onMainButtonStateChangedObservable;
  80560. },
  80561. enumerable: true,
  80562. configurable: true
  80563. });
  80564. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  80565. /**
  80566. * Fired when the right button on this controller is modified
  80567. */
  80568. get: function () {
  80569. return this.onMainButtonStateChangedObservable;
  80570. },
  80571. enumerable: true,
  80572. configurable: true
  80573. });
  80574. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  80575. /**
  80576. * Fired when the menu button on this controller is modified
  80577. */
  80578. get: function () {
  80579. return this.onSecondaryButtonStateChangedObservable;
  80580. },
  80581. enumerable: true,
  80582. configurable: true
  80583. });
  80584. /**
  80585. * Called once for each button that changed state since the last frame
  80586. * Vive mapping:
  80587. * 0: touchpad
  80588. * 1: trigger
  80589. * 2: left AND right buttons
  80590. * 3: menu button
  80591. * @param buttonIdx Which button index changed
  80592. * @param state New state of the button
  80593. * @param changes Which properties on the state changed since last frame
  80594. */
  80595. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80596. var notifyObject = state; //{ state: state, changes: changes };
  80597. switch (buttonIdx) {
  80598. case 0:
  80599. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  80600. return;
  80601. case 1: // index trigger
  80602. if (this._defaultModel) {
  80603. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  80604. }
  80605. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  80606. return;
  80607. case 2: // left AND right button
  80608. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  80609. return;
  80610. case 3:
  80611. if (this._defaultModel) {
  80612. if (notifyObject.pressed) {
  80613. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  80614. }
  80615. else {
  80616. (this._defaultModel.getChildren()[2]).position.y = 0;
  80617. }
  80618. }
  80619. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  80620. return;
  80621. }
  80622. };
  80623. /**
  80624. * Base Url for the controller model.
  80625. */
  80626. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  80627. /**
  80628. * File name for the controller model.
  80629. */
  80630. ViveController.MODEL_FILENAME = 'wand.babylon';
  80631. return ViveController;
  80632. }(BABYLON.WebVRController));
  80633. BABYLON.ViveController = ViveController;
  80634. })(BABYLON || (BABYLON = {}));
  80635. //# sourceMappingURL=babylon.viveController.js.map
  80636. var BABYLON;
  80637. (function (BABYLON) {
  80638. /**
  80639. * Generic Controller
  80640. */
  80641. var GenericController = /** @class */ (function (_super) {
  80642. __extends(GenericController, _super);
  80643. /**
  80644. * Creates a new GenericController from a gamepad
  80645. * @param vrGamepad the gamepad that the controller should be created from
  80646. */
  80647. function GenericController(vrGamepad) {
  80648. return _super.call(this, vrGamepad) || this;
  80649. }
  80650. /**
  80651. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80652. * @param scene scene in which to add meshes
  80653. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80654. */
  80655. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80656. var _this = this;
  80657. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  80658. _this._defaultModel = newMeshes[1];
  80659. _this.attachToMesh(_this._defaultModel);
  80660. if (meshLoaded) {
  80661. meshLoaded(_this._defaultModel);
  80662. }
  80663. });
  80664. };
  80665. /**
  80666. * Called once for each button that changed state since the last frame
  80667. * @param buttonIdx Which button index changed
  80668. * @param state New state of the button
  80669. * @param changes Which properties on the state changed since last frame
  80670. */
  80671. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80672. console.log("Button id: " + buttonIdx + "state: ");
  80673. console.dir(state);
  80674. };
  80675. /**
  80676. * Base Url for the controller model.
  80677. */
  80678. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  80679. /**
  80680. * File name for the controller model.
  80681. */
  80682. GenericController.MODEL_FILENAME = 'generic.babylon';
  80683. return GenericController;
  80684. }(BABYLON.WebVRController));
  80685. BABYLON.GenericController = GenericController;
  80686. })(BABYLON || (BABYLON = {}));
  80687. //# sourceMappingURL=babylon.genericController.js.map
  80688. var BABYLON;
  80689. (function (BABYLON) {
  80690. /**
  80691. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  80692. */
  80693. var LoadedMeshInfo = /** @class */ (function () {
  80694. function LoadedMeshInfo() {
  80695. /**
  80696. * Map of the button meshes contained in the controller
  80697. */
  80698. this.buttonMeshes = {};
  80699. /**
  80700. * Map of the axis meshes contained in the controller
  80701. */
  80702. this.axisMeshes = {};
  80703. }
  80704. return LoadedMeshInfo;
  80705. }());
  80706. /**
  80707. * Defines the WindowsMotionController object that the state of the windows motion controller
  80708. */
  80709. var WindowsMotionController = /** @class */ (function (_super) {
  80710. __extends(WindowsMotionController, _super);
  80711. /**
  80712. * Creates a new WindowsMotionController from a gamepad
  80713. * @param vrGamepad the gamepad that the controller should be created from
  80714. */
  80715. function WindowsMotionController(vrGamepad) {
  80716. var _this = _super.call(this, vrGamepad) || this;
  80717. _this._mapping = {
  80718. // Semantic button names
  80719. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  80720. // A mapping of the button name to glTF model node name
  80721. // that should be transformed by button value.
  80722. buttonMeshNames: {
  80723. 'trigger': 'SELECT',
  80724. 'menu': 'MENU',
  80725. 'grip': 'GRASP',
  80726. 'thumbstick': 'THUMBSTICK_PRESS',
  80727. 'trackpad': 'TOUCHPAD_PRESS'
  80728. },
  80729. // This mapping is used to translate from the Motion Controller to Babylon semantics
  80730. buttonObservableNames: {
  80731. 'trigger': 'onTriggerStateChangedObservable',
  80732. 'menu': 'onSecondaryButtonStateChangedObservable',
  80733. 'grip': 'onMainButtonStateChangedObservable',
  80734. 'thumbstick': 'onPadStateChangedObservable',
  80735. 'trackpad': 'onTrackpadChangedObservable'
  80736. },
  80737. // A mapping of the axis name to glTF model node name
  80738. // that should be transformed by axis value.
  80739. // This array mirrors the browserGamepad.axes array, such that
  80740. // the mesh corresponding to axis 0 is in this array index 0.
  80741. axisMeshNames: [
  80742. 'THUMBSTICK_X',
  80743. 'THUMBSTICK_Y',
  80744. 'TOUCHPAD_TOUCH_X',
  80745. 'TOUCHPAD_TOUCH_Y'
  80746. ],
  80747. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  80748. };
  80749. /**
  80750. * Fired when the trackpad on this controller is clicked
  80751. */
  80752. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  80753. /**
  80754. * Fired when the trackpad on this controller is modified
  80755. */
  80756. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  80757. /**
  80758. * The current x and y values of this controller's trackpad
  80759. */
  80760. _this.trackpad = { x: 0, y: 0 };
  80761. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  80762. _this._loadedMeshInfo = null;
  80763. return _this;
  80764. }
  80765. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  80766. /**
  80767. * Fired when the trigger on this controller is modified
  80768. */
  80769. get: function () {
  80770. return this.onTriggerStateChangedObservable;
  80771. },
  80772. enumerable: true,
  80773. configurable: true
  80774. });
  80775. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  80776. /**
  80777. * Fired when the menu button on this controller is modified
  80778. */
  80779. get: function () {
  80780. return this.onSecondaryButtonStateChangedObservable;
  80781. },
  80782. enumerable: true,
  80783. configurable: true
  80784. });
  80785. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  80786. /**
  80787. * Fired when the grip button on this controller is modified
  80788. */
  80789. get: function () {
  80790. return this.onMainButtonStateChangedObservable;
  80791. },
  80792. enumerable: true,
  80793. configurable: true
  80794. });
  80795. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  80796. /**
  80797. * Fired when the thumbstick button on this controller is modified
  80798. */
  80799. get: function () {
  80800. return this.onPadStateChangedObservable;
  80801. },
  80802. enumerable: true,
  80803. configurable: true
  80804. });
  80805. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  80806. /**
  80807. * Fired when the touchpad button on this controller is modified
  80808. */
  80809. get: function () {
  80810. return this.onTrackpadChangedObservable;
  80811. },
  80812. enumerable: true,
  80813. configurable: true
  80814. });
  80815. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  80816. /**
  80817. * Fired when the touchpad values on this controller are modified
  80818. */
  80819. get: function () {
  80820. return this.onTrackpadValuesChangedObservable;
  80821. },
  80822. enumerable: true,
  80823. configurable: true
  80824. });
  80825. WindowsMotionController.prototype._updateTrackpad = function () {
  80826. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  80827. this.trackpad.x = this.browserGamepad["axes"][2];
  80828. this.trackpad.y = this.browserGamepad["axes"][3];
  80829. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  80830. }
  80831. };
  80832. /**
  80833. * Called once per frame by the engine.
  80834. */
  80835. WindowsMotionController.prototype.update = function () {
  80836. _super.prototype.update.call(this);
  80837. if (this.browserGamepad.axes) {
  80838. this._updateTrackpad();
  80839. // Only need to animate axes if there is a loaded mesh
  80840. if (this._loadedMeshInfo) {
  80841. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  80842. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  80843. }
  80844. }
  80845. }
  80846. };
  80847. /**
  80848. * Called once for each button that changed state since the last frame
  80849. * @param buttonIdx Which button index changed
  80850. * @param state New state of the button
  80851. * @param changes Which properties on the state changed since last frame
  80852. */
  80853. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80854. var buttonName = this._mapping.buttons[buttonIdx];
  80855. if (!buttonName) {
  80856. return;
  80857. }
  80858. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  80859. this._updateTrackpad();
  80860. // Only emit events for buttons that we know how to map from index to name
  80861. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  80862. if (observable) {
  80863. observable.notifyObservers(state);
  80864. }
  80865. this._lerpButtonTransform(buttonName, state.value);
  80866. };
  80867. /**
  80868. * Moves the buttons on the controller mesh based on their current state
  80869. * @param buttonName the name of the button to move
  80870. * @param buttonValue the value of the button which determines the buttons new position
  80871. */
  80872. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  80873. // If there is no loaded mesh, there is nothing to transform.
  80874. if (!this._loadedMeshInfo) {
  80875. return;
  80876. }
  80877. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  80878. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  80879. return;
  80880. }
  80881. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  80882. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  80883. };
  80884. /**
  80885. * Moves the axis on the controller mesh based on its current state
  80886. * @param axis the index of the axis
  80887. * @param axisValue the value of the axis which determines the meshes new position
  80888. * @hidden
  80889. */
  80890. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  80891. if (!this._loadedMeshInfo) {
  80892. return;
  80893. }
  80894. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  80895. if (!meshInfo) {
  80896. return;
  80897. }
  80898. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  80899. return;
  80900. }
  80901. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  80902. var lerpValue = axisValue * 0.5 + 0.5;
  80903. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  80904. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  80905. };
  80906. /**
  80907. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80908. * @param scene scene in which to add meshes
  80909. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80910. */
  80911. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  80912. var _this = this;
  80913. if (forceDefault === void 0) { forceDefault = false; }
  80914. var path;
  80915. var filename;
  80916. // Checking if GLB loader is present
  80917. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  80918. // Determine the device specific folder based on the ID suffix
  80919. var device = 'default';
  80920. if (this.id && !forceDefault) {
  80921. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  80922. device = ((match && match[0]) || device);
  80923. }
  80924. // Hand
  80925. if (this.hand === 'left') {
  80926. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  80927. }
  80928. else { // Right is the default if no hand is specified
  80929. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  80930. }
  80931. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  80932. }
  80933. else {
  80934. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  80935. path = BABYLON.GenericController.MODEL_BASE_URL;
  80936. filename = BABYLON.GenericController.MODEL_FILENAME;
  80937. }
  80938. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  80939. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  80940. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  80941. if (!_this._loadedMeshInfo) {
  80942. return;
  80943. }
  80944. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  80945. _this.attachToMesh(_this._defaultModel);
  80946. if (meshLoaded) {
  80947. meshLoaded(_this._defaultModel);
  80948. }
  80949. }, null, function (scene, message) {
  80950. BABYLON.Tools.Log(message);
  80951. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  80952. if (!forceDefault) {
  80953. _this.initControllerMesh(scene, meshLoaded, true);
  80954. }
  80955. });
  80956. };
  80957. /**
  80958. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  80959. * can be transformed by button presses and axes values, based on this._mapping.
  80960. *
  80961. * @param scene scene in which the meshes exist
  80962. * @param meshes list of meshes that make up the controller model to process
  80963. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  80964. */
  80965. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  80966. var loadedMeshInfo = null;
  80967. // Create a new mesh to contain the glTF hierarchy
  80968. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  80969. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  80970. var childMesh = null;
  80971. for (var i = 0; i < meshes.length; i++) {
  80972. var mesh = meshes[i];
  80973. if (!mesh.parent) {
  80974. // Exclude controller meshes from picking results
  80975. mesh.isPickable = false;
  80976. // Handle root node, attach to the new parentMesh
  80977. childMesh = mesh;
  80978. break;
  80979. }
  80980. }
  80981. if (childMesh) {
  80982. childMesh.setParent(parentMesh);
  80983. // Create our mesh info. Note that this method will always return non-null.
  80984. loadedMeshInfo = this.createMeshInfo(parentMesh);
  80985. }
  80986. else {
  80987. BABYLON.Tools.Warn('Could not find root node in model file.');
  80988. }
  80989. return loadedMeshInfo;
  80990. };
  80991. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  80992. var loadedMeshInfo = new LoadedMeshInfo();
  80993. var i;
  80994. loadedMeshInfo.rootNode = rootNode;
  80995. // Reset the caches
  80996. loadedMeshInfo.buttonMeshes = {};
  80997. loadedMeshInfo.axisMeshes = {};
  80998. // Button Meshes
  80999. for (i = 0; i < this._mapping.buttons.length; i++) {
  81000. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  81001. if (!buttonMeshName) {
  81002. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  81003. continue;
  81004. }
  81005. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  81006. if (!buttonMesh) {
  81007. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  81008. continue;
  81009. }
  81010. var buttonMeshInfo = {
  81011. index: i,
  81012. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  81013. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  81014. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  81015. };
  81016. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  81017. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  81018. }
  81019. else {
  81020. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  81021. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  81022. '(VALUE: ' + !!buttonMeshInfo.value +
  81023. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  81024. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  81025. ')');
  81026. }
  81027. }
  81028. // Axis Meshes
  81029. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  81030. var axisMeshName = this._mapping.axisMeshNames[i];
  81031. if (!axisMeshName) {
  81032. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  81033. continue;
  81034. }
  81035. var axisMesh = getChildByName(rootNode, axisMeshName);
  81036. if (!axisMesh) {
  81037. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  81038. continue;
  81039. }
  81040. var axisMeshInfo = {
  81041. index: i,
  81042. value: getImmediateChildByName(axisMesh, 'VALUE'),
  81043. min: getImmediateChildByName(axisMesh, 'MIN'),
  81044. max: getImmediateChildByName(axisMesh, 'MAX')
  81045. };
  81046. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  81047. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  81048. }
  81049. else {
  81050. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  81051. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  81052. '(VALUE: ' + !!axisMeshInfo.value +
  81053. ', MIN: ' + !!axisMeshInfo.min +
  81054. ', MAX:' + !!axisMeshInfo.max +
  81055. ')');
  81056. }
  81057. }
  81058. // Pointing Ray
  81059. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  81060. if (!loadedMeshInfo.pointingPoseNode) {
  81061. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  81062. }
  81063. else {
  81064. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  81065. }
  81066. return loadedMeshInfo;
  81067. // Look through all children recursively. This will return null if no mesh exists with the given name.
  81068. function getChildByName(node, name) {
  81069. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  81070. }
  81071. // Look through only immediate children. This will return null if no mesh exists with the given name.
  81072. function getImmediateChildByName(node, name) {
  81073. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  81074. }
  81075. };
  81076. /**
  81077. * Gets the ray of the controller in the direction the controller is pointing
  81078. * @param length the length the resulting ray should be
  81079. * @returns a ray in the direction the controller is pointing
  81080. */
  81081. WindowsMotionController.prototype.getForwardRay = function (length) {
  81082. if (length === void 0) { length = 100; }
  81083. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  81084. return _super.prototype.getForwardRay.call(this, length);
  81085. }
  81086. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  81087. var origin = m.getTranslation();
  81088. var forward = new BABYLON.Vector3(0, 0, -1);
  81089. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  81090. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  81091. return new BABYLON.Ray(origin, direction, length);
  81092. };
  81093. /**
  81094. * Disposes of the controller
  81095. */
  81096. WindowsMotionController.prototype.dispose = function () {
  81097. _super.prototype.dispose.call(this);
  81098. this.onTrackpadChangedObservable.clear();
  81099. };
  81100. /**
  81101. * The base url used to load the left and right controller models
  81102. */
  81103. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  81104. /**
  81105. * The name of the left controller model file
  81106. */
  81107. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  81108. /**
  81109. * The name of the right controller model file
  81110. */
  81111. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  81112. /**
  81113. * The controller name prefix for this controller type
  81114. */
  81115. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  81116. /**
  81117. * The controller id pattern for this controller type
  81118. */
  81119. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  81120. return WindowsMotionController;
  81121. }(BABYLON.WebVRController));
  81122. BABYLON.WindowsMotionController = WindowsMotionController;
  81123. })(BABYLON || (BABYLON = {}));
  81124. //# sourceMappingURL=babylon.windowsMotionController.js.map
  81125. var BABYLON;
  81126. (function (BABYLON) {
  81127. /**
  81128. * Gear VR Controller
  81129. */
  81130. var GearVRController = /** @class */ (function (_super) {
  81131. __extends(GearVRController, _super);
  81132. /**
  81133. * Creates a new GearVRController from a gamepad
  81134. * @param vrGamepad the gamepad that the controller should be created from
  81135. */
  81136. function GearVRController(vrGamepad) {
  81137. var _this = _super.call(this, vrGamepad) || this;
  81138. _this._buttonIndexToObservableNameMap = [
  81139. 'onTrackpadChangedObservable',
  81140. 'onTriggerStateChangedObservable' // Trigger
  81141. ];
  81142. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  81143. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  81144. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  81145. _this._disableTrackPosition(_this._calculatedPosition);
  81146. return _this;
  81147. }
  81148. /**
  81149. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81150. * @param scene scene in which to add meshes
  81151. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81152. */
  81153. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81154. var _this = this;
  81155. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  81156. // Offset the controller so it will rotate around the users wrist
  81157. var mesh = new BABYLON.Mesh("", scene);
  81158. newMeshes[1].parent = mesh;
  81159. newMeshes[1].position.z = -0.15;
  81160. _this._defaultModel = mesh;
  81161. _this.attachToMesh(_this._defaultModel);
  81162. if (meshLoaded) {
  81163. meshLoaded(_this._defaultModel);
  81164. }
  81165. });
  81166. };
  81167. /**
  81168. * Called once for each button that changed state since the last frame
  81169. * @param buttonIdx Which button index changed
  81170. * @param state New state of the button
  81171. * @param changes Which properties on the state changed since last frame
  81172. */
  81173. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81174. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  81175. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  81176. // Only emit events for buttons that we know how to map from index to observable
  81177. var observable = this[observableName];
  81178. if (observable) {
  81179. observable.notifyObservers(state);
  81180. }
  81181. }
  81182. };
  81183. /**
  81184. * Base Url for the controller model.
  81185. */
  81186. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81187. /**
  81188. * File name for the controller model.
  81189. */
  81190. GearVRController.MODEL_FILENAME = 'generic.babylon';
  81191. /**
  81192. * Gamepad Id prefix used to identify this controller.
  81193. */
  81194. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  81195. return GearVRController;
  81196. }(BABYLON.WebVRController));
  81197. BABYLON.GearVRController = GearVRController;
  81198. })(BABYLON || (BABYLON = {}));
  81199. //# sourceMappingURL=babylon.gearVRController.js.map
  81200. var BABYLON;
  81201. (function (BABYLON) {
  81202. /**
  81203. * Google Daydream controller
  81204. */
  81205. var DaydreamController = /** @class */ (function (_super) {
  81206. __extends(DaydreamController, _super);
  81207. /**
  81208. * Creates a new DaydreamController from a gamepad
  81209. * @param vrGamepad the gamepad that the controller should be created from
  81210. */
  81211. function DaydreamController(vrGamepad) {
  81212. var _this = _super.call(this, vrGamepad) || this;
  81213. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  81214. return _this;
  81215. }
  81216. /**
  81217. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81218. * @param scene scene in which to add meshes
  81219. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81220. */
  81221. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81222. var _this = this;
  81223. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  81224. _this._defaultModel = newMeshes[1];
  81225. _this.attachToMesh(_this._defaultModel);
  81226. if (meshLoaded) {
  81227. meshLoaded(_this._defaultModel);
  81228. }
  81229. });
  81230. };
  81231. /**
  81232. * Called once for each button that changed state since the last frame
  81233. * @param buttonIdx Which button index changed
  81234. * @param state New state of the button
  81235. * @param changes Which properties on the state changed since last frame
  81236. */
  81237. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81238. // Daydream controller only has 1 GamepadButton (on the trackpad).
  81239. if (buttonIdx === 0) {
  81240. var observable = this.onTriggerStateChangedObservable;
  81241. if (observable) {
  81242. observable.notifyObservers(state);
  81243. }
  81244. }
  81245. else {
  81246. // If the app or home buttons are ever made available
  81247. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  81248. }
  81249. };
  81250. /**
  81251. * Base Url for the controller model.
  81252. */
  81253. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81254. /**
  81255. * File name for the controller model.
  81256. */
  81257. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  81258. /**
  81259. * Gamepad Id prefix used to identify Daydream Controller.
  81260. */
  81261. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  81262. return DaydreamController;
  81263. }(BABYLON.WebVRController));
  81264. BABYLON.DaydreamController = DaydreamController;
  81265. })(BABYLON || (BABYLON = {}));
  81266. //# sourceMappingURL=babylon.daydreamController.js.map
  81267. var BABYLON;
  81268. (function (BABYLON) {
  81269. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  81270. get: function () {
  81271. if (!this._gamepadManager) {
  81272. this._gamepadManager = new BABYLON.GamepadManager(this);
  81273. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  81274. if (!component) {
  81275. component = new GamepadSystemSceneComponent(this);
  81276. this._addComponent(component);
  81277. }
  81278. }
  81279. return this._gamepadManager;
  81280. },
  81281. enumerable: true,
  81282. configurable: true
  81283. });
  81284. /**
  81285. * Adds a gamepad to the free camera inputs manager
  81286. */
  81287. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  81288. this.add(new BABYLON.FreeCameraGamepadInput());
  81289. return this;
  81290. };
  81291. /**
  81292. * Adds a gamepad to the arc rotate camera inputs manager
  81293. */
  81294. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  81295. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  81296. return this;
  81297. };
  81298. /**
  81299. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  81300. */
  81301. var GamepadSystemSceneComponent = /** @class */ (function () {
  81302. /**
  81303. * Creates a new instance of the component for the given scene
  81304. * @param scene Defines the scene to register the component in
  81305. */
  81306. function GamepadSystemSceneComponent(scene) {
  81307. /**
  81308. * The component name helpfull to identify the component in the list of scene components.
  81309. */
  81310. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  81311. this.scene = scene;
  81312. }
  81313. /**
  81314. * Registers the component in a given scene
  81315. */
  81316. GamepadSystemSceneComponent.prototype.register = function () {
  81317. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  81318. };
  81319. /**
  81320. * Rebuilds the elements related to this component in case of
  81321. * context lost for instance.
  81322. */
  81323. GamepadSystemSceneComponent.prototype.rebuild = function () {
  81324. // Nothing to do for gamepads
  81325. };
  81326. /**
  81327. * Disposes the component and the associated ressources
  81328. */
  81329. GamepadSystemSceneComponent.prototype.dispose = function () {
  81330. var gamepadManager = this.scene._gamepadManager;
  81331. if (gamepadManager) {
  81332. gamepadManager.dispose();
  81333. this.scene._gamepadManager = null;
  81334. }
  81335. };
  81336. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  81337. var gamepadManager = this.scene._gamepadManager;
  81338. if (gamepadManager && gamepadManager._isMonitoring) {
  81339. gamepadManager._checkGamepadsStatus();
  81340. }
  81341. };
  81342. return GamepadSystemSceneComponent;
  81343. }());
  81344. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  81345. })(BABYLON || (BABYLON = {}));
  81346. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  81347. var BABYLON;
  81348. (function (BABYLON) {
  81349. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  81350. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  81351. });
  81352. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  81353. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  81354. });
  81355. /**
  81356. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  81357. * an arc rotate version arcFollowCamera are available.
  81358. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81359. */
  81360. var FollowCamera = /** @class */ (function (_super) {
  81361. __extends(FollowCamera, _super);
  81362. /**
  81363. * Instantiates the follow camera.
  81364. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81365. * @param name Define the name of the camera in the scene
  81366. * @param position Define the position of the camera
  81367. * @param scene Define the scene the camera belong to
  81368. * @param lockedTarget Define the target of the camera
  81369. */
  81370. function FollowCamera(name, position, scene, lockedTarget) {
  81371. if (lockedTarget === void 0) { lockedTarget = null; }
  81372. var _this = _super.call(this, name, position, scene) || this;
  81373. /**
  81374. * Distance the follow camera should follow an object at
  81375. */
  81376. _this.radius = 12;
  81377. /**
  81378. * Define a rotation offset between the camera and the object it follows
  81379. */
  81380. _this.rotationOffset = 0;
  81381. /**
  81382. * Define a height offset between the camera and the object it follows.
  81383. * It can help following an object from the top (like a car chaing a plane)
  81384. */
  81385. _this.heightOffset = 4;
  81386. /**
  81387. * Define how fast the camera can accelerate to follow it s target.
  81388. */
  81389. _this.cameraAcceleration = 0.05;
  81390. /**
  81391. * Define the speed limit of the camera following an object.
  81392. */
  81393. _this.maxCameraSpeed = 20;
  81394. _this.lockedTarget = lockedTarget;
  81395. return _this;
  81396. }
  81397. FollowCamera.prototype._follow = function (cameraTarget) {
  81398. if (!cameraTarget)
  81399. return;
  81400. var yRotation;
  81401. if (cameraTarget.rotationQuaternion) {
  81402. var rotMatrix = new BABYLON.Matrix();
  81403. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  81404. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  81405. }
  81406. else {
  81407. yRotation = cameraTarget.rotation.y;
  81408. }
  81409. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  81410. var targetPosition = cameraTarget.getAbsolutePosition();
  81411. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  81412. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  81413. var dx = targetX - this.position.x;
  81414. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  81415. var dz = (targetZ) - this.position.z;
  81416. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  81417. var vy = dy * this.cameraAcceleration;
  81418. var vz = dz * this.cameraAcceleration * 2;
  81419. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  81420. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  81421. }
  81422. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  81423. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  81424. }
  81425. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  81426. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  81427. }
  81428. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  81429. this.setTarget(targetPosition);
  81430. };
  81431. /** @hidden */
  81432. FollowCamera.prototype._checkInputs = function () {
  81433. _super.prototype._checkInputs.call(this);
  81434. if (this.lockedTarget) {
  81435. this._follow(this.lockedTarget);
  81436. }
  81437. };
  81438. /**
  81439. * Gets the camera class name.
  81440. * @returns the class name
  81441. */
  81442. FollowCamera.prototype.getClassName = function () {
  81443. return "FollowCamera";
  81444. };
  81445. __decorate([
  81446. BABYLON.serialize()
  81447. ], FollowCamera.prototype, "radius", void 0);
  81448. __decorate([
  81449. BABYLON.serialize()
  81450. ], FollowCamera.prototype, "rotationOffset", void 0);
  81451. __decorate([
  81452. BABYLON.serialize()
  81453. ], FollowCamera.prototype, "heightOffset", void 0);
  81454. __decorate([
  81455. BABYLON.serialize()
  81456. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  81457. __decorate([
  81458. BABYLON.serialize()
  81459. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  81460. __decorate([
  81461. BABYLON.serializeAsMeshReference("lockedTargetId")
  81462. ], FollowCamera.prototype, "lockedTarget", void 0);
  81463. return FollowCamera;
  81464. }(BABYLON.TargetCamera));
  81465. BABYLON.FollowCamera = FollowCamera;
  81466. /**
  81467. * Arc Rotate version of the follow camera.
  81468. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  81469. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81470. */
  81471. var ArcFollowCamera = /** @class */ (function (_super) {
  81472. __extends(ArcFollowCamera, _super);
  81473. /**
  81474. * Instantiates a new ArcFollowCamera
  81475. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81476. * @param name Define the name of the camera
  81477. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  81478. * @param beta Define the rotation angle of the camera around the elevation axis
  81479. * @param radius Define the radius of the camera from its target point
  81480. * @param target Define the target of the camera
  81481. * @param scene Define the scene the camera belongs to
  81482. */
  81483. function ArcFollowCamera(name,
  81484. /** The longitudinal angle of the camera */
  81485. alpha,
  81486. /** The latitudinal angle of the camera */
  81487. beta,
  81488. /** The radius of the camera from its target */
  81489. radius,
  81490. /** Define the camera target (the messh it should follow) */
  81491. target, scene) {
  81492. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  81493. _this.alpha = alpha;
  81494. _this.beta = beta;
  81495. _this.radius = radius;
  81496. _this.target = target;
  81497. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  81498. _this._follow();
  81499. return _this;
  81500. }
  81501. ArcFollowCamera.prototype._follow = function () {
  81502. if (!this.target) {
  81503. return;
  81504. }
  81505. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  81506. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  81507. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  81508. var targetPosition = this.target.getAbsolutePosition();
  81509. this.position = targetPosition.add(this._cartesianCoordinates);
  81510. this.setTarget(targetPosition);
  81511. };
  81512. /** @hidden */
  81513. ArcFollowCamera.prototype._checkInputs = function () {
  81514. _super.prototype._checkInputs.call(this);
  81515. this._follow();
  81516. };
  81517. /**
  81518. * Returns the class name of the object.
  81519. * It is mostly used internally for serialization purposes.
  81520. */
  81521. ArcFollowCamera.prototype.getClassName = function () {
  81522. return "ArcFollowCamera";
  81523. };
  81524. return ArcFollowCamera;
  81525. }(BABYLON.TargetCamera));
  81526. BABYLON.ArcFollowCamera = ArcFollowCamera;
  81527. })(BABYLON || (BABYLON = {}));
  81528. //# sourceMappingURL=babylon.followCamera.js.map
  81529. var BABYLON;
  81530. (function (BABYLON) {
  81531. /**
  81532. * 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,
  81533. * which still works and will still be found in many Playgrounds.
  81534. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81535. */
  81536. var UniversalCamera = /** @class */ (function (_super) {
  81537. __extends(UniversalCamera, _super);
  81538. /**
  81539. * 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,
  81540. * which still works and will still be found in many Playgrounds.
  81541. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81542. * @param name Define the name of the camera in the scene
  81543. * @param position Define the start position of the camera in the scene
  81544. * @param scene Define the scene the camera belongs to
  81545. */
  81546. function UniversalCamera(name, position, scene) {
  81547. var _this = _super.call(this, name, position, scene) || this;
  81548. _this.inputs.addGamepad();
  81549. return _this;
  81550. }
  81551. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  81552. /**
  81553. * Defines the gamepad rotation sensiblity.
  81554. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81555. */
  81556. get: function () {
  81557. var gamepad = this.inputs.attached["gamepad"];
  81558. if (gamepad)
  81559. return gamepad.gamepadAngularSensibility;
  81560. return 0;
  81561. },
  81562. set: function (value) {
  81563. var gamepad = this.inputs.attached["gamepad"];
  81564. if (gamepad)
  81565. gamepad.gamepadAngularSensibility = value;
  81566. },
  81567. enumerable: true,
  81568. configurable: true
  81569. });
  81570. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  81571. /**
  81572. * Defines the gamepad move sensiblity.
  81573. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81574. */
  81575. get: function () {
  81576. var gamepad = this.inputs.attached["gamepad"];
  81577. if (gamepad)
  81578. return gamepad.gamepadMoveSensibility;
  81579. return 0;
  81580. },
  81581. set: function (value) {
  81582. var gamepad = this.inputs.attached["gamepad"];
  81583. if (gamepad)
  81584. gamepad.gamepadMoveSensibility = value;
  81585. },
  81586. enumerable: true,
  81587. configurable: true
  81588. });
  81589. /**
  81590. * Gets the current object class name.
  81591. * @return the class name
  81592. */
  81593. UniversalCamera.prototype.getClassName = function () {
  81594. return "UniversalCamera";
  81595. };
  81596. return UniversalCamera;
  81597. }(BABYLON.TouchCamera));
  81598. BABYLON.UniversalCamera = UniversalCamera;
  81599. })(BABYLON || (BABYLON = {}));
  81600. //# sourceMappingURL=babylon.universalCamera.js.map
  81601. var BABYLON;
  81602. (function (BABYLON) {
  81603. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  81604. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  81605. });
  81606. /**
  81607. * This represents a FPS type of camera. This is only here for back compat purpose.
  81608. * Please use the UniversalCamera instead as both are identical.
  81609. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81610. */
  81611. var GamepadCamera = /** @class */ (function (_super) {
  81612. __extends(GamepadCamera, _super);
  81613. /**
  81614. * Instantiates a new Gamepad Camera
  81615. * This represents a FPS type of camera. This is only here for back compat purpose.
  81616. * Please use the UniversalCamera instead as both are identical.
  81617. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81618. * @param name Define the name of the camera in the scene
  81619. * @param position Define the start position of the camera in the scene
  81620. * @param scene Define the scene the camera belongs to
  81621. */
  81622. function GamepadCamera(name, position, scene) {
  81623. return _super.call(this, name, position, scene) || this;
  81624. }
  81625. /**
  81626. * Gets the current object class name.
  81627. * @return the class name
  81628. */
  81629. GamepadCamera.prototype.getClassName = function () {
  81630. return "GamepadCamera";
  81631. };
  81632. return GamepadCamera;
  81633. }(BABYLON.UniversalCamera));
  81634. BABYLON.GamepadCamera = GamepadCamera;
  81635. })(BABYLON || (BABYLON = {}));
  81636. //# sourceMappingURL=babylon.gamepadCamera.js.map
  81637. var BABYLON;
  81638. (function (BABYLON) {
  81639. /**
  81640. * PostProcessRenderPipelineManager class
  81641. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81642. */
  81643. var PostProcessRenderPipelineManager = /** @class */ (function () {
  81644. /**
  81645. * Initializes a PostProcessRenderPipelineManager
  81646. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81647. */
  81648. function PostProcessRenderPipelineManager() {
  81649. this._renderPipelines = {};
  81650. }
  81651. /**
  81652. * Adds a pipeline to the manager
  81653. * @param renderPipeline The pipeline to add
  81654. */
  81655. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  81656. this._renderPipelines[renderPipeline._name] = renderPipeline;
  81657. };
  81658. /**
  81659. * Attaches a camera to the pipeline
  81660. * @param renderPipelineName The name of the pipeline to attach to
  81661. * @param cameras the camera to attach
  81662. * @param unique if the camera can be attached multiple times to the pipeline
  81663. */
  81664. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  81665. if (unique === void 0) { unique = false; }
  81666. var renderPipeline = this._renderPipelines[renderPipelineName];
  81667. if (!renderPipeline) {
  81668. return;
  81669. }
  81670. renderPipeline._attachCameras(cameras, unique);
  81671. };
  81672. /**
  81673. * Detaches a camera from the pipeline
  81674. * @param renderPipelineName The name of the pipeline to detach from
  81675. * @param cameras the camera to detach
  81676. */
  81677. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  81678. var renderPipeline = this._renderPipelines[renderPipelineName];
  81679. if (!renderPipeline) {
  81680. return;
  81681. }
  81682. renderPipeline._detachCameras(cameras);
  81683. };
  81684. /**
  81685. * Enables an effect by name on a pipeline
  81686. * @param renderPipelineName the name of the pipeline to enable the effect in
  81687. * @param renderEffectName the name of the effect to enable
  81688. * @param cameras the cameras that the effect should be enabled on
  81689. */
  81690. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  81691. var renderPipeline = this._renderPipelines[renderPipelineName];
  81692. if (!renderPipeline) {
  81693. return;
  81694. }
  81695. renderPipeline._enableEffect(renderEffectName, cameras);
  81696. };
  81697. /**
  81698. * Disables an effect by name on a pipeline
  81699. * @param renderPipelineName the name of the pipeline to disable the effect in
  81700. * @param renderEffectName the name of the effect to disable
  81701. * @param cameras the cameras that the effect should be disabled on
  81702. */
  81703. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  81704. var renderPipeline = this._renderPipelines[renderPipelineName];
  81705. if (!renderPipeline) {
  81706. return;
  81707. }
  81708. renderPipeline._disableEffect(renderEffectName, cameras);
  81709. };
  81710. /**
  81711. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  81712. */
  81713. PostProcessRenderPipelineManager.prototype.update = function () {
  81714. for (var renderPipelineName in this._renderPipelines) {
  81715. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81716. var pipeline = this._renderPipelines[renderPipelineName];
  81717. if (!pipeline.isSupported) {
  81718. pipeline.dispose();
  81719. delete this._renderPipelines[renderPipelineName];
  81720. }
  81721. else {
  81722. pipeline._update();
  81723. }
  81724. }
  81725. }
  81726. };
  81727. /** @hidden */
  81728. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  81729. for (var renderPipelineName in this._renderPipelines) {
  81730. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81731. var pipeline = this._renderPipelines[renderPipelineName];
  81732. pipeline._rebuild();
  81733. }
  81734. }
  81735. };
  81736. /**
  81737. * Disposes of the manager and pipelines
  81738. */
  81739. PostProcessRenderPipelineManager.prototype.dispose = function () {
  81740. for (var renderPipelineName in this._renderPipelines) {
  81741. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81742. var pipeline = this._renderPipelines[renderPipelineName];
  81743. pipeline.dispose();
  81744. }
  81745. }
  81746. };
  81747. return PostProcessRenderPipelineManager;
  81748. }());
  81749. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  81750. })(BABYLON || (BABYLON = {}));
  81751. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  81752. var BABYLON;
  81753. (function (BABYLON) {
  81754. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  81755. get: function () {
  81756. if (!this._postProcessRenderPipelineManager) {
  81757. // Register the G Buffer component to the scene.
  81758. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  81759. if (!component) {
  81760. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  81761. this._addComponent(component);
  81762. }
  81763. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  81764. }
  81765. return this._postProcessRenderPipelineManager;
  81766. },
  81767. enumerable: true,
  81768. configurable: true
  81769. });
  81770. /**
  81771. * Defines the Render Pipeline scene component responsible to rendering pipelines
  81772. */
  81773. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  81774. /**
  81775. * Creates a new instance of the component for the given scene
  81776. * @param scene Defines the scene to register the component in
  81777. */
  81778. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  81779. /**
  81780. * The component name helpfull to identify the component in the list of scene components.
  81781. */
  81782. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  81783. this.scene = scene;
  81784. }
  81785. /**
  81786. * Registers the component in a given scene
  81787. */
  81788. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  81789. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  81790. };
  81791. /**
  81792. * Rebuilds the elements related to this component in case of
  81793. * context lost for instance.
  81794. */
  81795. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  81796. if (this.scene._postProcessRenderPipelineManager) {
  81797. this.scene._postProcessRenderPipelineManager._rebuild();
  81798. }
  81799. };
  81800. /**
  81801. * Disposes the component and the associated ressources
  81802. */
  81803. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  81804. if (this.scene._postProcessRenderPipelineManager) {
  81805. this.scene._postProcessRenderPipelineManager.dispose();
  81806. }
  81807. };
  81808. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  81809. if (this.scene._postProcessRenderPipelineManager) {
  81810. this.scene._postProcessRenderPipelineManager.update();
  81811. }
  81812. };
  81813. return PostProcessRenderPipelineManagerSceneComponent;
  81814. }());
  81815. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  81816. })(BABYLON || (BABYLON = {}));
  81817. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  81818. var BABYLON;
  81819. (function (BABYLON) {
  81820. /**
  81821. * This represents a set of one or more post processes in Babylon.
  81822. * A post process can be used to apply a shader to a texture after it is rendered.
  81823. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81824. */
  81825. var PostProcessRenderEffect = /** @class */ (function () {
  81826. /**
  81827. * Instantiates a post process render effect.
  81828. * A post process can be used to apply a shader to a texture after it is rendered.
  81829. * @param engine The engine the effect is tied to
  81830. * @param name The name of the effect
  81831. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  81832. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  81833. */
  81834. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  81835. this._name = name;
  81836. this._singleInstance = singleInstance || true;
  81837. this._getPostProcesses = getPostProcesses;
  81838. this._cameras = {};
  81839. this._indicesForCamera = {};
  81840. this._postProcesses = {};
  81841. }
  81842. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  81843. /**
  81844. * Checks if all the post processes in the effect are supported.
  81845. */
  81846. get: function () {
  81847. for (var index in this._postProcesses) {
  81848. if (this._postProcesses.hasOwnProperty(index)) {
  81849. var pps = this._postProcesses[index];
  81850. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  81851. if (!pps[ppIndex].isSupported) {
  81852. return false;
  81853. }
  81854. }
  81855. }
  81856. }
  81857. return true;
  81858. },
  81859. enumerable: true,
  81860. configurable: true
  81861. });
  81862. /**
  81863. * Updates the current state of the effect
  81864. * @hidden
  81865. */
  81866. PostProcessRenderEffect.prototype._update = function () {
  81867. };
  81868. /**
  81869. * Attaches the effect on cameras
  81870. * @param cameras The camera to attach to.
  81871. * @hidden
  81872. */
  81873. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  81874. var _this = this;
  81875. var cameraKey;
  81876. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81877. if (!cams) {
  81878. return;
  81879. }
  81880. for (var i = 0; i < cams.length; i++) {
  81881. var camera = cams[i];
  81882. var cameraName = camera.name;
  81883. if (this._singleInstance) {
  81884. cameraKey = 0;
  81885. }
  81886. else {
  81887. cameraKey = cameraName;
  81888. }
  81889. if (!this._postProcesses[cameraKey]) {
  81890. var postProcess = this._getPostProcesses();
  81891. if (postProcess) {
  81892. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  81893. }
  81894. }
  81895. if (!this._indicesForCamera[cameraName]) {
  81896. this._indicesForCamera[cameraName] = [];
  81897. }
  81898. this._postProcesses[cameraKey].forEach(function (postProcess) {
  81899. var index = camera.attachPostProcess(postProcess);
  81900. _this._indicesForCamera[cameraName].push(index);
  81901. });
  81902. if (!this._cameras[cameraName]) {
  81903. this._cameras[cameraName] = camera;
  81904. }
  81905. }
  81906. };
  81907. /**
  81908. * Detatches the effect on cameras
  81909. * @param cameras The camera to detatch from.
  81910. * @hidden
  81911. */
  81912. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  81913. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81914. if (!cams) {
  81915. return;
  81916. }
  81917. for (var i = 0; i < cams.length; i++) {
  81918. var camera = cams[i];
  81919. var cameraName = camera.name;
  81920. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81921. camera.detachPostProcess(postProcess);
  81922. });
  81923. if (this._cameras[cameraName]) {
  81924. //this._indicesForCamera.splice(index, 1);
  81925. this._cameras[cameraName] = null;
  81926. }
  81927. }
  81928. };
  81929. /**
  81930. * Enables the effect on given cameras
  81931. * @param cameras The camera to enable.
  81932. * @hidden
  81933. */
  81934. PostProcessRenderEffect.prototype._enable = function (cameras) {
  81935. var _this = this;
  81936. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81937. if (!cams) {
  81938. return;
  81939. }
  81940. for (var i = 0; i < cams.length; i++) {
  81941. var camera = cams[i];
  81942. var cameraName = camera.name;
  81943. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  81944. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  81945. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81946. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  81947. });
  81948. }
  81949. }
  81950. }
  81951. };
  81952. /**
  81953. * Disables the effect on the given cameras
  81954. * @param cameras The camera to disable.
  81955. * @hidden
  81956. */
  81957. PostProcessRenderEffect.prototype._disable = function (cameras) {
  81958. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81959. if (!cams) {
  81960. return;
  81961. }
  81962. for (var i = 0; i < cams.length; i++) {
  81963. var camera = cams[i];
  81964. var cameraName = camera.name;
  81965. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81966. camera.detachPostProcess(postProcess);
  81967. });
  81968. }
  81969. };
  81970. /**
  81971. * Gets a list of the post processes contained in the effect.
  81972. * @param camera The camera to get the post processes on.
  81973. * @returns The list of the post processes in the effect.
  81974. */
  81975. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  81976. if (this._singleInstance) {
  81977. return this._postProcesses[0];
  81978. }
  81979. else {
  81980. if (!camera) {
  81981. return null;
  81982. }
  81983. return this._postProcesses[camera.name];
  81984. }
  81985. };
  81986. return PostProcessRenderEffect;
  81987. }());
  81988. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  81989. })(BABYLON || (BABYLON = {}));
  81990. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  81991. var BABYLON;
  81992. (function (BABYLON) {
  81993. /**
  81994. * PostProcessRenderPipeline
  81995. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81996. */
  81997. var PostProcessRenderPipeline = /** @class */ (function () {
  81998. /**
  81999. * Initializes a PostProcessRenderPipeline
  82000. * @param engine engine to add the pipeline to
  82001. * @param name name of the pipeline
  82002. */
  82003. function PostProcessRenderPipeline(engine, name) {
  82004. this.engine = engine;
  82005. this._name = name;
  82006. this._renderEffects = {};
  82007. this._renderEffectsForIsolatedPass = new Array();
  82008. this._cameras = [];
  82009. }
  82010. /**
  82011. * "PostProcessRenderPipeline"
  82012. * @returns "PostProcessRenderPipeline"
  82013. */
  82014. PostProcessRenderPipeline.prototype.getClassName = function () {
  82015. return "PostProcessRenderPipeline";
  82016. };
  82017. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  82018. /**
  82019. * If all the render effects in the pipeline are support
  82020. */
  82021. get: function () {
  82022. for (var renderEffectName in this._renderEffects) {
  82023. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82024. if (!this._renderEffects[renderEffectName].isSupported) {
  82025. return false;
  82026. }
  82027. }
  82028. }
  82029. return true;
  82030. },
  82031. enumerable: true,
  82032. configurable: true
  82033. });
  82034. /**
  82035. * Adds an effect to the pipeline
  82036. * @param renderEffect the effect to add
  82037. */
  82038. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  82039. this._renderEffects[renderEffect._name] = renderEffect;
  82040. };
  82041. // private
  82042. /** @hidden */
  82043. PostProcessRenderPipeline.prototype._rebuild = function () {
  82044. };
  82045. /** @hidden */
  82046. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  82047. var renderEffects = this._renderEffects[renderEffectName];
  82048. if (!renderEffects) {
  82049. return;
  82050. }
  82051. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82052. };
  82053. /** @hidden */
  82054. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  82055. var renderEffects = this._renderEffects[renderEffectName];
  82056. if (!renderEffects) {
  82057. return;
  82058. }
  82059. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82060. };
  82061. /** @hidden */
  82062. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  82063. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82064. if (!cams) {
  82065. return;
  82066. }
  82067. var indicesToDelete = [];
  82068. var i;
  82069. for (i = 0; i < cams.length; i++) {
  82070. var camera = cams[i];
  82071. var cameraName = camera.name;
  82072. if (this._cameras.indexOf(camera) === -1) {
  82073. this._cameras[cameraName] = camera;
  82074. }
  82075. else if (unique) {
  82076. indicesToDelete.push(i);
  82077. }
  82078. }
  82079. for (i = 0; i < indicesToDelete.length; i++) {
  82080. cameras.splice(indicesToDelete[i], 1);
  82081. }
  82082. for (var renderEffectName in this._renderEffects) {
  82083. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82084. this._renderEffects[renderEffectName]._attachCameras(cams);
  82085. }
  82086. }
  82087. };
  82088. /** @hidden */
  82089. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  82090. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82091. if (!cams) {
  82092. return;
  82093. }
  82094. for (var renderEffectName in this._renderEffects) {
  82095. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82096. this._renderEffects[renderEffectName]._detachCameras(cams);
  82097. }
  82098. }
  82099. for (var i = 0; i < cams.length; i++) {
  82100. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  82101. }
  82102. };
  82103. /** @hidden */
  82104. PostProcessRenderPipeline.prototype._update = function () {
  82105. for (var renderEffectName in this._renderEffects) {
  82106. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82107. this._renderEffects[renderEffectName]._update();
  82108. }
  82109. }
  82110. for (var i = 0; i < this._cameras.length; i++) {
  82111. var cameraName = this._cameras[i].name;
  82112. if (this._renderEffectsForIsolatedPass[cameraName]) {
  82113. this._renderEffectsForIsolatedPass[cameraName]._update();
  82114. }
  82115. }
  82116. };
  82117. /** @hidden */
  82118. PostProcessRenderPipeline.prototype._reset = function () {
  82119. this._renderEffects = {};
  82120. this._renderEffectsForIsolatedPass = new Array();
  82121. };
  82122. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  82123. // 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)
  82124. var effectKeys = Object.keys(this._renderEffects);
  82125. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  82126. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  82127. if (postProcesses) {
  82128. postProcesses[0].samples = sampleCount;
  82129. return true;
  82130. }
  82131. }
  82132. return false;
  82133. };
  82134. /**
  82135. * Disposes of the pipeline
  82136. */
  82137. PostProcessRenderPipeline.prototype.dispose = function () {
  82138. // Must be implemented by children
  82139. };
  82140. __decorate([
  82141. BABYLON.serialize()
  82142. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  82143. return PostProcessRenderPipeline;
  82144. }());
  82145. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  82146. })(BABYLON || (BABYLON = {}));
  82147. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  82148. var BABYLON;
  82149. (function (BABYLON) {
  82150. /**
  82151. * This represents a depth renderer in Babylon.
  82152. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  82153. */
  82154. var DepthRenderer = /** @class */ (function () {
  82155. /**
  82156. * Instantiates a depth renderer
  82157. * @param scene The scene the renderer belongs to
  82158. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  82159. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  82160. */
  82161. function DepthRenderer(scene, type, camera) {
  82162. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  82163. if (camera === void 0) { camera = null; }
  82164. var _this = this;
  82165. /**
  82166. * Specifiess that the depth renderer will only be used within
  82167. * the camera it is created for.
  82168. * This can help forcing its rendering during the camera processing.
  82169. */
  82170. this.useOnlyInActiveCamera = false;
  82171. this._scene = scene;
  82172. // Register the G Buffer component to the scene.
  82173. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  82174. if (!component) {
  82175. component = new BABYLON.DepthRendererSceneComponent(scene);
  82176. scene._addComponent(component);
  82177. }
  82178. this._camera = camera;
  82179. var engine = scene.getEngine();
  82180. // Render target
  82181. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  82182. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82183. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82184. this._depthMap.refreshRate = 1;
  82185. this._depthMap.renderParticles = false;
  82186. this._depthMap.renderList = null;
  82187. // Camera to get depth map from to support multiple concurrent cameras
  82188. this._depthMap.activeCamera = this._camera;
  82189. this._depthMap.ignoreCameraViewport = true;
  82190. this._depthMap.useCameraPostProcesses = false;
  82191. // set default depth value to 1.0 (far away)
  82192. this._depthMap.onClearObservable.add(function (engine) {
  82193. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  82194. });
  82195. // Custom render function
  82196. var renderSubMesh = function (subMesh) {
  82197. var mesh = subMesh.getRenderingMesh();
  82198. var scene = _this._scene;
  82199. var engine = scene.getEngine();
  82200. var material = subMesh.getMaterial();
  82201. if (!material) {
  82202. return;
  82203. }
  82204. // Culling and reverse (right handed system)
  82205. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  82206. // Managing instances
  82207. var batch = mesh._getInstancesRenderList(subMesh._id);
  82208. if (batch.mustReturn) {
  82209. return;
  82210. }
  82211. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82212. var camera = _this._camera || scene.activeCamera;
  82213. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  82214. engine.enableEffect(_this._effect);
  82215. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  82216. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82217. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  82218. // Alpha test
  82219. if (material && material.needAlphaTesting()) {
  82220. var alphaTexture = material.getAlphaTestTexture();
  82221. if (alphaTexture) {
  82222. _this._effect.setTexture("diffuseSampler", alphaTexture);
  82223. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82224. }
  82225. }
  82226. // Bones
  82227. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82228. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82229. }
  82230. // Draw
  82231. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  82232. }
  82233. };
  82234. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82235. var index;
  82236. if (depthOnlySubMeshes.length) {
  82237. engine.setColorWrite(false);
  82238. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82239. renderSubMesh(depthOnlySubMeshes.data[index]);
  82240. }
  82241. engine.setColorWrite(true);
  82242. }
  82243. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82244. renderSubMesh(opaqueSubMeshes.data[index]);
  82245. }
  82246. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82247. renderSubMesh(alphaTestSubMeshes.data[index]);
  82248. }
  82249. };
  82250. }
  82251. /**
  82252. * Creates the depth rendering effect and checks if the effect is ready.
  82253. * @param subMesh The submesh to be used to render the depth map of
  82254. * @param useInstances If multiple world instances should be used
  82255. * @returns if the depth renderer is ready to render the depth map
  82256. */
  82257. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  82258. var material = subMesh.getMaterial();
  82259. if (material.disableDepthWrite) {
  82260. return false;
  82261. }
  82262. var defines = [];
  82263. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82264. var mesh = subMesh.getMesh();
  82265. // Alpha test
  82266. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  82267. defines.push("#define ALPHATEST");
  82268. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82269. attribs.push(BABYLON.VertexBuffer.UVKind);
  82270. defines.push("#define UV1");
  82271. }
  82272. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82273. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82274. defines.push("#define UV2");
  82275. }
  82276. }
  82277. // Bones
  82278. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82279. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82280. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82281. if (mesh.numBoneInfluencers > 4) {
  82282. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82283. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82284. }
  82285. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82286. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82287. }
  82288. else {
  82289. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82290. }
  82291. // Instances
  82292. if (useInstances) {
  82293. defines.push("#define INSTANCES");
  82294. attribs.push("world0");
  82295. attribs.push("world1");
  82296. attribs.push("world2");
  82297. attribs.push("world3");
  82298. }
  82299. // Get correct effect
  82300. var join = defines.join("\n");
  82301. if (this._cachedDefines !== join) {
  82302. this._cachedDefines = join;
  82303. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  82304. }
  82305. return this._effect.isReady();
  82306. };
  82307. /**
  82308. * Gets the texture which the depth map will be written to.
  82309. * @returns The depth map texture
  82310. */
  82311. DepthRenderer.prototype.getDepthMap = function () {
  82312. return this._depthMap;
  82313. };
  82314. /**
  82315. * Disposes of the depth renderer.
  82316. */
  82317. DepthRenderer.prototype.dispose = function () {
  82318. this._depthMap.dispose();
  82319. };
  82320. return DepthRenderer;
  82321. }());
  82322. BABYLON.DepthRenderer = DepthRenderer;
  82323. })(BABYLON || (BABYLON = {}));
  82324. //# sourceMappingURL=babylon.depthRenderer.js.map
  82325. var BABYLON;
  82326. (function (BABYLON) {
  82327. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  82328. camera = camera || this.activeCamera;
  82329. if (!camera) {
  82330. throw "No camera available to enable depth renderer";
  82331. }
  82332. if (!this._depthRenderer) {
  82333. this._depthRenderer = {};
  82334. }
  82335. if (!this._depthRenderer[camera.id]) {
  82336. var textureType = 0;
  82337. if (this.getEngine().getCaps().textureHalfFloatRender) {
  82338. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82339. }
  82340. else if (this.getEngine().getCaps().textureFloatRender) {
  82341. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82342. }
  82343. else {
  82344. throw "Depth renderer does not support int texture type";
  82345. }
  82346. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  82347. }
  82348. return this._depthRenderer[camera.id];
  82349. };
  82350. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  82351. camera = camera || this.activeCamera;
  82352. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  82353. return;
  82354. }
  82355. this._depthRenderer[camera.id].dispose();
  82356. delete this._depthRenderer[camera.id];
  82357. };
  82358. /**
  82359. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  82360. * in several rendering techniques.
  82361. */
  82362. var DepthRendererSceneComponent = /** @class */ (function () {
  82363. /**
  82364. * Creates a new instance of the component for the given scene
  82365. * @param scene Defines the scene to register the component in
  82366. */
  82367. function DepthRendererSceneComponent(scene) {
  82368. /**
  82369. * The component name helpfull to identify the component in the list of scene components.
  82370. */
  82371. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  82372. this.scene = scene;
  82373. }
  82374. /**
  82375. * Registers the component in a given scene
  82376. */
  82377. DepthRendererSceneComponent.prototype.register = function () {
  82378. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  82379. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  82380. };
  82381. /**
  82382. * Rebuilds the elements related to this component in case of
  82383. * context lost for instance.
  82384. */
  82385. DepthRendererSceneComponent.prototype.rebuild = function () {
  82386. // Nothing to do for this component
  82387. };
  82388. /**
  82389. * Disposes the component and the associated ressources
  82390. */
  82391. DepthRendererSceneComponent.prototype.dispose = function () {
  82392. for (var key in this.scene._depthRenderer) {
  82393. this.scene._depthRenderer[key].dispose();
  82394. }
  82395. };
  82396. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82397. if (this.scene._depthRenderer) {
  82398. for (var key in this.scene._depthRenderer) {
  82399. var depthRenderer = this.scene._depthRenderer[key];
  82400. if (!depthRenderer.useOnlyInActiveCamera) {
  82401. renderTargets.push(depthRenderer.getDepthMap());
  82402. }
  82403. }
  82404. }
  82405. };
  82406. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  82407. if (this.scene._depthRenderer) {
  82408. for (var key in this.scene._depthRenderer) {
  82409. var depthRenderer = this.scene._depthRenderer[key];
  82410. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  82411. renderTargets.push(depthRenderer.getDepthMap());
  82412. }
  82413. }
  82414. }
  82415. };
  82416. return DepthRendererSceneComponent;
  82417. }());
  82418. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  82419. })(BABYLON || (BABYLON = {}));
  82420. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  82421. var BABYLON;
  82422. (function (BABYLON) {
  82423. /**
  82424. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  82425. */
  82426. var GeometryBufferRenderer = /** @class */ (function () {
  82427. /**
  82428. * Creates a new G Buffer for the scene
  82429. * @param scene The scene the buffer belongs to
  82430. * @param ratio How big is the buffer related to the main canvas.
  82431. */
  82432. function GeometryBufferRenderer(scene, ratio) {
  82433. if (ratio === void 0) { ratio = 1; }
  82434. this._enablePosition = false;
  82435. this._scene = scene;
  82436. this._ratio = ratio;
  82437. // Register the G Buffer component to the scene.
  82438. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  82439. if (!component) {
  82440. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  82441. scene._addComponent(component);
  82442. }
  82443. // Render target
  82444. this._createRenderTargets();
  82445. }
  82446. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  82447. /**
  82448. * Set the render list (meshes to be rendered) used in the G buffer.
  82449. */
  82450. set: function (meshes) {
  82451. this._multiRenderTarget.renderList = meshes;
  82452. },
  82453. enumerable: true,
  82454. configurable: true
  82455. });
  82456. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  82457. /**
  82458. * Gets wether or not G buffer are supported by the running hardware.
  82459. * This requires draw buffer supports
  82460. */
  82461. get: function () {
  82462. return this._multiRenderTarget.isSupported;
  82463. },
  82464. enumerable: true,
  82465. configurable: true
  82466. });
  82467. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  82468. /**
  82469. * Gets wether or not position are enabled for the G buffer.
  82470. */
  82471. get: function () {
  82472. return this._enablePosition;
  82473. },
  82474. /**
  82475. * Sets wether or not position are enabled for the G buffer.
  82476. */
  82477. set: function (enable) {
  82478. this._enablePosition = enable;
  82479. this.dispose();
  82480. this._createRenderTargets();
  82481. },
  82482. enumerable: true,
  82483. configurable: true
  82484. });
  82485. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  82486. /**
  82487. * Gets the scene associated with the buffer.
  82488. */
  82489. get: function () {
  82490. return this._scene;
  82491. },
  82492. enumerable: true,
  82493. configurable: true
  82494. });
  82495. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  82496. /**
  82497. * Gets the ratio used by the buffer during its creation.
  82498. * How big is the buffer related to the main canvas.
  82499. */
  82500. get: function () {
  82501. return this._ratio;
  82502. },
  82503. enumerable: true,
  82504. configurable: true
  82505. });
  82506. /**
  82507. * Checks wether everything is ready to render a submesh to the G buffer.
  82508. * @param subMesh the submesh to check readiness for
  82509. * @param useInstances is the mesh drawn using instance or not
  82510. * @returns true if ready otherwise false
  82511. */
  82512. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  82513. var material = subMesh.getMaterial();
  82514. if (material && material.disableDepthWrite) {
  82515. return false;
  82516. }
  82517. var defines = [];
  82518. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  82519. var mesh = subMesh.getMesh();
  82520. // Alpha test
  82521. if (material && material.needAlphaTesting()) {
  82522. defines.push("#define ALPHATEST");
  82523. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82524. attribs.push(BABYLON.VertexBuffer.UVKind);
  82525. defines.push("#define UV1");
  82526. }
  82527. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82528. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82529. defines.push("#define UV2");
  82530. }
  82531. }
  82532. // Buffers
  82533. if (this._enablePosition) {
  82534. defines.push("#define POSITION");
  82535. }
  82536. // Bones
  82537. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82538. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82539. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82540. if (mesh.numBoneInfluencers > 4) {
  82541. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82542. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82543. }
  82544. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82545. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82546. }
  82547. else {
  82548. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82549. }
  82550. // Instances
  82551. if (useInstances) {
  82552. defines.push("#define INSTANCES");
  82553. attribs.push("world0");
  82554. attribs.push("world1");
  82555. attribs.push("world2");
  82556. attribs.push("world3");
  82557. }
  82558. // Get correct effect
  82559. var join = defines.join("\n");
  82560. if (this._cachedDefines !== join) {
  82561. this._cachedDefines = join;
  82562. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  82563. }
  82564. return this._effect.isReady();
  82565. };
  82566. /**
  82567. * Gets the current underlying G Buffer.
  82568. * @returns the buffer
  82569. */
  82570. GeometryBufferRenderer.prototype.getGBuffer = function () {
  82571. return this._multiRenderTarget;
  82572. };
  82573. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  82574. /**
  82575. * Gets the number of samples used to render the buffer (anti aliasing).
  82576. */
  82577. get: function () {
  82578. return this._multiRenderTarget.samples;
  82579. },
  82580. /**
  82581. * Sets the number of samples used to render the buffer (anti aliasing).
  82582. */
  82583. set: function (value) {
  82584. this._multiRenderTarget.samples = value;
  82585. },
  82586. enumerable: true,
  82587. configurable: true
  82588. });
  82589. /**
  82590. * Disposes the renderer and frees up associated resources.
  82591. */
  82592. GeometryBufferRenderer.prototype.dispose = function () {
  82593. this.getGBuffer().dispose();
  82594. };
  82595. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  82596. var _this = this;
  82597. var engine = this._scene.getEngine();
  82598. var count = this._enablePosition ? 3 : 2;
  82599. 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 });
  82600. if (!this.isSupported) {
  82601. return;
  82602. }
  82603. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82604. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82605. this._multiRenderTarget.refreshRate = 1;
  82606. this._multiRenderTarget.renderParticles = false;
  82607. this._multiRenderTarget.renderList = null;
  82608. // set default depth value to 1.0 (far away)
  82609. this._multiRenderTarget.onClearObservable.add(function (engine) {
  82610. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  82611. });
  82612. // Custom render function
  82613. var renderSubMesh = function (subMesh) {
  82614. var mesh = subMesh.getRenderingMesh();
  82615. var scene = _this._scene;
  82616. var engine = scene.getEngine();
  82617. var material = subMesh.getMaterial();
  82618. if (!material) {
  82619. return;
  82620. }
  82621. // Culling
  82622. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  82623. // Managing instances
  82624. var batch = mesh._getInstancesRenderList(subMesh._id);
  82625. if (batch.mustReturn) {
  82626. return;
  82627. }
  82628. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82629. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  82630. engine.enableEffect(_this._effect);
  82631. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  82632. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82633. _this._effect.setMatrix("view", scene.getViewMatrix());
  82634. // Alpha test
  82635. if (material && material.needAlphaTesting()) {
  82636. var alphaTexture = material.getAlphaTestTexture();
  82637. if (alphaTexture) {
  82638. _this._effect.setTexture("diffuseSampler", alphaTexture);
  82639. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82640. }
  82641. }
  82642. // Bones
  82643. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82644. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82645. }
  82646. // Draw
  82647. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  82648. }
  82649. };
  82650. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82651. var index;
  82652. if (depthOnlySubMeshes.length) {
  82653. engine.setColorWrite(false);
  82654. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82655. renderSubMesh(depthOnlySubMeshes.data[index]);
  82656. }
  82657. engine.setColorWrite(true);
  82658. }
  82659. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82660. renderSubMesh(opaqueSubMeshes.data[index]);
  82661. }
  82662. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82663. renderSubMesh(alphaTestSubMeshes.data[index]);
  82664. }
  82665. };
  82666. };
  82667. return GeometryBufferRenderer;
  82668. }());
  82669. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  82670. })(BABYLON || (BABYLON = {}));
  82671. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  82672. var BABYLON;
  82673. (function (BABYLON) {
  82674. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  82675. get: function () {
  82676. this._geometryBufferRenderer;
  82677. },
  82678. set: function (value) {
  82679. if (value && value.isSupported) {
  82680. this._geometryBufferRenderer = value;
  82681. }
  82682. ;
  82683. },
  82684. enumerable: true,
  82685. configurable: true
  82686. });
  82687. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  82688. if (ratio === void 0) { ratio = 1; }
  82689. if (this._geometryBufferRenderer) {
  82690. return this._geometryBufferRenderer;
  82691. }
  82692. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  82693. if (!this._geometryBufferRenderer.isSupported) {
  82694. this._geometryBufferRenderer = null;
  82695. }
  82696. return this._geometryBufferRenderer;
  82697. };
  82698. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  82699. if (!this._geometryBufferRenderer) {
  82700. return;
  82701. }
  82702. this._geometryBufferRenderer.dispose();
  82703. this._geometryBufferRenderer = null;
  82704. };
  82705. /**
  82706. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  82707. * in several rendering techniques.
  82708. */
  82709. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  82710. /**
  82711. * Creates a new instance of the component for the given scene
  82712. * @param scene Defines the scene to register the component in
  82713. */
  82714. function GeometryBufferRendererSceneComponent(scene) {
  82715. /**
  82716. * The component name helpful to identify the component in the list of scene components.
  82717. */
  82718. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  82719. this.scene = scene;
  82720. }
  82721. /**
  82722. * Registers the component in a given scene
  82723. */
  82724. GeometryBufferRendererSceneComponent.prototype.register = function () {
  82725. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  82726. };
  82727. /**
  82728. * Rebuilds the elements related to this component in case of
  82729. * context lost for instance.
  82730. */
  82731. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  82732. // Nothing to do for this component
  82733. };
  82734. /**
  82735. * Disposes the component and the associated ressources
  82736. */
  82737. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  82738. // Nothing to do for this component
  82739. };
  82740. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82741. if (this.scene._geometryBufferRenderer) {
  82742. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  82743. }
  82744. };
  82745. return GeometryBufferRendererSceneComponent;
  82746. }());
  82747. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  82748. })(BABYLON || (BABYLON = {}));
  82749. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  82750. var BABYLON;
  82751. (function (BABYLON) {
  82752. var SSAORenderingPipeline = /** @class */ (function (_super) {
  82753. __extends(SSAORenderingPipeline, _super);
  82754. /**
  82755. * @constructor
  82756. * @param {string} name - The rendering pipeline name
  82757. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82758. * @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 }
  82759. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82760. */
  82761. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  82762. var _this = _super.call(this, scene.getEngine(), name) || this;
  82763. // Members
  82764. /**
  82765. * The PassPostProcess id in the pipeline that contains the original scene color
  82766. */
  82767. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  82768. /**
  82769. * The SSAO PostProcess id in the pipeline
  82770. */
  82771. _this.SSAORenderEffect = "SSAORenderEffect";
  82772. /**
  82773. * The horizontal blur PostProcess id in the pipeline
  82774. */
  82775. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  82776. /**
  82777. * The vertical blur PostProcess id in the pipeline
  82778. */
  82779. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  82780. /**
  82781. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  82782. */
  82783. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  82784. /**
  82785. * The output strength of the SSAO post-process. Default value is 1.0.
  82786. */
  82787. _this.totalStrength = 1.0;
  82788. /**
  82789. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  82790. */
  82791. _this.radius = 0.0001;
  82792. /**
  82793. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  82794. * Must not be equal to fallOff and superior to fallOff.
  82795. * Default value is 0.975
  82796. */
  82797. _this.area = 0.0075;
  82798. /**
  82799. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  82800. * Must not be equal to area and inferior to area.
  82801. * Default value is 0.0
  82802. */
  82803. _this.fallOff = 0.000001;
  82804. /**
  82805. * The base color of the SSAO post-process
  82806. * The final result is "base + ssao" between [0, 1]
  82807. */
  82808. _this.base = 0.5;
  82809. _this._firstUpdate = true;
  82810. _this._scene = scene;
  82811. // Set up assets
  82812. _this._createRandomTexture();
  82813. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  82814. var ssaoRatio = ratio.ssaoRatio || ratio;
  82815. var combineRatio = ratio.combineRatio || ratio;
  82816. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  82817. _this._createSSAOPostProcess(ssaoRatio);
  82818. _this._createBlurPostProcess(ssaoRatio);
  82819. _this._createSSAOCombinePostProcess(combineRatio);
  82820. // Set up pipeline
  82821. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  82822. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  82823. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  82824. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  82825. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  82826. // Finish
  82827. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82828. if (cameras)
  82829. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  82830. return _this;
  82831. }
  82832. // Public Methods
  82833. /**
  82834. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  82835. */
  82836. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  82837. if (disableDepthRender === void 0) { disableDepthRender = false; }
  82838. for (var i = 0; i < this._scene.cameras.length; i++) {
  82839. var camera = this._scene.cameras[i];
  82840. this._originalColorPostProcess.dispose(camera);
  82841. this._ssaoPostProcess.dispose(camera);
  82842. this._blurHPostProcess.dispose(camera);
  82843. this._blurVPostProcess.dispose(camera);
  82844. this._ssaoCombinePostProcess.dispose(camera);
  82845. }
  82846. this._randomTexture.dispose();
  82847. if (disableDepthRender)
  82848. this._scene.disableDepthRenderer();
  82849. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  82850. _super.prototype.dispose.call(this);
  82851. };
  82852. // Private Methods
  82853. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  82854. var _this = this;
  82855. var size = 16;
  82856. 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);
  82857. 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);
  82858. this._blurHPostProcess.onActivateObservable.add(function () {
  82859. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  82860. _this._blurHPostProcess.kernel = size * dw;
  82861. });
  82862. this._blurVPostProcess.onActivateObservable.add(function () {
  82863. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  82864. _this._blurVPostProcess.kernel = size * dw;
  82865. });
  82866. };
  82867. /** @hidden */
  82868. SSAORenderingPipeline.prototype._rebuild = function () {
  82869. this._firstUpdate = true;
  82870. _super.prototype._rebuild.call(this);
  82871. };
  82872. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  82873. var _this = this;
  82874. var numSamples = 16;
  82875. var sampleSphere = [
  82876. 0.5381, 0.1856, -0.4319,
  82877. 0.1379, 0.2486, 0.4430,
  82878. 0.3371, 0.5679, -0.0057,
  82879. -0.6999, -0.0451, -0.0019,
  82880. 0.0689, -0.1598, -0.8547,
  82881. 0.0560, 0.0069, -0.1843,
  82882. -0.0146, 0.1402, 0.0762,
  82883. 0.0100, -0.1924, -0.0344,
  82884. -0.3577, -0.5301, -0.4358,
  82885. -0.3169, 0.1063, 0.0158,
  82886. 0.0103, -0.5869, 0.0046,
  82887. -0.0897, -0.4940, 0.3287,
  82888. 0.7119, -0.0154, -0.0918,
  82889. -0.0533, 0.0596, -0.5411,
  82890. 0.0352, -0.0631, 0.5460,
  82891. -0.4776, 0.2847, -0.0271
  82892. ];
  82893. var samplesFactor = 1.0 / numSamples;
  82894. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  82895. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  82896. "area", "fallOff", "base", "range", "viewport"
  82897. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  82898. this._ssaoPostProcess.onApply = function (effect) {
  82899. if (_this._firstUpdate) {
  82900. effect.setArray3("sampleSphere", sampleSphere);
  82901. effect.setFloat("samplesFactor", samplesFactor);
  82902. effect.setFloat("randTextureTiles", 4.0);
  82903. }
  82904. effect.setFloat("totalStrength", _this.totalStrength);
  82905. effect.setFloat("radius", _this.radius);
  82906. effect.setFloat("area", _this.area);
  82907. effect.setFloat("fallOff", _this.fallOff);
  82908. effect.setFloat("base", _this.base);
  82909. effect.setTexture("textureSampler", _this._depthTexture);
  82910. effect.setTexture("randomSampler", _this._randomTexture);
  82911. };
  82912. };
  82913. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  82914. var _this = this;
  82915. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82916. this._ssaoCombinePostProcess.onApply = function (effect) {
  82917. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  82918. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  82919. };
  82920. };
  82921. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  82922. var size = 512;
  82923. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82924. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  82925. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  82926. var context = this._randomTexture.getContext();
  82927. var rand = function (min, max) {
  82928. return Math.random() * (max - min) + min;
  82929. };
  82930. var randVector = BABYLON.Vector3.Zero();
  82931. for (var x = 0; x < size; x++) {
  82932. for (var y = 0; y < size; y++) {
  82933. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  82934. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  82935. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  82936. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  82937. context.fillRect(x, y, 1, 1);
  82938. }
  82939. }
  82940. this._randomTexture.update(false);
  82941. };
  82942. __decorate([
  82943. BABYLON.serialize()
  82944. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  82945. __decorate([
  82946. BABYLON.serialize()
  82947. ], SSAORenderingPipeline.prototype, "radius", void 0);
  82948. __decorate([
  82949. BABYLON.serialize()
  82950. ], SSAORenderingPipeline.prototype, "area", void 0);
  82951. __decorate([
  82952. BABYLON.serialize()
  82953. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  82954. __decorate([
  82955. BABYLON.serialize()
  82956. ], SSAORenderingPipeline.prototype, "base", void 0);
  82957. return SSAORenderingPipeline;
  82958. }(BABYLON.PostProcessRenderPipeline));
  82959. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  82960. })(BABYLON || (BABYLON = {}));
  82961. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  82962. var BABYLON;
  82963. (function (BABYLON) {
  82964. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  82965. __extends(SSAO2RenderingPipeline, _super);
  82966. /**
  82967. * @constructor
  82968. * @param {string} name - The rendering pipeline name
  82969. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82970. * @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 }
  82971. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82972. */
  82973. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  82974. var _this = _super.call(this, scene.getEngine(), name) || this;
  82975. // Members
  82976. /**
  82977. * The PassPostProcess id in the pipeline that contains the original scene color
  82978. */
  82979. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  82980. /**
  82981. * The SSAO PostProcess id in the pipeline
  82982. */
  82983. _this.SSAORenderEffect = "SSAORenderEffect";
  82984. /**
  82985. * The horizontal blur PostProcess id in the pipeline
  82986. */
  82987. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  82988. /**
  82989. * The vertical blur PostProcess id in the pipeline
  82990. */
  82991. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  82992. /**
  82993. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  82994. */
  82995. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  82996. /**
  82997. * The output strength of the SSAO post-process. Default value is 1.0.
  82998. */
  82999. _this.totalStrength = 1.0;
  83000. /**
  83001. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  83002. */
  83003. _this.maxZ = 100.0;
  83004. /**
  83005. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  83006. */
  83007. _this.minZAspect = 0.2;
  83008. _this._samples = 8;
  83009. _this._textureSamples = 1;
  83010. /**
  83011. * Are we using bilateral blur ?
  83012. */
  83013. _this._expensiveBlur = true;
  83014. /**
  83015. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  83016. */
  83017. _this.radius = 2.0;
  83018. /**
  83019. * The base color of the SSAO post-process
  83020. * The final result is "base + ssao" between [0, 1]
  83021. */
  83022. _this.base = 0;
  83023. _this._firstUpdate = true;
  83024. _this._bits = new Uint32Array(1);
  83025. _this._scene = scene;
  83026. _this._ratio = ratio;
  83027. if (!_this.isSupported) {
  83028. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  83029. return _this;
  83030. }
  83031. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  83032. var blurRatio = _this._ratio.blurRatio || ratio;
  83033. // Set up assets
  83034. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  83035. _this._createRandomTexture();
  83036. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  83037. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  83038. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  83039. _this._originalColorPostProcess.samples = _this.textureSamples;
  83040. _this._createSSAOPostProcess(1.0);
  83041. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  83042. _this._createSSAOCombinePostProcess(blurRatio);
  83043. // Set up pipeline
  83044. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  83045. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  83046. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  83047. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  83048. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  83049. // Finish
  83050. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83051. if (cameras)
  83052. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83053. return _this;
  83054. }
  83055. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  83056. get: function () {
  83057. return this._samples;
  83058. },
  83059. /**
  83060. * Number of samples used for the SSAO calculations. Default value is 8
  83061. */
  83062. set: function (n) {
  83063. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  83064. this._samples = n;
  83065. this._sampleSphere = this._generateHemisphere();
  83066. this._firstUpdate = true;
  83067. },
  83068. enumerable: true,
  83069. configurable: true
  83070. });
  83071. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  83072. get: function () {
  83073. return this._textureSamples;
  83074. },
  83075. /**
  83076. * Number of samples to use for antialiasing
  83077. */
  83078. set: function (n) {
  83079. this._textureSamples = n;
  83080. this._originalColorPostProcess.samples = n;
  83081. this._blurHPostProcess.samples = n;
  83082. this._blurVPostProcess.samples = n;
  83083. this._ssaoPostProcess.samples = n;
  83084. this._ssaoCombinePostProcess.samples = n;
  83085. },
  83086. enumerable: true,
  83087. configurable: true
  83088. });
  83089. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  83090. get: function () {
  83091. return this._expensiveBlur;
  83092. },
  83093. set: function (b) {
  83094. 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"]);
  83095. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  83096. this._expensiveBlur = b;
  83097. this._firstUpdate = true;
  83098. },
  83099. enumerable: true,
  83100. configurable: true
  83101. });
  83102. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  83103. /**
  83104. * Support test.
  83105. */
  83106. get: function () {
  83107. var engine = BABYLON.Engine.LastCreatedEngine;
  83108. if (!engine) {
  83109. return false;
  83110. }
  83111. return engine.getCaps().drawBuffersExtension;
  83112. },
  83113. enumerable: true,
  83114. configurable: true
  83115. });
  83116. // Public Methods
  83117. /**
  83118. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  83119. */
  83120. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  83121. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  83122. for (var i = 0; i < this._scene.cameras.length; i++) {
  83123. var camera = this._scene.cameras[i];
  83124. this._originalColorPostProcess.dispose(camera);
  83125. this._ssaoPostProcess.dispose(camera);
  83126. this._blurHPostProcess.dispose(camera);
  83127. this._blurVPostProcess.dispose(camera);
  83128. this._ssaoCombinePostProcess.dispose(camera);
  83129. }
  83130. this._randomTexture.dispose();
  83131. if (disableGeometryBufferRenderer)
  83132. this._scene.disableGeometryBufferRenderer();
  83133. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  83134. _super.prototype.dispose.call(this);
  83135. };
  83136. // Private Methods
  83137. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  83138. var _this = this;
  83139. this._samplerOffsets = [];
  83140. var expensive = this.expensiveBlur;
  83141. for (var i = -8; i < 8; i++) {
  83142. this._samplerOffsets.push(i * 2 + 0.5);
  83143. }
  83144. 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");
  83145. this._blurHPostProcess.onApply = function (effect) {
  83146. if (!_this._scene.activeCamera) {
  83147. return;
  83148. }
  83149. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  83150. effect.setFloat("near", _this._scene.activeCamera.minZ);
  83151. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  83152. effect.setFloat("radius", _this.radius);
  83153. effect.setTexture("depthSampler", _this._depthTexture);
  83154. if (_this._firstUpdate) {
  83155. effect.setArray("samplerOffsets", _this._samplerOffsets);
  83156. }
  83157. };
  83158. 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");
  83159. this._blurVPostProcess.onApply = function (effect) {
  83160. if (!_this._scene.activeCamera) {
  83161. return;
  83162. }
  83163. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  83164. effect.setFloat("near", _this._scene.activeCamera.minZ);
  83165. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  83166. effect.setFloat("radius", _this.radius);
  83167. effect.setTexture("depthSampler", _this._depthTexture);
  83168. if (_this._firstUpdate) {
  83169. effect.setArray("samplerOffsets", _this._samplerOffsets);
  83170. _this._firstUpdate = false;
  83171. }
  83172. };
  83173. this._blurHPostProcess.samples = this.textureSamples;
  83174. this._blurVPostProcess.samples = this.textureSamples;
  83175. };
  83176. /** @hidden */
  83177. SSAO2RenderingPipeline.prototype._rebuild = function () {
  83178. this._firstUpdate = true;
  83179. _super.prototype._rebuild.call(this);
  83180. };
  83181. //Van der Corput radical inverse
  83182. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  83183. this._bits[0] = i;
  83184. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  83185. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  83186. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  83187. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  83188. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  83189. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  83190. };
  83191. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  83192. return [i / n, this._radicalInverse_VdC(i)];
  83193. };
  83194. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  83195. var phi = v * 2.0 * Math.PI;
  83196. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  83197. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  83198. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  83199. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  83200. };
  83201. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  83202. var numSamples = this.samples;
  83203. var result = [];
  83204. var vector;
  83205. var i = 0;
  83206. while (i < numSamples) {
  83207. if (numSamples < 16) {
  83208. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  83209. }
  83210. else {
  83211. var rand = this._hammersley(i, numSamples);
  83212. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  83213. }
  83214. result.push(vector.x, vector.y, vector.z);
  83215. i++;
  83216. }
  83217. return result;
  83218. };
  83219. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  83220. var _this = this;
  83221. var numSamples = this.samples;
  83222. this._sampleSphere = this._generateHemisphere();
  83223. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  83224. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  83225. "base", "range", "projection", "near", "far", "texelSize",
  83226. "xViewport", "yViewport", "maxZ", "minZAspect"
  83227. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  83228. this._ssaoPostProcess.onApply = function (effect) {
  83229. if (_this._firstUpdate) {
  83230. effect.setArray3("sampleSphere", _this._sampleSphere);
  83231. effect.setFloat("randTextureTiles", 32.0);
  83232. }
  83233. if (!_this._scene.activeCamera) {
  83234. return;
  83235. }
  83236. effect.setFloat("samplesFactor", 1 / _this.samples);
  83237. effect.setFloat("totalStrength", _this.totalStrength);
  83238. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  83239. effect.setFloat("radius", _this.radius);
  83240. effect.setFloat("maxZ", _this.maxZ);
  83241. effect.setFloat("minZAspect", _this.minZAspect);
  83242. effect.setFloat("base", _this.base);
  83243. effect.setFloat("near", _this._scene.activeCamera.minZ);
  83244. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  83245. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  83246. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  83247. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  83248. effect.setTexture("textureSampler", _this._depthTexture);
  83249. effect.setTexture("normalSampler", _this._normalTexture);
  83250. effect.setTexture("randomSampler", _this._randomTexture);
  83251. };
  83252. this._ssaoPostProcess.samples = this.textureSamples;
  83253. };
  83254. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  83255. var _this = this;
  83256. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83257. this._ssaoCombinePostProcess.onApply = function (effect) {
  83258. var viewport = _this._scene.activeCamera.viewport;
  83259. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  83260. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  83261. };
  83262. this._ssaoCombinePostProcess.samples = this.textureSamples;
  83263. };
  83264. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  83265. var size = 128;
  83266. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83267. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  83268. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  83269. var context = this._randomTexture.getContext();
  83270. var rand = function (min, max) {
  83271. return Math.random() * (max - min) + min;
  83272. };
  83273. var randVector = BABYLON.Vector3.Zero();
  83274. for (var x = 0; x < size; x++) {
  83275. for (var y = 0; y < size; y++) {
  83276. randVector.x = rand(0.0, 1.0);
  83277. randVector.y = rand(0.0, 1.0);
  83278. randVector.z = 0.0;
  83279. randVector.normalize();
  83280. randVector.scaleInPlace(255);
  83281. randVector.x = Math.floor(randVector.x);
  83282. randVector.y = Math.floor(randVector.y);
  83283. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  83284. context.fillRect(x, y, 1, 1);
  83285. }
  83286. }
  83287. this._randomTexture.update(false);
  83288. };
  83289. /**
  83290. * Serialize the rendering pipeline (Used when exporting)
  83291. * @returns the serialized object
  83292. */
  83293. SSAO2RenderingPipeline.prototype.serialize = function () {
  83294. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83295. serializationObject.customType = "SSAO2RenderingPipeline";
  83296. return serializationObject;
  83297. };
  83298. /**
  83299. * Parse the serialized pipeline
  83300. * @param source Source pipeline.
  83301. * @param scene The scene to load the pipeline to.
  83302. * @param rootUrl The URL of the serialized pipeline.
  83303. * @returns An instantiated pipeline from the serialized object.
  83304. */
  83305. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  83306. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  83307. };
  83308. __decorate([
  83309. BABYLON.serialize()
  83310. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  83311. __decorate([
  83312. BABYLON.serialize()
  83313. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  83314. __decorate([
  83315. BABYLON.serialize()
  83316. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  83317. __decorate([
  83318. BABYLON.serialize("samples")
  83319. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  83320. __decorate([
  83321. BABYLON.serialize("textureSamples")
  83322. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  83323. __decorate([
  83324. BABYLON.serialize()
  83325. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  83326. __decorate([
  83327. BABYLON.serialize("expensiveBlur")
  83328. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  83329. __decorate([
  83330. BABYLON.serialize()
  83331. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  83332. __decorate([
  83333. BABYLON.serialize()
  83334. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  83335. return SSAO2RenderingPipeline;
  83336. }(BABYLON.PostProcessRenderPipeline));
  83337. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  83338. })(BABYLON || (BABYLON = {}));
  83339. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  83340. // BABYLON.JS Chromatic Aberration GLSL Shader
  83341. // Author: Olivier Guyot
  83342. // Separates very slightly R, G and B colors on the edges of the screen
  83343. // Inspired by Francois Tarlier & Martins Upitis
  83344. var BABYLON;
  83345. (function (BABYLON) {
  83346. var LensRenderingPipeline = /** @class */ (function (_super) {
  83347. __extends(LensRenderingPipeline, _super);
  83348. /**
  83349. * @constructor
  83350. *
  83351. * Effect parameters are as follow:
  83352. * {
  83353. * chromatic_aberration: number; // from 0 to x (1 for realism)
  83354. * edge_blur: number; // from 0 to x (1 for realism)
  83355. * distortion: number; // from 0 to x (1 for realism)
  83356. * grain_amount: number; // from 0 to 1
  83357. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  83358. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  83359. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  83360. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  83361. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  83362. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  83363. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  83364. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  83365. * }
  83366. * Note: if an effect parameter is unset, effect is disabled
  83367. *
  83368. * @param {string} name - The rendering pipeline name
  83369. * @param {object} parameters - An object containing all parameters (see above)
  83370. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  83371. * @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)
  83372. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  83373. */
  83374. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  83375. if (ratio === void 0) { ratio = 1.0; }
  83376. var _this = _super.call(this, scene.getEngine(), name) || this;
  83377. // Lens effects can be of the following:
  83378. // - chromatic aberration (slight shift of RGB colors)
  83379. // - blur on the edge of the lens
  83380. // - lens distortion
  83381. // - depth-of-field blur & highlights enhancing
  83382. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  83383. // - grain effect (noise or custom texture)
  83384. // Two additional texture samplers are needed:
  83385. // - depth map (for depth-of-field)
  83386. // - grain texture
  83387. /**
  83388. * The chromatic aberration PostProcess id in the pipeline
  83389. */
  83390. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  83391. /**
  83392. * The highlights enhancing PostProcess id in the pipeline
  83393. */
  83394. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  83395. /**
  83396. * The depth-of-field PostProcess id in the pipeline
  83397. */
  83398. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  83399. _this._scene = scene;
  83400. // Fetch texture samplers
  83401. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  83402. if (parameters.grain_texture) {
  83403. _this._grainTexture = parameters.grain_texture;
  83404. }
  83405. else {
  83406. _this._createGrainTexture();
  83407. }
  83408. // save parameters
  83409. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  83410. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  83411. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  83412. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  83413. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  83414. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  83415. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  83416. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  83417. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  83418. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  83419. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  83420. // Create effects
  83421. _this._createChromaticAberrationPostProcess(ratio);
  83422. _this._createHighlightsPostProcess(ratio);
  83423. _this._createDepthOfFieldPostProcess(ratio / 4);
  83424. // Set up pipeline
  83425. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  83426. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  83427. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  83428. if (_this._highlightsGain === -1) {
  83429. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  83430. }
  83431. // Finish
  83432. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83433. if (cameras) {
  83434. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83435. }
  83436. return _this;
  83437. }
  83438. // public methods (self explanatory)
  83439. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  83440. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  83441. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  83442. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  83443. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  83444. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  83445. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  83446. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  83447. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  83448. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  83449. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  83450. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  83451. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  83452. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  83453. };
  83454. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  83455. this._highlightsPostProcess.updateEffect();
  83456. };
  83457. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  83458. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  83459. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  83460. this._highlightsGain = amount;
  83461. };
  83462. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  83463. if (this._highlightsGain === -1) {
  83464. this._highlightsGain = 1.0;
  83465. }
  83466. this._highlightsThreshold = amount;
  83467. };
  83468. LensRenderingPipeline.prototype.disableHighlights = function () {
  83469. this._highlightsGain = -1;
  83470. };
  83471. /**
  83472. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  83473. */
  83474. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  83475. if (disableDepthRender === void 0) { disableDepthRender = false; }
  83476. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  83477. this._chromaticAberrationPostProcess = null;
  83478. this._highlightsPostProcess = null;
  83479. this._depthOfFieldPostProcess = null;
  83480. this._grainTexture.dispose();
  83481. if (disableDepthRender)
  83482. this._scene.disableDepthRenderer();
  83483. };
  83484. // colors shifting and distortion
  83485. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  83486. var _this = this;
  83487. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  83488. [], // samplers
  83489. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83490. this._chromaticAberrationPostProcess.onApply = function (effect) {
  83491. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  83492. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  83493. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  83494. effect.setFloat('radialIntensity', 1);
  83495. effect.setFloat2('direction', 17, 17);
  83496. effect.setFloat2('centerPosition', 0.5, 0.5);
  83497. };
  83498. };
  83499. // highlights enhancing
  83500. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  83501. var _this = this;
  83502. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  83503. [], // samplers
  83504. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  83505. this._highlightsPostProcess.onApply = function (effect) {
  83506. effect.setFloat('gain', _this._highlightsGain);
  83507. effect.setFloat('threshold', _this._highlightsThreshold);
  83508. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  83509. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  83510. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  83511. };
  83512. };
  83513. // colors shifting and distortion
  83514. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  83515. var _this = this;
  83516. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  83517. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  83518. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  83519. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83520. this._depthOfFieldPostProcess.onApply = function (effect) {
  83521. effect.setTexture("depthSampler", _this._depthTexture);
  83522. effect.setTexture("grainSampler", _this._grainTexture);
  83523. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  83524. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  83525. effect.setFloat('grain_amount', _this._grainAmount);
  83526. effect.setBool('blur_noise', _this._blurNoise);
  83527. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  83528. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  83529. effect.setFloat('distortion', _this._distortion);
  83530. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  83531. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  83532. effect.setFloat('aperture', _this._dofAperture);
  83533. effect.setFloat('darken', _this._dofDarken);
  83534. effect.setFloat('edge_blur', _this._edgeBlur);
  83535. effect.setBool('highlights', (_this._highlightsGain !== -1));
  83536. if (_this._scene.activeCamera) {
  83537. effect.setFloat('near', _this._scene.activeCamera.minZ);
  83538. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  83539. }
  83540. };
  83541. };
  83542. // creates a black and white random noise texture, 512x512
  83543. LensRenderingPipeline.prototype._createGrainTexture = function () {
  83544. var size = 512;
  83545. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83546. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  83547. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  83548. var context = this._grainTexture.getContext();
  83549. var rand = function (min, max) {
  83550. return Math.random() * (max - min) + min;
  83551. };
  83552. var value;
  83553. for (var x = 0; x < size; x++) {
  83554. for (var y = 0; y < size; y++) {
  83555. value = Math.floor(rand(0.42, 0.58) * 255);
  83556. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  83557. context.fillRect(x, y, 1, 1);
  83558. }
  83559. }
  83560. this._grainTexture.update(false);
  83561. };
  83562. return LensRenderingPipeline;
  83563. }(BABYLON.PostProcessRenderPipeline));
  83564. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  83565. })(BABYLON || (BABYLON = {}));
  83566. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  83567. var BABYLON;
  83568. (function (BABYLON) {
  83569. /**
  83570. * Standard rendering pipeline
  83571. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  83572. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  83573. */
  83574. var StandardRenderingPipeline = /** @class */ (function (_super) {
  83575. __extends(StandardRenderingPipeline, _super);
  83576. /**
  83577. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  83578. * @constructor
  83579. * @param {string} name - The rendering pipeline name
  83580. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  83581. * @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)
  83582. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  83583. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  83584. */
  83585. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  83586. if (originalPostProcess === void 0) { originalPostProcess = null; }
  83587. var _this = _super.call(this, scene.getEngine(), name) || this;
  83588. /**
  83589. * Post-process used to down scale an image x4
  83590. */
  83591. _this.downSampleX4PostProcess = null;
  83592. /**
  83593. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  83594. */
  83595. _this.brightPassPostProcess = null;
  83596. /**
  83597. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  83598. */
  83599. _this.blurHPostProcesses = [];
  83600. /**
  83601. * Post-process array storing all the vertical blur post-processes used by the pipeline
  83602. */
  83603. _this.blurVPostProcesses = [];
  83604. /**
  83605. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  83606. */
  83607. _this.textureAdderPostProcess = null;
  83608. /**
  83609. * Post-process used to create volumetric lighting effect
  83610. */
  83611. _this.volumetricLightPostProcess = null;
  83612. /**
  83613. * Post-process used to smooth the previous volumetric light post-process on the X axis
  83614. */
  83615. _this.volumetricLightSmoothXPostProcess = null;
  83616. /**
  83617. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  83618. */
  83619. _this.volumetricLightSmoothYPostProcess = null;
  83620. /**
  83621. * Post-process used to merge the volumetric light effect and the real scene color
  83622. */
  83623. _this.volumetricLightMergePostProces = null;
  83624. /**
  83625. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  83626. */
  83627. _this.volumetricLightFinalPostProcess = null;
  83628. /**
  83629. * Base post-process used to calculate the average luminance of the final image for HDR
  83630. */
  83631. _this.luminancePostProcess = null;
  83632. /**
  83633. * Post-processes used to create down sample post-processes in order to get
  83634. * the average luminance of the final image for HDR
  83635. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  83636. */
  83637. _this.luminanceDownSamplePostProcesses = [];
  83638. /**
  83639. * Post-process used to create a HDR effect (light adaptation)
  83640. */
  83641. _this.hdrPostProcess = null;
  83642. /**
  83643. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  83644. */
  83645. _this.textureAdderFinalPostProcess = null;
  83646. /**
  83647. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  83648. */
  83649. _this.lensFlareFinalPostProcess = null;
  83650. /**
  83651. * Post-process used to merge the final HDR post-process and the real scene color
  83652. */
  83653. _this.hdrFinalPostProcess = null;
  83654. /**
  83655. * Post-process used to create a lens flare effect
  83656. */
  83657. _this.lensFlarePostProcess = null;
  83658. /**
  83659. * Post-process that merges the result of the lens flare post-process and the real scene color
  83660. */
  83661. _this.lensFlareComposePostProcess = null;
  83662. /**
  83663. * Post-process used to create a motion blur effect
  83664. */
  83665. _this.motionBlurPostProcess = null;
  83666. /**
  83667. * Post-process used to create a depth of field effect
  83668. */
  83669. _this.depthOfFieldPostProcess = null;
  83670. /**
  83671. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  83672. */
  83673. _this.fxaaPostProcess = null;
  83674. // Values
  83675. /**
  83676. * Represents the brightness threshold in order to configure the illuminated surfaces
  83677. */
  83678. _this.brightThreshold = 1.0;
  83679. /**
  83680. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  83681. */
  83682. _this.blurWidth = 512.0;
  83683. /**
  83684. * Sets if the blur for highlighted surfaces must be only horizontal
  83685. */
  83686. _this.horizontalBlur = false;
  83687. /**
  83688. * Sets the overall exposure used by the pipeline
  83689. */
  83690. _this.exposure = 1.0;
  83691. /**
  83692. * Texture used typically to simulate "dirty" on camera lens
  83693. */
  83694. _this.lensTexture = null;
  83695. /**
  83696. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  83697. */
  83698. _this.volumetricLightCoefficient = 0.2;
  83699. /**
  83700. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  83701. */
  83702. _this.volumetricLightPower = 4.0;
  83703. /**
  83704. * Used the set the blur intensity to smooth the volumetric lights
  83705. */
  83706. _this.volumetricLightBlurScale = 64.0;
  83707. /**
  83708. * Light (spot or directional) used to generate the volumetric lights rays
  83709. * The source light must have a shadow generate so the pipeline can get its
  83710. * depth map
  83711. */
  83712. _this.sourceLight = null;
  83713. /**
  83714. * For eye adaptation, represents the minimum luminance the eye can see
  83715. */
  83716. _this.hdrMinimumLuminance = 1.0;
  83717. /**
  83718. * For eye adaptation, represents the decrease luminance speed
  83719. */
  83720. _this.hdrDecreaseRate = 0.5;
  83721. /**
  83722. * For eye adaptation, represents the increase luminance speed
  83723. */
  83724. _this.hdrIncreaseRate = 0.5;
  83725. /**
  83726. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  83727. */
  83728. _this.lensColorTexture = null;
  83729. /**
  83730. * The overall strengh for the lens flare effect
  83731. */
  83732. _this.lensFlareStrength = 20.0;
  83733. /**
  83734. * Dispersion coefficient for lens flare ghosts
  83735. */
  83736. _this.lensFlareGhostDispersal = 1.4;
  83737. /**
  83738. * Main lens flare halo width
  83739. */
  83740. _this.lensFlareHaloWidth = 0.7;
  83741. /**
  83742. * Based on the lens distortion effect, defines how much the lens flare result
  83743. * is distorted
  83744. */
  83745. _this.lensFlareDistortionStrength = 16.0;
  83746. /**
  83747. * Lens star texture must be used to simulate rays on the flares and is available
  83748. * in the documentation
  83749. */
  83750. _this.lensStarTexture = null;
  83751. /**
  83752. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  83753. * flare effect by taking account of the dirt texture
  83754. */
  83755. _this.lensFlareDirtTexture = null;
  83756. /**
  83757. * Represents the focal length for the depth of field effect
  83758. */
  83759. _this.depthOfFieldDistance = 10.0;
  83760. /**
  83761. * Represents the blur intensity for the blurred part of the depth of field effect
  83762. */
  83763. _this.depthOfFieldBlurWidth = 64.0;
  83764. /**
  83765. * For motion blur, defines how much the image is blurred by the movement
  83766. */
  83767. _this.motionStrength = 1.0;
  83768. /**
  83769. * List of animations for the pipeline (IAnimatable implementation)
  83770. */
  83771. _this.animations = [];
  83772. _this._currentDepthOfFieldSource = null;
  83773. _this._hdrCurrentLuminance = 1.0;
  83774. // Getters and setters
  83775. _this._bloomEnabled = false;
  83776. _this._depthOfFieldEnabled = false;
  83777. _this._vlsEnabled = false;
  83778. _this._lensFlareEnabled = false;
  83779. _this._hdrEnabled = false;
  83780. _this._motionBlurEnabled = false;
  83781. _this._fxaaEnabled = false;
  83782. _this._motionBlurSamples = 64.0;
  83783. _this._volumetricLightStepsCount = 50.0;
  83784. _this._samples = 1;
  83785. _this._cameras = cameras || [];
  83786. // Initialize
  83787. _this._scene = scene;
  83788. _this._basePostProcess = originalPostProcess;
  83789. _this._ratio = ratio;
  83790. // Misc
  83791. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83792. // Finish
  83793. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83794. _this._buildPipeline();
  83795. return _this;
  83796. }
  83797. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  83798. /**
  83799. * Specifies if the bloom pipeline is enabled
  83800. */
  83801. get: function () {
  83802. return this._bloomEnabled;
  83803. },
  83804. set: function (enabled) {
  83805. if (this._bloomEnabled === enabled) {
  83806. return;
  83807. }
  83808. this._bloomEnabled = enabled;
  83809. this._buildPipeline();
  83810. },
  83811. enumerable: true,
  83812. configurable: true
  83813. });
  83814. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  83815. /**
  83816. * Specifies if the depth of field pipeline is enabed
  83817. */
  83818. get: function () {
  83819. return this._depthOfFieldEnabled;
  83820. },
  83821. set: function (enabled) {
  83822. if (this._depthOfFieldEnabled === enabled) {
  83823. return;
  83824. }
  83825. this._depthOfFieldEnabled = enabled;
  83826. this._buildPipeline();
  83827. },
  83828. enumerable: true,
  83829. configurable: true
  83830. });
  83831. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  83832. /**
  83833. * Specifies if the lens flare pipeline is enabed
  83834. */
  83835. get: function () {
  83836. return this._lensFlareEnabled;
  83837. },
  83838. set: function (enabled) {
  83839. if (this._lensFlareEnabled === enabled) {
  83840. return;
  83841. }
  83842. this._lensFlareEnabled = enabled;
  83843. this._buildPipeline();
  83844. },
  83845. enumerable: true,
  83846. configurable: true
  83847. });
  83848. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  83849. /**
  83850. * Specifies if the HDR pipeline is enabled
  83851. */
  83852. get: function () {
  83853. return this._hdrEnabled;
  83854. },
  83855. set: function (enabled) {
  83856. if (this._hdrEnabled === enabled) {
  83857. return;
  83858. }
  83859. this._hdrEnabled = enabled;
  83860. this._buildPipeline();
  83861. },
  83862. enumerable: true,
  83863. configurable: true
  83864. });
  83865. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  83866. /**
  83867. * Specifies if the volumetric lights scattering effect is enabled
  83868. */
  83869. get: function () {
  83870. return this._vlsEnabled;
  83871. },
  83872. set: function (enabled) {
  83873. if (this._vlsEnabled === enabled) {
  83874. return;
  83875. }
  83876. if (enabled) {
  83877. var geometry = this._scene.enableGeometryBufferRenderer();
  83878. if (!geometry) {
  83879. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  83880. return;
  83881. }
  83882. }
  83883. this._vlsEnabled = enabled;
  83884. this._buildPipeline();
  83885. },
  83886. enumerable: true,
  83887. configurable: true
  83888. });
  83889. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  83890. /**
  83891. * Specifies if the motion blur effect is enabled
  83892. */
  83893. get: function () {
  83894. return this._motionBlurEnabled;
  83895. },
  83896. set: function (enabled) {
  83897. if (this._motionBlurEnabled === enabled) {
  83898. return;
  83899. }
  83900. this._motionBlurEnabled = enabled;
  83901. this._buildPipeline();
  83902. },
  83903. enumerable: true,
  83904. configurable: true
  83905. });
  83906. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  83907. /**
  83908. * Specifies if anti-aliasing is enabled
  83909. */
  83910. get: function () {
  83911. return this._fxaaEnabled;
  83912. },
  83913. set: function (enabled) {
  83914. if (this._fxaaEnabled === enabled) {
  83915. return;
  83916. }
  83917. this._fxaaEnabled = enabled;
  83918. this._buildPipeline();
  83919. },
  83920. enumerable: true,
  83921. configurable: true
  83922. });
  83923. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  83924. /**
  83925. * Specifies the number of steps used to calculate the volumetric lights
  83926. * Typically in interval [50, 200]
  83927. */
  83928. get: function () {
  83929. return this._volumetricLightStepsCount;
  83930. },
  83931. set: function (count) {
  83932. if (this.volumetricLightPostProcess) {
  83933. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  83934. }
  83935. this._volumetricLightStepsCount = count;
  83936. },
  83937. enumerable: true,
  83938. configurable: true
  83939. });
  83940. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  83941. /**
  83942. * Specifies the number of samples used for the motion blur effect
  83943. * Typically in interval [16, 64]
  83944. */
  83945. get: function () {
  83946. return this._motionBlurSamples;
  83947. },
  83948. set: function (samples) {
  83949. if (this.motionBlurPostProcess) {
  83950. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  83951. }
  83952. this._motionBlurSamples = samples;
  83953. },
  83954. enumerable: true,
  83955. configurable: true
  83956. });
  83957. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  83958. /**
  83959. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  83960. */
  83961. get: function () {
  83962. return this._samples;
  83963. },
  83964. set: function (sampleCount) {
  83965. if (this._samples === sampleCount) {
  83966. return;
  83967. }
  83968. this._samples = sampleCount;
  83969. this._buildPipeline();
  83970. },
  83971. enumerable: true,
  83972. configurable: true
  83973. });
  83974. StandardRenderingPipeline.prototype._buildPipeline = function () {
  83975. var _this = this;
  83976. var ratio = this._ratio;
  83977. var scene = this._scene;
  83978. this._disposePostProcesses();
  83979. this._reset();
  83980. // Create pass post-process
  83981. if (!this._basePostProcess) {
  83982. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  83983. this.originalPostProcess.onApply = function (effect) {
  83984. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  83985. };
  83986. }
  83987. else {
  83988. this.originalPostProcess = this._basePostProcess;
  83989. }
  83990. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  83991. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  83992. }
  83993. this._currentDepthOfFieldSource = this.originalPostProcess;
  83994. if (this._bloomEnabled) {
  83995. // Create down sample X4 post-process
  83996. this._createDownSampleX4PostProcess(scene, ratio / 2);
  83997. // Create bright pass post-process
  83998. this._createBrightPassPostProcess(scene, ratio / 2);
  83999. // Create gaussian blur post-processes (down sampling blurs)
  84000. this._createBlurPostProcesses(scene, ratio / 4, 1);
  84001. // Create texture adder post-process
  84002. this._createTextureAdderPostProcess(scene, ratio);
  84003. // Create depth-of-field source post-process
  84004. 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);
  84005. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  84006. }
  84007. if (this._vlsEnabled) {
  84008. // Create volumetric light
  84009. this._createVolumetricLightPostProcess(scene, ratio);
  84010. // Create volumetric light final post-process
  84011. 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);
  84012. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  84013. }
  84014. if (this._lensFlareEnabled) {
  84015. // Create lens flare post-process
  84016. this._createLensFlarePostProcess(scene, ratio);
  84017. // Create depth-of-field source post-process post lens-flare and disable it now
  84018. 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);
  84019. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  84020. }
  84021. if (this._hdrEnabled) {
  84022. // Create luminance
  84023. this._createLuminancePostProcesses(scene, this._floatTextureType);
  84024. // Create HDR
  84025. this._createHdrPostProcess(scene, ratio);
  84026. // Create depth-of-field source post-process post hdr and disable it now
  84027. 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);
  84028. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  84029. }
  84030. if (this._depthOfFieldEnabled) {
  84031. // Create gaussian blur used by depth-of-field
  84032. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  84033. // Create depth-of-field post-process
  84034. this._createDepthOfFieldPostProcess(scene, ratio);
  84035. }
  84036. if (this._motionBlurEnabled) {
  84037. // Create motion blur post-process
  84038. this._createMotionBlurPostProcess(scene, ratio);
  84039. }
  84040. if (this._fxaaEnabled) {
  84041. // Create fxaa post-process
  84042. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  84044. }
  84045. if (this._cameras !== null) {
  84046. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  84047. }
  84048. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  84049. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  84050. }
  84051. };
  84052. // Down Sample X4 Post-Processs
  84053. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  84054. var _this = this;
  84055. var downSampleX4Offsets = new Array(32);
  84056. 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);
  84057. this.downSampleX4PostProcess.onApply = function (effect) {
  84058. var id = 0;
  84059. var width = _this.downSampleX4PostProcess.width;
  84060. var height = _this.downSampleX4PostProcess.height;
  84061. for (var i = -2; i < 2; i++) {
  84062. for (var j = -2; j < 2; j++) {
  84063. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  84064. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  84065. id += 2;
  84066. }
  84067. }
  84068. effect.setArray2("dsOffsets", downSampleX4Offsets);
  84069. };
  84070. // Add to pipeline
  84071. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  84072. };
  84073. // Brightpass Post-Process
  84074. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  84075. var _this = this;
  84076. var brightOffsets = new Array(8);
  84077. 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);
  84078. this.brightPassPostProcess.onApply = function (effect) {
  84079. var sU = (1.0 / _this.brightPassPostProcess.width);
  84080. var sV = (1.0 / _this.brightPassPostProcess.height);
  84081. brightOffsets[0] = -0.5 * sU;
  84082. brightOffsets[1] = 0.5 * sV;
  84083. brightOffsets[2] = 0.5 * sU;
  84084. brightOffsets[3] = 0.5 * sV;
  84085. brightOffsets[4] = -0.5 * sU;
  84086. brightOffsets[5] = -0.5 * sV;
  84087. brightOffsets[6] = 0.5 * sU;
  84088. brightOffsets[7] = -0.5 * sV;
  84089. effect.setArray2("dsOffsets", brightOffsets);
  84090. effect.setFloat("brightThreshold", _this.brightThreshold);
  84091. };
  84092. // Add to pipeline
  84093. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  84094. };
  84095. // Create blur H&V post-processes
  84096. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  84097. var _this = this;
  84098. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  84099. var engine = scene.getEngine();
  84100. 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);
  84101. 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);
  84102. blurX.onActivateObservable.add(function () {
  84103. var dw = blurX.width / engine.getRenderWidth();
  84104. blurX.kernel = _this[blurWidthKey] * dw;
  84105. });
  84106. blurY.onActivateObservable.add(function () {
  84107. var dw = blurY.height / engine.getRenderHeight();
  84108. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  84109. });
  84110. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  84111. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  84112. this.blurHPostProcesses.push(blurX);
  84113. this.blurVPostProcesses.push(blurY);
  84114. };
  84115. // Create texture adder post-process
  84116. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  84117. var _this = this;
  84118. 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);
  84119. this.textureAdderPostProcess.onApply = function (effect) {
  84120. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  84121. effect.setTexture("lensSampler", _this.lensTexture);
  84122. effect.setFloat("exposure", _this.exposure);
  84123. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  84124. };
  84125. // Add to pipeline
  84126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  84127. };
  84128. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  84129. var _this = this;
  84130. var geometryRenderer = scene.enableGeometryBufferRenderer();
  84131. geometryRenderer.enablePosition = true;
  84132. var geometry = geometryRenderer.getGBuffer();
  84133. // Base post-process
  84134. 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));
  84135. var depthValues = BABYLON.Vector2.Zero();
  84136. this.volumetricLightPostProcess.onApply = function (effect) {
  84137. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  84138. var generator = _this.sourceLight.getShadowGenerator();
  84139. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  84140. effect.setTexture("positionSampler", geometry.textures[2]);
  84141. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  84142. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  84143. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  84144. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  84145. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  84146. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  84147. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  84148. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  84149. effect.setVector2("depthValues", depthValues);
  84150. }
  84151. };
  84152. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  84153. // Smooth
  84154. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  84155. // Merge
  84156. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  84157. this.volumetricLightMergePostProces.onApply = function (effect) {
  84158. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  84159. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  84160. };
  84161. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  84162. };
  84163. // Create luminance
  84164. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  84165. var _this = this;
  84166. // Create luminance
  84167. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  84168. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  84169. var offsets = [];
  84170. this.luminancePostProcess.onApply = function (effect) {
  84171. var sU = (1.0 / _this.luminancePostProcess.width);
  84172. var sV = (1.0 / _this.luminancePostProcess.height);
  84173. offsets[0] = -0.5 * sU;
  84174. offsets[1] = 0.5 * sV;
  84175. offsets[2] = 0.5 * sU;
  84176. offsets[3] = 0.5 * sV;
  84177. offsets[4] = -0.5 * sU;
  84178. offsets[5] = -0.5 * sV;
  84179. offsets[6] = 0.5 * sU;
  84180. offsets[7] = -0.5 * sV;
  84181. effect.setArray2("lumOffsets", offsets);
  84182. };
  84183. // Add to pipeline
  84184. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  84185. // Create down sample luminance
  84186. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  84187. var size = Math.pow(3, i);
  84188. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  84189. if (i === 0) {
  84190. defines += "#define FINAL_DOWN_SAMPLER";
  84191. }
  84192. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  84193. this.luminanceDownSamplePostProcesses.push(postProcess);
  84194. }
  84195. // Create callbacks and add effects
  84196. var lastLuminance = this.luminancePostProcess;
  84197. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  84198. var downSampleOffsets = new Array(18);
  84199. pp.onApply = function (effect) {
  84200. if (!lastLuminance) {
  84201. return;
  84202. }
  84203. var id = 0;
  84204. for (var x = -1; x < 2; x++) {
  84205. for (var y = -1; y < 2; y++) {
  84206. downSampleOffsets[id] = x / lastLuminance.width;
  84207. downSampleOffsets[id + 1] = y / lastLuminance.height;
  84208. id += 2;
  84209. }
  84210. }
  84211. effect.setArray2("dsOffsets", downSampleOffsets);
  84212. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  84213. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  84214. lastLuminance = _this.luminancePostProcess;
  84215. }
  84216. else {
  84217. lastLuminance = pp;
  84218. }
  84219. };
  84220. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  84221. pp.onAfterRender = function (effect) {
  84222. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  84223. 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);
  84224. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  84225. };
  84226. }
  84227. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  84228. });
  84229. };
  84230. // Create HDR post-process
  84231. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  84232. var _this = this;
  84233. 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);
  84234. var outputLiminance = 1;
  84235. var time = 0;
  84236. var lastTime = 0;
  84237. this.hdrPostProcess.onApply = function (effect) {
  84238. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  84239. time += scene.getEngine().getDeltaTime();
  84240. if (outputLiminance < 0) {
  84241. outputLiminance = _this._hdrCurrentLuminance;
  84242. }
  84243. else {
  84244. var dt = (lastTime - time) / 1000.0;
  84245. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  84246. outputLiminance += _this.hdrDecreaseRate * dt;
  84247. }
  84248. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  84249. outputLiminance -= _this.hdrIncreaseRate * dt;
  84250. }
  84251. else {
  84252. outputLiminance = _this._hdrCurrentLuminance;
  84253. }
  84254. }
  84255. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  84256. effect.setFloat("averageLuminance", outputLiminance);
  84257. lastTime = time;
  84258. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  84259. };
  84260. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  84261. };
  84262. // Create lens flare post-process
  84263. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  84264. var _this = this;
  84265. 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);
  84266. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  84267. this._createBlurPostProcesses(scene, ratio / 4, 2);
  84268. 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);
  84269. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  84270. var resolution = new BABYLON.Vector2(0, 0);
  84271. // Lens flare
  84272. this.lensFlarePostProcess.onApply = function (effect) {
  84273. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  84274. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  84275. effect.setFloat("strength", _this.lensFlareStrength);
  84276. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  84277. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  84278. // Shift
  84279. resolution.x = _this.lensFlarePostProcess.width;
  84280. resolution.y = _this.lensFlarePostProcess.height;
  84281. effect.setVector2("resolution", resolution);
  84282. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  84283. };
  84284. // Compose
  84285. 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);
  84286. 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);
  84287. this.lensFlareComposePostProcess.onApply = function (effect) {
  84288. if (!_this._scene.activeCamera) {
  84289. return;
  84290. }
  84291. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  84292. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  84293. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  84294. // Lens start rotation matrix
  84295. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  84296. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  84297. 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));
  84298. camRot *= 4.0;
  84299. 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);
  84300. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  84301. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  84302. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  84303. };
  84304. };
  84305. // Create depth-of-field post-process
  84306. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  84307. var _this = this;
  84308. 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);
  84309. this.depthOfFieldPostProcess.onApply = function (effect) {
  84310. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  84311. effect.setTexture("depthSampler", _this._getDepthTexture());
  84312. effect.setFloat("distance", _this.depthOfFieldDistance);
  84313. };
  84314. // Add to pipeline
  84315. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  84316. };
  84317. // Create motion blur post-process
  84318. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  84319. var _this = this;
  84320. 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);
  84321. var motionScale = 0;
  84322. var prevViewProjection = BABYLON.Matrix.Identity();
  84323. var invViewProjection = BABYLON.Matrix.Identity();
  84324. var viewProjection = BABYLON.Matrix.Identity();
  84325. var screenSize = BABYLON.Vector2.Zero();
  84326. this.motionBlurPostProcess.onApply = function (effect) {
  84327. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  84328. viewProjection.invertToRef(invViewProjection);
  84329. effect.setMatrix("inverseViewProjection", invViewProjection);
  84330. effect.setMatrix("prevViewProjection", prevViewProjection);
  84331. prevViewProjection = viewProjection;
  84332. screenSize.x = _this.motionBlurPostProcess.width;
  84333. screenSize.y = _this.motionBlurPostProcess.height;
  84334. effect.setVector2("screenSize", screenSize);
  84335. motionScale = scene.getEngine().getFps() / 60.0;
  84336. effect.setFloat("motionScale", motionScale);
  84337. effect.setFloat("motionStrength", _this.motionStrength);
  84338. effect.setTexture("depthSampler", _this._getDepthTexture());
  84339. };
  84340. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  84341. };
  84342. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  84343. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  84344. var renderer = this._scene.enableGeometryBufferRenderer();
  84345. return renderer.getGBuffer().textures[0];
  84346. }
  84347. return this._scene.enableDepthRenderer().getDepthMap();
  84348. };
  84349. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  84350. for (var i = 0; i < this._cameras.length; i++) {
  84351. var camera = this._cameras[i];
  84352. if (this.originalPostProcess) {
  84353. this.originalPostProcess.dispose(camera);
  84354. }
  84355. if (this.downSampleX4PostProcess) {
  84356. this.downSampleX4PostProcess.dispose(camera);
  84357. }
  84358. if (this.brightPassPostProcess) {
  84359. this.brightPassPostProcess.dispose(camera);
  84360. }
  84361. if (this.textureAdderPostProcess) {
  84362. this.textureAdderPostProcess.dispose(camera);
  84363. }
  84364. if (this.textureAdderFinalPostProcess) {
  84365. this.textureAdderFinalPostProcess.dispose(camera);
  84366. }
  84367. if (this.volumetricLightPostProcess) {
  84368. this.volumetricLightPostProcess.dispose(camera);
  84369. }
  84370. if (this.volumetricLightSmoothXPostProcess) {
  84371. this.volumetricLightSmoothXPostProcess.dispose(camera);
  84372. }
  84373. if (this.volumetricLightSmoothYPostProcess) {
  84374. this.volumetricLightSmoothYPostProcess.dispose(camera);
  84375. }
  84376. if (this.volumetricLightMergePostProces) {
  84377. this.volumetricLightMergePostProces.dispose(camera);
  84378. }
  84379. if (this.volumetricLightFinalPostProcess) {
  84380. this.volumetricLightFinalPostProcess.dispose(camera);
  84381. }
  84382. if (this.lensFlarePostProcess) {
  84383. this.lensFlarePostProcess.dispose(camera);
  84384. }
  84385. if (this.lensFlareComposePostProcess) {
  84386. this.lensFlareComposePostProcess.dispose(camera);
  84387. }
  84388. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  84389. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  84390. }
  84391. if (this.luminancePostProcess) {
  84392. this.luminancePostProcess.dispose(camera);
  84393. }
  84394. if (this.hdrPostProcess) {
  84395. this.hdrPostProcess.dispose(camera);
  84396. }
  84397. if (this.hdrFinalPostProcess) {
  84398. this.hdrFinalPostProcess.dispose(camera);
  84399. }
  84400. if (this.depthOfFieldPostProcess) {
  84401. this.depthOfFieldPostProcess.dispose(camera);
  84402. }
  84403. if (this.motionBlurPostProcess) {
  84404. this.motionBlurPostProcess.dispose(camera);
  84405. }
  84406. if (this.fxaaPostProcess) {
  84407. this.fxaaPostProcess.dispose(camera);
  84408. }
  84409. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  84410. this.blurHPostProcesses[j].dispose(camera);
  84411. }
  84412. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  84413. this.blurVPostProcesses[j].dispose(camera);
  84414. }
  84415. }
  84416. this.originalPostProcess = null;
  84417. this.downSampleX4PostProcess = null;
  84418. this.brightPassPostProcess = null;
  84419. this.textureAdderPostProcess = null;
  84420. this.textureAdderFinalPostProcess = null;
  84421. this.volumetricLightPostProcess = null;
  84422. this.volumetricLightSmoothXPostProcess = null;
  84423. this.volumetricLightSmoothYPostProcess = null;
  84424. this.volumetricLightMergePostProces = null;
  84425. this.volumetricLightFinalPostProcess = null;
  84426. this.lensFlarePostProcess = null;
  84427. this.lensFlareComposePostProcess = null;
  84428. this.luminancePostProcess = null;
  84429. this.hdrPostProcess = null;
  84430. this.hdrFinalPostProcess = null;
  84431. this.depthOfFieldPostProcess = null;
  84432. this.motionBlurPostProcess = null;
  84433. this.fxaaPostProcess = null;
  84434. this.luminanceDownSamplePostProcesses = [];
  84435. this.blurHPostProcesses = [];
  84436. this.blurVPostProcesses = [];
  84437. };
  84438. /**
  84439. * Dispose of the pipeline and stop all post processes
  84440. */
  84441. StandardRenderingPipeline.prototype.dispose = function () {
  84442. this._disposePostProcesses();
  84443. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84444. _super.prototype.dispose.call(this);
  84445. };
  84446. /**
  84447. * Serialize the rendering pipeline (Used when exporting)
  84448. * @returns the serialized object
  84449. */
  84450. StandardRenderingPipeline.prototype.serialize = function () {
  84451. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84452. if (this.sourceLight) {
  84453. serializationObject.sourceLightId = this.sourceLight.id;
  84454. }
  84455. serializationObject.customType = "StandardRenderingPipeline";
  84456. return serializationObject;
  84457. };
  84458. /**
  84459. * Parse the serialized pipeline
  84460. * @param source Source pipeline.
  84461. * @param scene The scene to load the pipeline to.
  84462. * @param rootUrl The URL of the serialized pipeline.
  84463. * @returns An instantiated pipeline from the serialized object.
  84464. */
  84465. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  84466. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  84467. if (source.sourceLightId) {
  84468. p.sourceLight = scene.getLightByID(source.sourceLightId);
  84469. }
  84470. return p;
  84471. };
  84472. // Luminance steps
  84473. StandardRenderingPipeline.LuminanceSteps = 6;
  84474. __decorate([
  84475. BABYLON.serialize()
  84476. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  84477. __decorate([
  84478. BABYLON.serialize()
  84479. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  84480. __decorate([
  84481. BABYLON.serialize()
  84482. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  84483. __decorate([
  84484. BABYLON.serialize()
  84485. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  84486. __decorate([
  84487. BABYLON.serializeAsTexture("lensTexture")
  84488. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  84489. __decorate([
  84490. BABYLON.serialize()
  84491. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  84492. __decorate([
  84493. BABYLON.serialize()
  84494. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  84495. __decorate([
  84496. BABYLON.serialize()
  84497. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  84498. __decorate([
  84499. BABYLON.serialize()
  84500. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  84501. __decorate([
  84502. BABYLON.serialize()
  84503. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  84504. __decorate([
  84505. BABYLON.serialize()
  84506. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  84507. __decorate([
  84508. BABYLON.serializeAsTexture("lensColorTexture")
  84509. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  84510. __decorate([
  84511. BABYLON.serialize()
  84512. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  84513. __decorate([
  84514. BABYLON.serialize()
  84515. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  84516. __decorate([
  84517. BABYLON.serialize()
  84518. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  84519. __decorate([
  84520. BABYLON.serialize()
  84521. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  84522. __decorate([
  84523. BABYLON.serializeAsTexture("lensStarTexture")
  84524. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  84525. __decorate([
  84526. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  84527. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  84528. __decorate([
  84529. BABYLON.serialize()
  84530. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  84531. __decorate([
  84532. BABYLON.serialize()
  84533. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  84534. __decorate([
  84535. BABYLON.serialize()
  84536. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  84537. __decorate([
  84538. BABYLON.serialize()
  84539. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  84540. __decorate([
  84541. BABYLON.serialize()
  84542. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  84543. __decorate([
  84544. BABYLON.serialize()
  84545. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  84546. __decorate([
  84547. BABYLON.serialize()
  84548. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  84549. __decorate([
  84550. BABYLON.serialize()
  84551. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  84552. __decorate([
  84553. BABYLON.serialize()
  84554. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  84555. __decorate([
  84556. BABYLON.serialize()
  84557. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  84558. __decorate([
  84559. BABYLON.serialize()
  84560. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  84561. __decorate([
  84562. BABYLON.serialize()
  84563. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  84564. __decorate([
  84565. BABYLON.serialize()
  84566. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  84567. __decorate([
  84568. BABYLON.serialize()
  84569. ], StandardRenderingPipeline.prototype, "samples", null);
  84570. return StandardRenderingPipeline;
  84571. }(BABYLON.PostProcessRenderPipeline));
  84572. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  84573. })(BABYLON || (BABYLON = {}));
  84574. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  84575. var BABYLON;
  84576. (function (BABYLON) {
  84577. var FxaaPostProcess = /** @class */ (function (_super) {
  84578. __extends(FxaaPostProcess, _super);
  84579. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  84580. if (camera === void 0) { camera = null; }
  84581. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84582. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  84583. var defines = _this._getDefines();
  84584. _this.updateEffect(defines);
  84585. _this.onApplyObservable.add(function (effect) {
  84586. var texelSize = _this.texelSize;
  84587. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  84588. });
  84589. return _this;
  84590. }
  84591. FxaaPostProcess.prototype._getDefines = function () {
  84592. var engine = this.getEngine();
  84593. if (!engine) {
  84594. return null;
  84595. }
  84596. var glInfo = engine.getGlInfo();
  84597. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  84598. return "#define MALI 1\n";
  84599. }
  84600. return null;
  84601. };
  84602. return FxaaPostProcess;
  84603. }(BABYLON.PostProcess));
  84604. BABYLON.FxaaPostProcess = FxaaPostProcess;
  84605. })(BABYLON || (BABYLON = {}));
  84606. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  84607. var BABYLON;
  84608. (function (BABYLON) {
  84609. /**
  84610. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  84611. */
  84612. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  84613. __extends(ChromaticAberrationPostProcess, _super);
  84614. /**
  84615. * Creates a new instance ChromaticAberrationPostProcess
  84616. * @param name The name of the effect.
  84617. * @param screenWidth The width of the screen to apply the effect on.
  84618. * @param screenHeight The height of the screen to apply the effect on.
  84619. * @param options The required width/height ratio to downsize to before computing the render pass.
  84620. * @param camera The camera to apply the render pass to.
  84621. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84622. * @param engine The engine which the post process will be applied. (default: current engine)
  84623. * @param reusable If the post process can be reused on the same frame. (default: false)
  84624. * @param textureType Type of textures used when performing the post process. (default: 0)
  84625. * @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)
  84626. */
  84627. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84628. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84629. if (blockCompilation === void 0) { blockCompilation = false; }
  84630. 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;
  84631. /**
  84632. * The amount of seperation of rgb channels (default: 30)
  84633. */
  84634. _this.aberrationAmount = 30;
  84635. /**
  84636. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  84637. */
  84638. _this.radialIntensity = 0;
  84639. /**
  84640. * 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))
  84641. */
  84642. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  84643. /**
  84644. * 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))
  84645. */
  84646. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  84647. _this.onApplyObservable.add(function (effect) {
  84648. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  84649. effect.setFloat('screen_width', screenWidth);
  84650. effect.setFloat('screen_height', screenHeight);
  84651. effect.setFloat('radialIntensity', _this.radialIntensity);
  84652. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  84653. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  84654. });
  84655. return _this;
  84656. }
  84657. return ChromaticAberrationPostProcess;
  84658. }(BABYLON.PostProcess));
  84659. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  84660. })(BABYLON || (BABYLON = {}));
  84661. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  84662. var BABYLON;
  84663. (function (BABYLON) {
  84664. /**
  84665. * The GrainPostProcess adds noise to the image at mid luminance levels
  84666. */
  84667. var GrainPostProcess = /** @class */ (function (_super) {
  84668. __extends(GrainPostProcess, _super);
  84669. /**
  84670. * Creates a new instance of @see GrainPostProcess
  84671. * @param name The name of the effect.
  84672. * @param options The required width/height ratio to downsize to before computing the render pass.
  84673. * @param camera The camera to apply the render pass to.
  84674. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84675. * @param engine The engine which the post process will be applied. (default: current engine)
  84676. * @param reusable If the post process can be reused on the same frame. (default: false)
  84677. * @param textureType Type of textures used when performing the post process. (default: 0)
  84678. * @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)
  84679. */
  84680. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84681. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84682. if (blockCompilation === void 0) { blockCompilation = false; }
  84683. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84684. /**
  84685. * The intensity of the grain added (default: 30)
  84686. */
  84687. _this.intensity = 30;
  84688. /**
  84689. * If the grain should be randomized on every frame
  84690. */
  84691. _this.animated = false;
  84692. _this.onApplyObservable.add(function (effect) {
  84693. effect.setFloat('intensity', _this.intensity);
  84694. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  84695. });
  84696. return _this;
  84697. }
  84698. return GrainPostProcess;
  84699. }(BABYLON.PostProcess));
  84700. BABYLON.GrainPostProcess = GrainPostProcess;
  84701. })(BABYLON || (BABYLON = {}));
  84702. //# sourceMappingURL=babylon.grainPostProcess.js.map
  84703. var BABYLON;
  84704. (function (BABYLON) {
  84705. /**
  84706. * The SharpenPostProcess applies a sharpen kernel to every pixel
  84707. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  84708. */
  84709. var SharpenPostProcess = /** @class */ (function (_super) {
  84710. __extends(SharpenPostProcess, _super);
  84711. /**
  84712. * Creates a new instance ConvolutionPostProcess
  84713. * @param name The name of the effect.
  84714. * @param options The required width/height ratio to downsize to before computing the render pass.
  84715. * @param camera The camera to apply the render pass to.
  84716. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84717. * @param engine The engine which the post process will be applied. (default: current engine)
  84718. * @param reusable If the post process can be reused on the same frame. (default: false)
  84719. * @param textureType Type of textures used when performing the post process. (default: 0)
  84720. * @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)
  84721. */
  84722. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84723. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84724. if (blockCompilation === void 0) { blockCompilation = false; }
  84725. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84726. /**
  84727. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  84728. */
  84729. _this.colorAmount = 1.0;
  84730. /**
  84731. * How much sharpness should be applied (default: 0.3)
  84732. */
  84733. _this.edgeAmount = 0.3;
  84734. _this.onApply = function (effect) {
  84735. effect.setFloat2("screenSize", _this.width, _this.height);
  84736. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  84737. };
  84738. return _this;
  84739. }
  84740. return SharpenPostProcess;
  84741. }(BABYLON.PostProcess));
  84742. BABYLON.SharpenPostProcess = SharpenPostProcess;
  84743. })(BABYLON || (BABYLON = {}));
  84744. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  84745. var BABYLON;
  84746. (function (BABYLON) {
  84747. /**
  84748. * The Blur Post Process which blurs an image based on a kernel and direction.
  84749. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  84750. */
  84751. var BlurPostProcess = /** @class */ (function (_super) {
  84752. __extends(BlurPostProcess, _super);
  84753. /**
  84754. * Creates a new instance BlurPostProcess
  84755. * @param name The name of the effect.
  84756. * @param direction The direction in which to blur the image.
  84757. * @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.
  84758. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  84759. * @param camera The camera to apply the render pass to.
  84760. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84761. * @param engine The engine which the post process will be applied. (default: current engine)
  84762. * @param reusable If the post process can be reused on the same frame. (default: false)
  84763. * @param textureType Type of textures used when performing the post process. (default: 0)
  84764. * @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)
  84765. */
  84766. function BlurPostProcess(name,
  84767. /** The direction in which to blur the image. */
  84768. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  84769. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84770. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84771. if (defines === void 0) { defines = ""; }
  84772. if (blockCompilation === void 0) { blockCompilation = false; }
  84773. 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;
  84774. _this.direction = direction;
  84775. _this.blockCompilation = blockCompilation;
  84776. _this._packedFloat = false;
  84777. _this._staticDefines = "";
  84778. _this._staticDefines = defines;
  84779. _this.onApplyObservable.add(function (effect) {
  84780. if (_this._outputTexture) {
  84781. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  84782. }
  84783. else {
  84784. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  84785. }
  84786. });
  84787. _this.kernel = kernel;
  84788. return _this;
  84789. }
  84790. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  84791. /**
  84792. * Gets the length in pixels of the blur sample region
  84793. */
  84794. get: function () {
  84795. return this._idealKernel;
  84796. },
  84797. /**
  84798. * Sets the length in pixels of the blur sample region
  84799. */
  84800. set: function (v) {
  84801. if (this._idealKernel === v) {
  84802. return;
  84803. }
  84804. v = Math.max(v, 1);
  84805. this._idealKernel = v;
  84806. this._kernel = this._nearestBestKernel(v);
  84807. if (!this.blockCompilation) {
  84808. this._updateParameters();
  84809. }
  84810. },
  84811. enumerable: true,
  84812. configurable: true
  84813. });
  84814. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  84815. /**
  84816. * Gets wether or not the blur is unpacking/repacking floats
  84817. */
  84818. get: function () {
  84819. return this._packedFloat;
  84820. },
  84821. /**
  84822. * Sets wether or not the blur needs to unpack/repack floats
  84823. */
  84824. set: function (v) {
  84825. if (this._packedFloat === v) {
  84826. return;
  84827. }
  84828. this._packedFloat = v;
  84829. if (!this.blockCompilation) {
  84830. this._updateParameters();
  84831. }
  84832. },
  84833. enumerable: true,
  84834. configurable: true
  84835. });
  84836. /**
  84837. * Updates the effect with the current post process compile time values and recompiles the shader.
  84838. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  84839. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  84840. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  84841. * @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
  84842. * @param onCompiled Called when the shader has been compiled.
  84843. * @param onError Called if there is an error when compiling a shader.
  84844. */
  84845. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  84846. if (defines === void 0) { defines = null; }
  84847. if (uniforms === void 0) { uniforms = null; }
  84848. if (samplers === void 0) { samplers = null; }
  84849. this._updateParameters(onCompiled, onError);
  84850. };
  84851. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  84852. // Generate sampling offsets and weights
  84853. var N = this._kernel;
  84854. var centerIndex = (N - 1) / 2;
  84855. // Generate Gaussian sampling weights over kernel
  84856. var offsets = [];
  84857. var weights = [];
  84858. var totalWeight = 0;
  84859. for (var i = 0; i < N; i++) {
  84860. var u = i / (N - 1);
  84861. var w = this._gaussianWeight(u * 2.0 - 1);
  84862. offsets[i] = (i - centerIndex);
  84863. weights[i] = w;
  84864. totalWeight += w;
  84865. }
  84866. // Normalize weights
  84867. for (var i = 0; i < weights.length; i++) {
  84868. weights[i] /= totalWeight;
  84869. }
  84870. // Optimize: combine samples to take advantage of hardware linear sampling
  84871. // Walk from left to center, combining pairs (symmetrically)
  84872. var linearSamplingWeights = [];
  84873. var linearSamplingOffsets = [];
  84874. var linearSamplingMap = [];
  84875. for (var i = 0; i <= centerIndex; i += 2) {
  84876. var j = Math.min(i + 1, Math.floor(centerIndex));
  84877. var singleCenterSample = i === j;
  84878. if (singleCenterSample) {
  84879. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  84880. }
  84881. else {
  84882. var sharedCell = j === centerIndex;
  84883. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  84884. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  84885. if (offsetLinear === 0) {
  84886. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  84887. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  84888. }
  84889. else {
  84890. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  84891. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  84892. }
  84893. }
  84894. }
  84895. for (var i = 0; i < linearSamplingMap.length; i++) {
  84896. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  84897. linearSamplingWeights[i] = linearSamplingMap[i].w;
  84898. }
  84899. // Replace with optimized
  84900. offsets = linearSamplingOffsets;
  84901. weights = linearSamplingWeights;
  84902. // Generate shaders
  84903. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  84904. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  84905. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  84906. var defines = "";
  84907. defines += this._staticDefines;
  84908. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  84909. if (this._staticDefines.indexOf("DOF") != -1) {
  84910. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  84911. varyingCount--;
  84912. }
  84913. for (var i = 0; i < varyingCount; i++) {
  84914. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  84915. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  84916. }
  84917. var depCount = 0;
  84918. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  84919. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  84920. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  84921. depCount++;
  84922. }
  84923. if (this.packedFloat) {
  84924. defines += "#define PACKEDFLOAT 1";
  84925. }
  84926. this.blockCompilation = false;
  84927. _super.prototype.updateEffect.call(this, defines, null, null, {
  84928. varyingCount: varyingCount,
  84929. depCount: depCount
  84930. }, onCompiled, onError);
  84931. };
  84932. /**
  84933. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  84934. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  84935. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  84936. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  84937. * The gaps between physical kernels are compensated for in the weighting of the samples
  84938. * @param idealKernel Ideal blur kernel.
  84939. * @return Nearest best kernel.
  84940. */
  84941. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  84942. var v = Math.round(idealKernel);
  84943. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  84944. var k = _a[_i];
  84945. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  84946. return Math.max(k, 3);
  84947. }
  84948. }
  84949. return Math.max(v, 3);
  84950. };
  84951. /**
  84952. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  84953. * @param x The point on the Gaussian distribution to sample.
  84954. * @return the value of the Gaussian function at x.
  84955. */
  84956. BlurPostProcess.prototype._gaussianWeight = function (x) {
  84957. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  84958. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  84959. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  84960. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  84961. // truncated at around 1.3% of peak strength.
  84962. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  84963. var sigma = (1 / 3);
  84964. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  84965. var exponent = -((x * x) / (2.0 * sigma * sigma));
  84966. var weight = (1.0 / denominator) * Math.exp(exponent);
  84967. return weight;
  84968. };
  84969. /**
  84970. * Generates a string that can be used as a floating point number in GLSL.
  84971. * @param x Value to print.
  84972. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  84973. * @return GLSL float string.
  84974. */
  84975. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  84976. if (decimalFigures === void 0) { decimalFigures = 8; }
  84977. return x.toFixed(decimalFigures).replace(/0+$/, '');
  84978. };
  84979. return BlurPostProcess;
  84980. }(BABYLON.PostProcess));
  84981. BABYLON.BlurPostProcess = BlurPostProcess;
  84982. })(BABYLON || (BABYLON = {}));
  84983. //# sourceMappingURL=babylon.blurPostProcess.js.map
  84984. var BABYLON;
  84985. (function (BABYLON) {
  84986. /**
  84987. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  84988. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  84989. * based on samples that have a large difference in distance than the center pixel.
  84990. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  84991. */
  84992. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  84993. __extends(DepthOfFieldBlurPostProcess, _super);
  84994. /**
  84995. * Creates a new instance CircleOfConfusionPostProcess
  84996. * @param name The name of the effect.
  84997. * @param scene The scene the effect belongs to.
  84998. * @param direction The direction the blur should be applied.
  84999. * @param kernel The size of the kernel used to blur.
  85000. * @param options The required width/height ratio to downsize to before computing the render pass.
  85001. * @param camera The camera to apply the render pass to.
  85002. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  85003. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  85004. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85005. * @param engine The engine which the post process will be applied. (default: current engine)
  85006. * @param reusable If the post process can be reused on the same frame. (default: false)
  85007. * @param textureType Type of textures used when performing the post process. (default: 0)
  85008. * @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)
  85009. */
  85010. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  85011. if (imageToBlur === void 0) { imageToBlur = null; }
  85012. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85013. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85014. if (blockCompilation === void 0) { blockCompilation = false; }
  85015. 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;
  85016. _this.direction = direction;
  85017. _this.onApplyObservable.add(function (effect) {
  85018. if (imageToBlur != null) {
  85019. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  85020. }
  85021. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  85022. if (scene.activeCamera) {
  85023. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  85024. }
  85025. });
  85026. return _this;
  85027. }
  85028. return DepthOfFieldBlurPostProcess;
  85029. }(BABYLON.BlurPostProcess));
  85030. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  85031. })(BABYLON || (BABYLON = {}));
  85032. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  85033. var BABYLON;
  85034. (function (BABYLON) {
  85035. /**
  85036. * Options to be set when merging outputs from the default pipeline.
  85037. */
  85038. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  85039. function DepthOfFieldMergePostProcessOptions() {
  85040. }
  85041. return DepthOfFieldMergePostProcessOptions;
  85042. }());
  85043. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  85044. /**
  85045. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  85046. */
  85047. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  85048. __extends(DepthOfFieldMergePostProcess, _super);
  85049. /**
  85050. * Creates a new instance of DepthOfFieldMergePostProcess
  85051. * @param name The name of the effect.
  85052. * @param originalFromInput Post process which's input will be used for the merge.
  85053. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  85054. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  85055. * @param options The required width/height ratio to downsize to before computing the render pass.
  85056. * @param camera The camera to apply the render pass to.
  85057. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85058. * @param engine The engine which the post process will be applied. (default: current engine)
  85059. * @param reusable If the post process can be reused on the same frame. (default: false)
  85060. * @param textureType Type of textures used when performing the post process. (default: 0)
  85061. * @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)
  85062. */
  85063. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85064. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85065. if (blockCompilation === void 0) { blockCompilation = false; }
  85066. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  85067. _this.blurSteps = blurSteps;
  85068. _this.onApplyObservable.add(function (effect) {
  85069. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  85070. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  85071. blurSteps.forEach(function (step, index) {
  85072. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  85073. });
  85074. });
  85075. if (!blockCompilation) {
  85076. _this.updateEffect();
  85077. }
  85078. return _this;
  85079. }
  85080. /**
  85081. * Updates the effect with the current post process compile time values and recompiles the shader.
  85082. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  85083. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  85084. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  85085. * @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
  85086. * @param onCompiled Called when the shader has been compiled.
  85087. * @param onError Called if there is an error when compiling a shader.
  85088. */
  85089. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  85090. if (defines === void 0) { defines = null; }
  85091. if (uniforms === void 0) { uniforms = null; }
  85092. if (samplers === void 0) { samplers = null; }
  85093. if (!defines) {
  85094. defines = "";
  85095. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  85096. }
  85097. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  85098. };
  85099. return DepthOfFieldMergePostProcess;
  85100. }(BABYLON.PostProcess));
  85101. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  85102. })(BABYLON || (BABYLON = {}));
  85103. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  85104. var BABYLON;
  85105. (function (BABYLON) {
  85106. /**
  85107. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  85108. */
  85109. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  85110. __extends(CircleOfConfusionPostProcess, _super);
  85111. /**
  85112. * Creates a new instance CircleOfConfusionPostProcess
  85113. * @param name The name of the effect.
  85114. * @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.
  85115. * @param options The required width/height ratio to downsize to before computing the render pass.
  85116. * @param camera The camera to apply the render pass to.
  85117. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85118. * @param engine The engine which the post process will be applied. (default: current engine)
  85119. * @param reusable If the post process can be reused on the same frame. (default: false)
  85120. * @param textureType Type of textures used when performing the post process. (default: 0)
  85121. * @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)
  85122. */
  85123. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85124. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85125. if (blockCompilation === void 0) { blockCompilation = false; }
  85126. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85127. /**
  85128. * 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.
  85129. */
  85130. _this.lensSize = 50;
  85131. /**
  85132. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  85133. */
  85134. _this.fStop = 1.4;
  85135. /**
  85136. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  85137. */
  85138. _this.focusDistance = 2000;
  85139. /**
  85140. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  85141. */
  85142. _this.focalLength = 50;
  85143. _this._depthTexture = null;
  85144. _this._depthTexture = depthTexture;
  85145. _this.onApplyObservable.add(function (effect) {
  85146. if (!_this._depthTexture) {
  85147. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  85148. return;
  85149. }
  85150. effect.setTexture("depthSampler", _this._depthTexture);
  85151. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  85152. var aperture = _this.lensSize / _this.fStop;
  85153. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  85154. effect.setFloat('focusDistance', _this.focusDistance);
  85155. effect.setFloat('cocPrecalculation', cocPrecalculation);
  85156. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  85157. });
  85158. return _this;
  85159. }
  85160. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  85161. /**
  85162. * 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.
  85163. */
  85164. set: function (value) {
  85165. this._depthTexture = value;
  85166. },
  85167. enumerable: true,
  85168. configurable: true
  85169. });
  85170. return CircleOfConfusionPostProcess;
  85171. }(BABYLON.PostProcess));
  85172. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  85173. })(BABYLON || (BABYLON = {}));
  85174. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  85175. var BABYLON;
  85176. (function (BABYLON) {
  85177. /**
  85178. * Specifies the level of max blur that should be applied when using the depth of field effect
  85179. */
  85180. var DepthOfFieldEffectBlurLevel;
  85181. (function (DepthOfFieldEffectBlurLevel) {
  85182. /**
  85183. * Subtle blur
  85184. */
  85185. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  85186. /**
  85187. * Medium blur
  85188. */
  85189. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  85190. /**
  85191. * Large blur
  85192. */
  85193. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  85194. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  85195. ;
  85196. /**
  85197. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  85198. */
  85199. var DepthOfFieldEffect = /** @class */ (function (_super) {
  85200. __extends(DepthOfFieldEffect, _super);
  85201. /**
  85202. * Creates a new instance DepthOfFieldEffect
  85203. * @param scene The scene the effect belongs to.
  85204. * @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.
  85205. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  85206. * @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)
  85207. */
  85208. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  85209. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  85210. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  85211. if (blockCompilation === void 0) { blockCompilation = false; }
  85212. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  85213. return _this._effects;
  85214. }, true) || this;
  85215. /**
  85216. * @hidden Internal post processes in depth of field effect
  85217. */
  85218. _this._effects = [];
  85219. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  85220. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85221. // 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)
  85222. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  85223. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  85224. _this._depthOfFieldBlurY = [];
  85225. _this._depthOfFieldBlurX = [];
  85226. var blurCount = 1;
  85227. var kernelSize = 15;
  85228. switch (blurLevel) {
  85229. case DepthOfFieldEffectBlurLevel.High: {
  85230. blurCount = 3;
  85231. kernelSize = 51;
  85232. break;
  85233. }
  85234. case DepthOfFieldEffectBlurLevel.Medium: {
  85235. blurCount = 2;
  85236. kernelSize = 31;
  85237. break;
  85238. }
  85239. default: {
  85240. kernelSize = 15;
  85241. blurCount = 1;
  85242. break;
  85243. }
  85244. }
  85245. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  85246. var ratio = 1.0;
  85247. for (var i = 0; i < blurCount; i++) {
  85248. 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);
  85249. blurY.autoClear = false;
  85250. ratio = 0.75 / Math.pow(2, i);
  85251. 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);
  85252. blurX.autoClear = false;
  85253. _this._depthOfFieldBlurY.push(blurY);
  85254. _this._depthOfFieldBlurX.push(blurX);
  85255. }
  85256. // Set all post processes on the effect.
  85257. _this._effects = [_this._circleOfConfusion];
  85258. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  85259. _this._effects.push(_this._depthOfFieldBlurY[i]);
  85260. _this._effects.push(_this._depthOfFieldBlurX[i]);
  85261. }
  85262. // Merge blurred images with original image based on circleOfConfusion
  85263. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85264. _this._dofMerge.autoClear = false;
  85265. _this._effects.push(_this._dofMerge);
  85266. return _this;
  85267. }
  85268. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  85269. get: function () {
  85270. return this._circleOfConfusion.focalLength;
  85271. },
  85272. /**
  85273. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  85274. */
  85275. set: function (value) {
  85276. this._circleOfConfusion.focalLength = value;
  85277. },
  85278. enumerable: true,
  85279. configurable: true
  85280. });
  85281. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  85282. get: function () {
  85283. return this._circleOfConfusion.fStop;
  85284. },
  85285. /**
  85286. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  85287. */
  85288. set: function (value) {
  85289. this._circleOfConfusion.fStop = value;
  85290. },
  85291. enumerable: true,
  85292. configurable: true
  85293. });
  85294. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  85295. get: function () {
  85296. return this._circleOfConfusion.focusDistance;
  85297. },
  85298. /**
  85299. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  85300. */
  85301. set: function (value) {
  85302. this._circleOfConfusion.focusDistance = value;
  85303. },
  85304. enumerable: true,
  85305. configurable: true
  85306. });
  85307. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  85308. get: function () {
  85309. return this._circleOfConfusion.lensSize;
  85310. },
  85311. /**
  85312. * 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.
  85313. */
  85314. set: function (value) {
  85315. this._circleOfConfusion.lensSize = value;
  85316. },
  85317. enumerable: true,
  85318. configurable: true
  85319. });
  85320. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  85321. /**
  85322. * 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.
  85323. */
  85324. set: function (value) {
  85325. this._circleOfConfusion.depthTexture = value;
  85326. },
  85327. enumerable: true,
  85328. configurable: true
  85329. });
  85330. /**
  85331. * Disposes each of the internal effects for a given camera.
  85332. * @param camera The camera to dispose the effect on.
  85333. */
  85334. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  85335. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85336. this._effects[effectIndex].dispose(camera);
  85337. }
  85338. };
  85339. /**
  85340. * @hidden Internal
  85341. */
  85342. DepthOfFieldEffect.prototype._updateEffects = function () {
  85343. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85344. this._effects[effectIndex].updateEffect();
  85345. }
  85346. };
  85347. /**
  85348. * Internal
  85349. * @returns if all the contained post processes are ready.
  85350. * @hidden
  85351. */
  85352. DepthOfFieldEffect.prototype._isReady = function () {
  85353. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85354. if (!this._effects[effectIndex].isReady()) {
  85355. return false;
  85356. }
  85357. }
  85358. return true;
  85359. };
  85360. return DepthOfFieldEffect;
  85361. }(BABYLON.PostProcessRenderEffect));
  85362. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  85363. })(BABYLON || (BABYLON = {}));
  85364. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  85365. var BABYLON;
  85366. (function (BABYLON) {
  85367. /**
  85368. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  85369. */
  85370. var BloomMergePostProcess = /** @class */ (function (_super) {
  85371. __extends(BloomMergePostProcess, _super);
  85372. /**
  85373. * Creates a new instance of @see BloomMergePostProcess
  85374. * @param name The name of the effect.
  85375. * @param originalFromInput Post process which's input will be used for the merge.
  85376. * @param blurred Blurred highlights post process which's output will be used.
  85377. * @param weight Weight of the bloom to be added to the original input.
  85378. * @param options The required width/height ratio to downsize to before computing the render pass.
  85379. * @param camera The camera to apply the render pass to.
  85380. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85381. * @param engine The engine which the post process will be applied. (default: current engine)
  85382. * @param reusable If the post process can be reused on the same frame. (default: false)
  85383. * @param textureType Type of textures used when performing the post process. (default: 0)
  85384. * @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)
  85385. */
  85386. function BloomMergePostProcess(name, originalFromInput, blurred,
  85387. /** Weight of the bloom to be added to the original input. */
  85388. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85389. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85390. if (blockCompilation === void 0) { blockCompilation = false; }
  85391. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  85392. _this.weight = weight;
  85393. _this.onApplyObservable.add(function (effect) {
  85394. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  85395. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  85396. effect.setFloat("bloomWeight", _this.weight);
  85397. });
  85398. if (!blockCompilation) {
  85399. _this.updateEffect();
  85400. }
  85401. return _this;
  85402. }
  85403. return BloomMergePostProcess;
  85404. }(BABYLON.PostProcess));
  85405. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  85406. })(BABYLON || (BABYLON = {}));
  85407. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  85408. var BABYLON;
  85409. (function (BABYLON) {
  85410. /**
  85411. * 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.
  85412. */
  85413. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  85414. __extends(ExtractHighlightsPostProcess, _super);
  85415. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85416. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85417. if (blockCompilation === void 0) { blockCompilation = false; }
  85418. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85419. /**
  85420. * The luminance threshold, pixels below this value will be set to black.
  85421. */
  85422. _this.threshold = 0.9;
  85423. /** @hidden */
  85424. _this._exposure = 1;
  85425. /**
  85426. * Post process which has the input texture to be used when performing highlight extraction
  85427. * @hidden
  85428. */
  85429. _this._inputPostProcess = null;
  85430. _this.onApplyObservable.add(function (effect) {
  85431. if (_this._inputPostProcess) {
  85432. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  85433. }
  85434. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  85435. effect.setFloat('exposure', _this._exposure);
  85436. });
  85437. return _this;
  85438. }
  85439. return ExtractHighlightsPostProcess;
  85440. }(BABYLON.PostProcess));
  85441. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  85442. })(BABYLON || (BABYLON = {}));
  85443. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  85444. var BABYLON;
  85445. (function (BABYLON) {
  85446. /**
  85447. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  85448. */
  85449. var BloomEffect = /** @class */ (function (_super) {
  85450. __extends(BloomEffect, _super);
  85451. /**
  85452. * Creates a new instance of @see BloomEffect
  85453. * @param scene The scene the effect belongs to.
  85454. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  85455. * @param bloomKernel The size of the kernel to be used when applying the blur.
  85456. * @param bloomWeight The the strength of bloom.
  85457. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  85458. * @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)
  85459. */
  85460. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  85461. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  85462. if (blockCompilation === void 0) { blockCompilation = false; }
  85463. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  85464. return _this._effects;
  85465. }, true) || this;
  85466. _this.bloomScale = bloomScale;
  85467. /**
  85468. * @hidden Internal
  85469. */
  85470. _this._effects = [];
  85471. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85472. _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);
  85473. _this._blurX.alwaysForcePOT = true;
  85474. _this._blurX.autoClear = false;
  85475. _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);
  85476. _this._blurY.alwaysForcePOT = true;
  85477. _this._blurY.autoClear = false;
  85478. _this.kernel = bloomKernel;
  85479. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  85480. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85481. _this._merge.autoClear = false;
  85482. _this._effects.push(_this._merge);
  85483. return _this;
  85484. }
  85485. Object.defineProperty(BloomEffect.prototype, "threshold", {
  85486. /**
  85487. * The luminance threshold to find bright areas of the image to bloom.
  85488. */
  85489. get: function () {
  85490. return this._downscale.threshold;
  85491. },
  85492. set: function (value) {
  85493. this._downscale.threshold = value;
  85494. },
  85495. enumerable: true,
  85496. configurable: true
  85497. });
  85498. Object.defineProperty(BloomEffect.prototype, "weight", {
  85499. /**
  85500. * The strength of the bloom.
  85501. */
  85502. get: function () {
  85503. return this._merge.weight;
  85504. },
  85505. set: function (value) {
  85506. this._merge.weight = value;
  85507. },
  85508. enumerable: true,
  85509. configurable: true
  85510. });
  85511. Object.defineProperty(BloomEffect.prototype, "kernel", {
  85512. /**
  85513. * Specifies the size of the bloom blur kernel, relative to the final output size
  85514. */
  85515. get: function () {
  85516. return this._blurX.kernel / this.bloomScale;
  85517. },
  85518. set: function (value) {
  85519. this._blurX.kernel = value * this.bloomScale;
  85520. this._blurY.kernel = value * this.bloomScale;
  85521. },
  85522. enumerable: true,
  85523. configurable: true
  85524. });
  85525. /**
  85526. * Disposes each of the internal effects for a given camera.
  85527. * @param camera The camera to dispose the effect on.
  85528. */
  85529. BloomEffect.prototype.disposeEffects = function (camera) {
  85530. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85531. this._effects[effectIndex].dispose(camera);
  85532. }
  85533. };
  85534. /**
  85535. * @hidden Internal
  85536. */
  85537. BloomEffect.prototype._updateEffects = function () {
  85538. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85539. this._effects[effectIndex].updateEffect();
  85540. }
  85541. };
  85542. /**
  85543. * Internal
  85544. * @returns if all the contained post processes are ready.
  85545. * @hidden
  85546. */
  85547. BloomEffect.prototype._isReady = function () {
  85548. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85549. if (!this._effects[effectIndex].isReady()) {
  85550. return false;
  85551. }
  85552. }
  85553. return true;
  85554. };
  85555. return BloomEffect;
  85556. }(BABYLON.PostProcessRenderEffect));
  85557. BABYLON.BloomEffect = BloomEffect;
  85558. })(BABYLON || (BABYLON = {}));
  85559. //# sourceMappingURL=babylon.bloomEffect.js.map
  85560. var BABYLON;
  85561. (function (BABYLON) {
  85562. /**
  85563. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  85564. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  85565. */
  85566. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  85567. __extends(DefaultRenderingPipeline, _super);
  85568. /**
  85569. * @constructor
  85570. * @param {string} name - The rendering pipeline name (default: "")
  85571. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  85572. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  85573. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  85574. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  85575. */
  85576. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  85577. if (name === void 0) { name = ""; }
  85578. if (hdr === void 0) { hdr = true; }
  85579. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  85580. if (automaticBuild === void 0) { automaticBuild = true; }
  85581. var _this = _super.call(this, scene.getEngine(), name) || this;
  85582. _this._camerasToBeAttached = [];
  85583. /**
  85584. * ID of the sharpen post process,
  85585. */
  85586. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  85587. /**
  85588. * @ignore
  85589. * ID of the image processing post process;
  85590. */
  85591. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  85592. /**
  85593. * @ignore
  85594. * ID of the Fast Approximate Anti-Aliasing post process;
  85595. */
  85596. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  85597. /**
  85598. * ID of the chromatic aberration post process,
  85599. */
  85600. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  85601. /**
  85602. * ID of the grain post process
  85603. */
  85604. _this.GrainPostProcessId = "GrainPostProcessEffect";
  85605. /**
  85606. * Glow post process which adds a glow to emmisive areas of the image
  85607. */
  85608. _this._glowLayer = null;
  85609. /**
  85610. * Animations which can be used to tweak settings over a period of time
  85611. */
  85612. _this.animations = [];
  85613. _this._imageProcessingConfigurationObserver = null;
  85614. // Values
  85615. _this._sharpenEnabled = false;
  85616. _this._bloomEnabled = false;
  85617. _this._depthOfFieldEnabled = false;
  85618. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  85619. _this._fxaaEnabled = false;
  85620. _this._imageProcessingEnabled = true;
  85621. _this._bloomScale = 0.5;
  85622. _this._chromaticAberrationEnabled = false;
  85623. _this._grainEnabled = false;
  85624. _this._buildAllowed = true;
  85625. _this._resizeObserver = null;
  85626. _this._hardwareScaleLevel = 1.0;
  85627. _this._bloomKernel = 64;
  85628. /**
  85629. * Specifies the weight of the bloom in the final rendering
  85630. */
  85631. _this._bloomWeight = 0.15;
  85632. /**
  85633. * Specifies the luma threshold for the area that will be blurred by the bloom
  85634. */
  85635. _this._bloomThreshold = 0.9;
  85636. _this._samples = 1;
  85637. _this._hasCleared = false;
  85638. _this._prevPostProcess = null;
  85639. _this._prevPrevPostProcess = null;
  85640. _this._depthOfFieldSceneObserver = null;
  85641. _this._cameras = cameras || scene.cameras;
  85642. _this._cameras = _this._cameras.slice();
  85643. _this._camerasToBeAttached = _this._cameras.slice();
  85644. _this._buildAllowed = automaticBuild;
  85645. // Initialize
  85646. _this._scene = scene;
  85647. var caps = _this._scene.getEngine().getCaps();
  85648. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  85649. // Misc
  85650. if (_this._hdr) {
  85651. if (caps.textureHalfFloatRender) {
  85652. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85653. }
  85654. else if (caps.textureFloatRender) {
  85655. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85656. }
  85657. }
  85658. else {
  85659. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85660. }
  85661. // Attach
  85662. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85663. var engine = _this._scene.getEngine();
  85664. // Create post processes before hand so they can be modified before enabled.
  85665. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  85666. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85667. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  85668. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  85669. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  85670. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85671. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  85672. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85673. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  85674. _this._resizeObserver = engine.onResizeObservable.add(function () {
  85675. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  85676. _this.bloomKernel = _this.bloomKernel;
  85677. });
  85678. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  85679. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  85680. });
  85681. _this._buildPipeline();
  85682. return _this;
  85683. }
  85684. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  85685. get: function () {
  85686. return this._sharpenEnabled;
  85687. },
  85688. /**
  85689. * Enable or disable the sharpen process from the pipeline
  85690. */
  85691. set: function (enabled) {
  85692. if (this._sharpenEnabled === enabled) {
  85693. return;
  85694. }
  85695. this._sharpenEnabled = enabled;
  85696. this._buildPipeline();
  85697. },
  85698. enumerable: true,
  85699. configurable: true
  85700. });
  85701. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  85702. /**
  85703. * Specifies the size of the bloom blur kernel, relative to the final output size
  85704. */
  85705. get: function () {
  85706. return this._bloomKernel;
  85707. },
  85708. set: function (value) {
  85709. this._bloomKernel = value;
  85710. this.bloom.kernel = value / this._hardwareScaleLevel;
  85711. },
  85712. enumerable: true,
  85713. configurable: true
  85714. });
  85715. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  85716. get: function () {
  85717. return this._bloomWeight;
  85718. },
  85719. /**
  85720. * The strength of the bloom.
  85721. */
  85722. set: function (value) {
  85723. if (this._bloomWeight === value) {
  85724. return;
  85725. }
  85726. this.bloom.weight = value;
  85727. this._bloomWeight = value;
  85728. },
  85729. enumerable: true,
  85730. configurable: true
  85731. });
  85732. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  85733. get: function () {
  85734. return this._bloomThreshold;
  85735. },
  85736. /**
  85737. * The strength of the bloom.
  85738. */
  85739. set: function (value) {
  85740. if (this._bloomThreshold === value) {
  85741. return;
  85742. }
  85743. this.bloom.threshold = value;
  85744. this._bloomThreshold = value;
  85745. },
  85746. enumerable: true,
  85747. configurable: true
  85748. });
  85749. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  85750. get: function () {
  85751. return this._bloomScale;
  85752. },
  85753. /**
  85754. * The scale of the bloom, lower value will provide better performance.
  85755. */
  85756. set: function (value) {
  85757. if (this._bloomScale === value) {
  85758. return;
  85759. }
  85760. this._bloomScale = value;
  85761. // recreate bloom and dispose old as this setting is not dynamic
  85762. this._rebuildBloom();
  85763. this._buildPipeline();
  85764. },
  85765. enumerable: true,
  85766. configurable: true
  85767. });
  85768. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  85769. get: function () {
  85770. return this._bloomEnabled;
  85771. },
  85772. /**
  85773. * Enable or disable the bloom from the pipeline
  85774. */
  85775. set: function (enabled) {
  85776. if (this._bloomEnabled === enabled) {
  85777. return;
  85778. }
  85779. this._bloomEnabled = enabled;
  85780. this._buildPipeline();
  85781. },
  85782. enumerable: true,
  85783. configurable: true
  85784. });
  85785. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  85786. // recreate bloom and dispose old as this setting is not dynamic
  85787. var oldBloom = this.bloom;
  85788. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  85789. this.bloom.threshold = oldBloom.threshold;
  85790. for (var i = 0; i < this._cameras.length; i++) {
  85791. oldBloom.disposeEffects(this._cameras[i]);
  85792. }
  85793. };
  85794. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  85795. /**
  85796. * If the depth of field is enabled.
  85797. */
  85798. get: function () {
  85799. return this._depthOfFieldEnabled;
  85800. },
  85801. set: function (enabled) {
  85802. if (this._depthOfFieldEnabled === enabled) {
  85803. return;
  85804. }
  85805. this._depthOfFieldEnabled = enabled;
  85806. this._buildPipeline();
  85807. },
  85808. enumerable: true,
  85809. configurable: true
  85810. });
  85811. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  85812. /**
  85813. * Blur level of the depth of field effect. (Higher blur will effect performance)
  85814. */
  85815. get: function () {
  85816. return this._depthOfFieldBlurLevel;
  85817. },
  85818. set: function (value) {
  85819. if (this._depthOfFieldBlurLevel === value) {
  85820. return;
  85821. }
  85822. this._depthOfFieldBlurLevel = value;
  85823. // recreate dof and dispose old as this setting is not dynamic
  85824. var oldDof = this.depthOfField;
  85825. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  85826. this.depthOfField.focalLength = oldDof.focalLength;
  85827. this.depthOfField.focusDistance = oldDof.focusDistance;
  85828. this.depthOfField.fStop = oldDof.fStop;
  85829. this.depthOfField.lensSize = oldDof.lensSize;
  85830. for (var i = 0; i < this._cameras.length; i++) {
  85831. oldDof.disposeEffects(this._cameras[i]);
  85832. }
  85833. this._buildPipeline();
  85834. },
  85835. enumerable: true,
  85836. configurable: true
  85837. });
  85838. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  85839. get: function () {
  85840. return this._fxaaEnabled;
  85841. },
  85842. /**
  85843. * If the anti aliasing is enabled.
  85844. */
  85845. set: function (enabled) {
  85846. if (this._fxaaEnabled === enabled) {
  85847. return;
  85848. }
  85849. this._fxaaEnabled = enabled;
  85850. this._buildPipeline();
  85851. },
  85852. enumerable: true,
  85853. configurable: true
  85854. });
  85855. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  85856. get: function () {
  85857. return this._samples;
  85858. },
  85859. /**
  85860. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  85861. */
  85862. set: function (sampleCount) {
  85863. if (this._samples === sampleCount) {
  85864. return;
  85865. }
  85866. this._samples = sampleCount;
  85867. this._buildPipeline();
  85868. },
  85869. enumerable: true,
  85870. configurable: true
  85871. });
  85872. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  85873. get: function () {
  85874. return this._imageProcessingEnabled;
  85875. },
  85876. /**
  85877. * If image processing is enabled.
  85878. */
  85879. set: function (enabled) {
  85880. if (this._imageProcessingEnabled === enabled) {
  85881. return;
  85882. }
  85883. this._imageProcessingEnabled = enabled;
  85884. this._buildPipeline();
  85885. },
  85886. enumerable: true,
  85887. configurable: true
  85888. });
  85889. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  85890. get: function () {
  85891. return this._glowLayer == null;
  85892. },
  85893. /**
  85894. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  85895. */
  85896. set: function (enabled) {
  85897. if (enabled && !this._glowLayer) {
  85898. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  85899. }
  85900. else if (!enabled && this._glowLayer) {
  85901. this._glowLayer.dispose();
  85902. this._glowLayer = null;
  85903. }
  85904. },
  85905. enumerable: true,
  85906. configurable: true
  85907. });
  85908. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  85909. get: function () {
  85910. return this._chromaticAberrationEnabled;
  85911. },
  85912. /**
  85913. * Enable or disable the chromaticAberration process from the pipeline
  85914. */
  85915. set: function (enabled) {
  85916. if (this._chromaticAberrationEnabled === enabled) {
  85917. return;
  85918. }
  85919. this._chromaticAberrationEnabled = enabled;
  85920. this._buildPipeline();
  85921. },
  85922. enumerable: true,
  85923. configurable: true
  85924. });
  85925. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  85926. get: function () {
  85927. return this._grainEnabled;
  85928. },
  85929. /**
  85930. * Enable or disable the grain process from the pipeline
  85931. */
  85932. set: function (enabled) {
  85933. if (this._grainEnabled === enabled) {
  85934. return;
  85935. }
  85936. this._grainEnabled = enabled;
  85937. this._buildPipeline();
  85938. },
  85939. enumerable: true,
  85940. configurable: true
  85941. });
  85942. /**
  85943. * Force the compilation of the entire pipeline.
  85944. */
  85945. DefaultRenderingPipeline.prototype.prepare = function () {
  85946. var previousState = this._buildAllowed;
  85947. this._buildAllowed = true;
  85948. this._buildPipeline();
  85949. this._buildAllowed = previousState;
  85950. };
  85951. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  85952. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  85953. if (this._hasCleared) {
  85954. postProcess.autoClear = false;
  85955. }
  85956. else {
  85957. postProcess.autoClear = true;
  85958. this._scene.autoClear = false;
  85959. this._hasCleared = true;
  85960. }
  85961. if (!skipTextureSharing) {
  85962. if (this._prevPrevPostProcess) {
  85963. postProcess.shareOutputWith(this._prevPrevPostProcess);
  85964. }
  85965. else {
  85966. postProcess.useOwnOutput();
  85967. }
  85968. if (this._prevPostProcess) {
  85969. this._prevPrevPostProcess = this._prevPostProcess;
  85970. }
  85971. this._prevPostProcess = postProcess;
  85972. }
  85973. };
  85974. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  85975. var _this = this;
  85976. if (!this._buildAllowed) {
  85977. return;
  85978. }
  85979. this._scene.autoClear = true;
  85980. var engine = this._scene.getEngine();
  85981. this._disposePostProcesses();
  85982. if (this._cameras !== null) {
  85983. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  85984. // get back cameras to be used to reattach pipeline
  85985. this._cameras = this._camerasToBeAttached.slice();
  85986. }
  85987. this._reset();
  85988. this._prevPostProcess = null;
  85989. this._prevPrevPostProcess = null;
  85990. this._hasCleared = false;
  85991. if (this.depthOfFieldEnabled) {
  85992. // Multi camera suport
  85993. if (this._cameras.length > 1) {
  85994. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  85995. var camera = _a[_i];
  85996. var depthRenderer = this._scene.enableDepthRenderer(camera);
  85997. depthRenderer.useOnlyInActiveCamera = true;
  85998. }
  85999. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  86000. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  86001. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  86002. }
  86003. });
  86004. }
  86005. else {
  86006. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  86007. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  86008. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  86009. }
  86010. if (!this.depthOfField._isReady()) {
  86011. this.depthOfField._updateEffects();
  86012. }
  86013. this.addEffect(this.depthOfField);
  86014. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  86015. }
  86016. else {
  86017. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  86018. }
  86019. if (this.bloomEnabled) {
  86020. if (!this.bloom._isReady()) {
  86021. this.bloom._updateEffects();
  86022. }
  86023. this.addEffect(this.bloom);
  86024. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  86025. }
  86026. if (this._imageProcessingEnabled) {
  86027. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  86028. if (this._hdr) {
  86029. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  86030. this._setAutoClearAndTextureSharing(this.imageProcessing);
  86031. }
  86032. else {
  86033. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  86034. }
  86035. }
  86036. if (this.sharpenEnabled) {
  86037. if (!this.sharpen.isReady()) {
  86038. this.sharpen.updateEffect();
  86039. }
  86040. this.addEffect(this._sharpenEffect);
  86041. this._setAutoClearAndTextureSharing(this.sharpen);
  86042. }
  86043. if (this.grainEnabled) {
  86044. if (!this.grain.isReady()) {
  86045. this.grain.updateEffect();
  86046. }
  86047. this.addEffect(this._grainEffect);
  86048. this._setAutoClearAndTextureSharing(this.grain);
  86049. }
  86050. if (this.chromaticAberrationEnabled) {
  86051. if (!this.chromaticAberration.isReady()) {
  86052. this.chromaticAberration.updateEffect();
  86053. }
  86054. this.addEffect(this._chromaticAberrationEffect);
  86055. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  86056. }
  86057. if (this.fxaaEnabled) {
  86058. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  86059. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  86060. this._setAutoClearAndTextureSharing(this.fxaa, true);
  86061. }
  86062. if (this._cameras !== null) {
  86063. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  86064. }
  86065. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  86066. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  86067. }
  86068. };
  86069. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  86070. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  86071. for (var i = 0; i < this._cameras.length; i++) {
  86072. var camera = this._cameras[i];
  86073. if (this.imageProcessing) {
  86074. this.imageProcessing.dispose(camera);
  86075. }
  86076. if (this.fxaa) {
  86077. this.fxaa.dispose(camera);
  86078. }
  86079. // These are created in the constructor and should not be disposed on every pipeline change
  86080. if (disposeNonRecreated) {
  86081. if (this.sharpen) {
  86082. this.sharpen.dispose(camera);
  86083. }
  86084. if (this.depthOfField) {
  86085. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  86086. this.depthOfField.disposeEffects(camera);
  86087. }
  86088. if (this.bloom) {
  86089. this.bloom.disposeEffects(camera);
  86090. }
  86091. if (this.chromaticAberration) {
  86092. this.chromaticAberration.dispose(camera);
  86093. }
  86094. if (this.grain) {
  86095. this.grain.dispose(camera);
  86096. }
  86097. if (this._glowLayer) {
  86098. this._glowLayer.dispose();
  86099. }
  86100. }
  86101. }
  86102. this.imageProcessing = null;
  86103. this.fxaa = null;
  86104. if (disposeNonRecreated) {
  86105. this.sharpen = null;
  86106. this._sharpenEffect = null;
  86107. this.depthOfField = null;
  86108. this.bloom = null;
  86109. this.chromaticAberration = null;
  86110. this._chromaticAberrationEffect = null;
  86111. this.grain = null;
  86112. this._grainEffect = null;
  86113. this._glowLayer = null;
  86114. }
  86115. };
  86116. /**
  86117. * Adds a camera to the pipeline
  86118. * @param camera the camera to be added
  86119. */
  86120. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  86121. this._camerasToBeAttached.push(camera);
  86122. this._buildPipeline();
  86123. };
  86124. /**
  86125. * Removes a camera from the pipeline
  86126. * @param camera the camera to remove
  86127. */
  86128. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  86129. var index = this._camerasToBeAttached.indexOf(camera);
  86130. this._camerasToBeAttached.splice(index, 1);
  86131. this._buildPipeline();
  86132. };
  86133. /**
  86134. * Dispose of the pipeline and stop all post processes
  86135. */
  86136. DefaultRenderingPipeline.prototype.dispose = function () {
  86137. this._disposePostProcesses(true);
  86138. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86139. this._scene.autoClear = true;
  86140. if (this._resizeObserver) {
  86141. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  86142. this._resizeObserver = null;
  86143. }
  86144. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  86145. _super.prototype.dispose.call(this);
  86146. };
  86147. /**
  86148. * Serialize the rendering pipeline (Used when exporting)
  86149. * @returns the serialized object
  86150. */
  86151. DefaultRenderingPipeline.prototype.serialize = function () {
  86152. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86153. serializationObject.customType = "DefaultRenderingPipeline";
  86154. return serializationObject;
  86155. };
  86156. /**
  86157. * Parse the serialized pipeline
  86158. * @param source Source pipeline.
  86159. * @param scene The scene to load the pipeline to.
  86160. * @param rootUrl The URL of the serialized pipeline.
  86161. * @returns An instantiated pipeline from the serialized object.
  86162. */
  86163. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  86164. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  86165. };
  86166. __decorate([
  86167. BABYLON.serialize()
  86168. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  86169. __decorate([
  86170. BABYLON.serialize()
  86171. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  86172. __decorate([
  86173. BABYLON.serialize()
  86174. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  86175. __decorate([
  86176. BABYLON.serialize()
  86177. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  86178. __decorate([
  86179. BABYLON.serialize()
  86180. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  86181. __decorate([
  86182. BABYLON.serialize()
  86183. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  86184. __decorate([
  86185. BABYLON.serialize()
  86186. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  86187. __decorate([
  86188. BABYLON.serialize()
  86189. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  86190. __decorate([
  86191. BABYLON.serialize()
  86192. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  86193. __decorate([
  86194. BABYLON.serialize()
  86195. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  86196. __decorate([
  86197. BABYLON.serialize()
  86198. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  86199. __decorate([
  86200. BABYLON.serialize()
  86201. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  86202. __decorate([
  86203. BABYLON.serialize()
  86204. ], DefaultRenderingPipeline.prototype, "samples", null);
  86205. __decorate([
  86206. BABYLON.serialize()
  86207. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  86208. __decorate([
  86209. BABYLON.serialize()
  86210. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  86211. __decorate([
  86212. BABYLON.serialize()
  86213. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  86214. __decorate([
  86215. BABYLON.serialize()
  86216. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  86217. return DefaultRenderingPipeline;
  86218. }(BABYLON.PostProcessRenderPipeline));
  86219. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  86220. })(BABYLON || (BABYLON = {}));
  86221. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  86222. var BABYLON;
  86223. (function (BABYLON) {
  86224. /**
  86225. * @hidden
  86226. */
  86227. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  86228. __extends(ImageProcessingConfigurationDefines, _super);
  86229. function ImageProcessingConfigurationDefines() {
  86230. var _this = _super.call(this) || this;
  86231. _this.IMAGEPROCESSING = false;
  86232. _this.VIGNETTE = false;
  86233. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86234. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86235. _this.TONEMAPPING = false;
  86236. _this.TONEMAPPING_ACES = false;
  86237. _this.CONTRAST = false;
  86238. _this.COLORCURVES = false;
  86239. _this.COLORGRADING = false;
  86240. _this.COLORGRADING3D = false;
  86241. _this.SAMPLER3DGREENDEPTH = false;
  86242. _this.SAMPLER3DBGRMAP = false;
  86243. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86244. _this.EXPOSURE = false;
  86245. _this.rebuild();
  86246. return _this;
  86247. }
  86248. return ImageProcessingConfigurationDefines;
  86249. }(BABYLON.MaterialDefines));
  86250. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  86251. /**
  86252. * This groups together the common properties used for image processing either in direct forward pass
  86253. * or through post processing effect depending on the use of the image processing pipeline in your scene
  86254. * or not.
  86255. */
  86256. var ImageProcessingConfiguration = /** @class */ (function () {
  86257. function ImageProcessingConfiguration() {
  86258. /**
  86259. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  86260. */
  86261. this.colorCurves = new BABYLON.ColorCurves();
  86262. this._colorCurvesEnabled = false;
  86263. this._colorGradingEnabled = false;
  86264. this._colorGradingWithGreenDepth = true;
  86265. this._colorGradingBGR = true;
  86266. /** @hidden */
  86267. this._exposure = 1.0;
  86268. this._toneMappingEnabled = false;
  86269. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  86270. this._contrast = 1.0;
  86271. /**
  86272. * Vignette stretch size.
  86273. */
  86274. this.vignetteStretch = 0;
  86275. /**
  86276. * Vignette centre X Offset.
  86277. */
  86278. this.vignetteCentreX = 0;
  86279. /**
  86280. * Vignette centre Y Offset.
  86281. */
  86282. this.vignetteCentreY = 0;
  86283. /**
  86284. * Vignette weight or intensity of the vignette effect.
  86285. */
  86286. this.vignetteWeight = 1.5;
  86287. /**
  86288. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86289. * if vignetteEnabled is set to true.
  86290. */
  86291. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  86292. /**
  86293. * Camera field of view used by the Vignette effect.
  86294. */
  86295. this.vignetteCameraFov = 0.5;
  86296. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  86297. this._vignetteEnabled = false;
  86298. this._applyByPostProcess = false;
  86299. this._isEnabled = true;
  86300. /**
  86301. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  86302. */
  86303. this.onUpdateParameters = new BABYLON.Observable();
  86304. }
  86305. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  86306. /**
  86307. * Gets wether the color curves effect is enabled.
  86308. */
  86309. get: function () {
  86310. return this._colorCurvesEnabled;
  86311. },
  86312. /**
  86313. * Sets wether the color curves effect is enabled.
  86314. */
  86315. set: function (value) {
  86316. if (this._colorCurvesEnabled === value) {
  86317. return;
  86318. }
  86319. this._colorCurvesEnabled = value;
  86320. this._updateParameters();
  86321. },
  86322. enumerable: true,
  86323. configurable: true
  86324. });
  86325. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  86326. /**
  86327. * Gets wether the color grading effect is enabled.
  86328. */
  86329. get: function () {
  86330. return this._colorGradingEnabled;
  86331. },
  86332. /**
  86333. * Sets wether the color grading effect is enabled.
  86334. */
  86335. set: function (value) {
  86336. if (this._colorGradingEnabled === value) {
  86337. return;
  86338. }
  86339. this._colorGradingEnabled = value;
  86340. this._updateParameters();
  86341. },
  86342. enumerable: true,
  86343. configurable: true
  86344. });
  86345. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  86346. /**
  86347. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  86348. */
  86349. get: function () {
  86350. return this._colorGradingWithGreenDepth;
  86351. },
  86352. /**
  86353. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  86354. */
  86355. set: function (value) {
  86356. if (this._colorGradingWithGreenDepth === value) {
  86357. return;
  86358. }
  86359. this._colorGradingWithGreenDepth = value;
  86360. this._updateParameters();
  86361. },
  86362. enumerable: true,
  86363. configurable: true
  86364. });
  86365. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  86366. /**
  86367. * Gets wether the color grading texture contains BGR values.
  86368. */
  86369. get: function () {
  86370. return this._colorGradingBGR;
  86371. },
  86372. /**
  86373. * Sets wether the color grading texture contains BGR values.
  86374. */
  86375. set: function (value) {
  86376. if (this._colorGradingBGR === value) {
  86377. return;
  86378. }
  86379. this._colorGradingBGR = value;
  86380. this._updateParameters();
  86381. },
  86382. enumerable: true,
  86383. configurable: true
  86384. });
  86385. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  86386. /**
  86387. * Gets the Exposure used in the effect.
  86388. */
  86389. get: function () {
  86390. return this._exposure;
  86391. },
  86392. /**
  86393. * Sets the Exposure used in the effect.
  86394. */
  86395. set: function (value) {
  86396. if (this._exposure === value) {
  86397. return;
  86398. }
  86399. this._exposure = value;
  86400. this._updateParameters();
  86401. },
  86402. enumerable: true,
  86403. configurable: true
  86404. });
  86405. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  86406. /**
  86407. * Gets wether the tone mapping effect is enabled.
  86408. */
  86409. get: function () {
  86410. return this._toneMappingEnabled;
  86411. },
  86412. /**
  86413. * Sets wether the tone mapping effect is enabled.
  86414. */
  86415. set: function (value) {
  86416. if (this._toneMappingEnabled === value) {
  86417. return;
  86418. }
  86419. this._toneMappingEnabled = value;
  86420. this._updateParameters();
  86421. },
  86422. enumerable: true,
  86423. configurable: true
  86424. });
  86425. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  86426. /**
  86427. * Gets the type of tone mapping effect.
  86428. */
  86429. get: function () {
  86430. return this._toneMappingType;
  86431. },
  86432. /**
  86433. * Sets the type of tone mapping effect used in BabylonJS.
  86434. */
  86435. set: function (value) {
  86436. if (this._toneMappingType === value) {
  86437. return;
  86438. }
  86439. this._toneMappingType = value;
  86440. this._updateParameters();
  86441. },
  86442. enumerable: true,
  86443. configurable: true
  86444. });
  86445. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  86446. /**
  86447. * Gets the contrast used in the effect.
  86448. */
  86449. get: function () {
  86450. return this._contrast;
  86451. },
  86452. /**
  86453. * Sets the contrast used in the effect.
  86454. */
  86455. set: function (value) {
  86456. if (this._contrast === value) {
  86457. return;
  86458. }
  86459. this._contrast = value;
  86460. this._updateParameters();
  86461. },
  86462. enumerable: true,
  86463. configurable: true
  86464. });
  86465. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  86466. /**
  86467. * Gets the vignette blend mode allowing different kind of effect.
  86468. */
  86469. get: function () {
  86470. return this._vignetteBlendMode;
  86471. },
  86472. /**
  86473. * Sets the vignette blend mode allowing different kind of effect.
  86474. */
  86475. set: function (value) {
  86476. if (this._vignetteBlendMode === value) {
  86477. return;
  86478. }
  86479. this._vignetteBlendMode = value;
  86480. this._updateParameters();
  86481. },
  86482. enumerable: true,
  86483. configurable: true
  86484. });
  86485. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  86486. /**
  86487. * Gets wether the vignette effect is enabled.
  86488. */
  86489. get: function () {
  86490. return this._vignetteEnabled;
  86491. },
  86492. /**
  86493. * Sets wether the vignette effect is enabled.
  86494. */
  86495. set: function (value) {
  86496. if (this._vignetteEnabled === value) {
  86497. return;
  86498. }
  86499. this._vignetteEnabled = value;
  86500. this._updateParameters();
  86501. },
  86502. enumerable: true,
  86503. configurable: true
  86504. });
  86505. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  86506. /**
  86507. * Gets wether the image processing is applied through a post process or not.
  86508. */
  86509. get: function () {
  86510. return this._applyByPostProcess;
  86511. },
  86512. /**
  86513. * Sets wether the image processing is applied through a post process or not.
  86514. */
  86515. set: function (value) {
  86516. if (this._applyByPostProcess === value) {
  86517. return;
  86518. }
  86519. this._applyByPostProcess = value;
  86520. this._updateParameters();
  86521. },
  86522. enumerable: true,
  86523. configurable: true
  86524. });
  86525. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  86526. /**
  86527. * Gets wether the image processing is enabled or not.
  86528. */
  86529. get: function () {
  86530. return this._isEnabled;
  86531. },
  86532. /**
  86533. * Sets wether the image processing is enabled or not.
  86534. */
  86535. set: function (value) {
  86536. if (this._isEnabled === value) {
  86537. return;
  86538. }
  86539. this._isEnabled = value;
  86540. this._updateParameters();
  86541. },
  86542. enumerable: true,
  86543. configurable: true
  86544. });
  86545. /**
  86546. * Method called each time the image processing information changes requires to recompile the effect.
  86547. */
  86548. ImageProcessingConfiguration.prototype._updateParameters = function () {
  86549. this.onUpdateParameters.notifyObservers(this);
  86550. };
  86551. /**
  86552. * Gets the current class name.
  86553. * @return "ImageProcessingConfiguration"
  86554. */
  86555. ImageProcessingConfiguration.prototype.getClassName = function () {
  86556. return "ImageProcessingConfiguration";
  86557. };
  86558. /**
  86559. * Prepare the list of uniforms associated with the Image Processing effects.
  86560. * @param uniforms The list of uniforms used in the effect
  86561. * @param defines the list of defines currently in use
  86562. */
  86563. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  86564. if (defines.EXPOSURE) {
  86565. uniforms.push("exposureLinear");
  86566. }
  86567. if (defines.CONTRAST) {
  86568. uniforms.push("contrast");
  86569. }
  86570. if (defines.COLORGRADING) {
  86571. uniforms.push("colorTransformSettings");
  86572. }
  86573. if (defines.VIGNETTE) {
  86574. uniforms.push("vInverseScreenSize");
  86575. uniforms.push("vignetteSettings1");
  86576. uniforms.push("vignetteSettings2");
  86577. }
  86578. if (defines.COLORCURVES) {
  86579. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  86580. }
  86581. };
  86582. /**
  86583. * Prepare the list of samplers associated with the Image Processing effects.
  86584. * @param samplersList The list of uniforms used in the effect
  86585. * @param defines the list of defines currently in use
  86586. */
  86587. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  86588. if (defines.COLORGRADING) {
  86589. samplersList.push("txColorTransform");
  86590. }
  86591. };
  86592. /**
  86593. * Prepare the list of defines associated to the shader.
  86594. * @param defines the list of defines to complete
  86595. * @param forPostProcess Define if we are currently in post process mode or not
  86596. */
  86597. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  86598. if (forPostProcess === void 0) { forPostProcess = false; }
  86599. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  86600. defines.VIGNETTE = false;
  86601. defines.TONEMAPPING = false;
  86602. defines.TONEMAPPING_ACES = false;
  86603. defines.CONTRAST = false;
  86604. defines.EXPOSURE = false;
  86605. defines.COLORCURVES = false;
  86606. defines.COLORGRADING = false;
  86607. defines.COLORGRADING3D = false;
  86608. defines.IMAGEPROCESSING = false;
  86609. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  86610. return;
  86611. }
  86612. defines.VIGNETTE = this.vignetteEnabled;
  86613. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  86614. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  86615. defines.TONEMAPPING = this.toneMappingEnabled;
  86616. switch (this._toneMappingType) {
  86617. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  86618. defines.TONEMAPPING_ACES = true;
  86619. break;
  86620. }
  86621. defines.CONTRAST = (this.contrast !== 1.0);
  86622. defines.EXPOSURE = (this.exposure !== 1.0);
  86623. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  86624. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  86625. if (defines.COLORGRADING) {
  86626. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  86627. }
  86628. else {
  86629. defines.COLORGRADING3D = false;
  86630. }
  86631. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  86632. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  86633. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  86634. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  86635. };
  86636. /**
  86637. * Returns true if all the image processing information are ready.
  86638. * @returns True if ready, otherwise, false
  86639. */
  86640. ImageProcessingConfiguration.prototype.isReady = function () {
  86641. // Color Grading texure can not be none blocking.
  86642. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  86643. };
  86644. /**
  86645. * Binds the image processing to the shader.
  86646. * @param effect The effect to bind to
  86647. * @param aspectRatio Define the current aspect ratio of the effect
  86648. */
  86649. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  86650. if (aspectRatio === void 0) { aspectRatio = 1; }
  86651. // Color Curves
  86652. if (this._colorCurvesEnabled && this.colorCurves) {
  86653. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  86654. }
  86655. // Vignette
  86656. if (this._vignetteEnabled) {
  86657. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  86658. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  86659. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  86660. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  86661. var vignetteScaleX = vignetteScaleY * aspectRatio;
  86662. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  86663. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  86664. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  86665. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  86666. var vignettePower = -2.0 * this.vignetteWeight;
  86667. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  86668. }
  86669. // Exposure
  86670. effect.setFloat("exposureLinear", this.exposure);
  86671. // Contrast
  86672. effect.setFloat("contrast", this.contrast);
  86673. // Color transform settings
  86674. if (this.colorGradingTexture) {
  86675. effect.setTexture("txColorTransform", this.colorGradingTexture);
  86676. var textureSize = this.colorGradingTexture.getSize().height;
  86677. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  86678. 0.5 / textureSize, // textureOffset
  86679. textureSize, // textureSize
  86680. this.colorGradingTexture.level // weight
  86681. );
  86682. }
  86683. };
  86684. /**
  86685. * Clones the current image processing instance.
  86686. * @return The cloned image processing
  86687. */
  86688. ImageProcessingConfiguration.prototype.clone = function () {
  86689. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  86690. };
  86691. /**
  86692. * Serializes the current image processing instance to a json representation.
  86693. * @return a JSON representation
  86694. */
  86695. ImageProcessingConfiguration.prototype.serialize = function () {
  86696. return BABYLON.SerializationHelper.Serialize(this);
  86697. };
  86698. /**
  86699. * Parses the image processing from a json representation.
  86700. * @param source the JSON source to parse
  86701. * @return The parsed image processing
  86702. */
  86703. ImageProcessingConfiguration.Parse = function (source) {
  86704. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  86705. };
  86706. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  86707. /**
  86708. * Used to apply the vignette as a mix with the pixel color.
  86709. */
  86710. get: function () {
  86711. return this._VIGNETTEMODE_MULTIPLY;
  86712. },
  86713. enumerable: true,
  86714. configurable: true
  86715. });
  86716. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  86717. /**
  86718. * Used to apply the vignette as a replacement of the pixel color.
  86719. */
  86720. get: function () {
  86721. return this._VIGNETTEMODE_OPAQUE;
  86722. },
  86723. enumerable: true,
  86724. configurable: true
  86725. });
  86726. /**
  86727. * Default tone mapping applied in BabylonJS.
  86728. */
  86729. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  86730. /**
  86731. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  86732. * to other engines rendering to increase portability.
  86733. */
  86734. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  86735. // Static constants associated to the image processing.
  86736. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  86737. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  86738. __decorate([
  86739. BABYLON.serializeAsColorCurves()
  86740. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  86741. __decorate([
  86742. BABYLON.serialize()
  86743. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  86744. __decorate([
  86745. BABYLON.serializeAsTexture()
  86746. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  86747. __decorate([
  86748. BABYLON.serialize()
  86749. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  86750. __decorate([
  86751. BABYLON.serialize()
  86752. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  86753. __decorate([
  86754. BABYLON.serialize()
  86755. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  86756. __decorate([
  86757. BABYLON.serialize()
  86758. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  86759. __decorate([
  86760. BABYLON.serialize()
  86761. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  86762. __decorate([
  86763. BABYLON.serialize()
  86764. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  86765. __decorate([
  86766. BABYLON.serialize()
  86767. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  86768. __decorate([
  86769. BABYLON.serialize()
  86770. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  86771. __decorate([
  86772. BABYLON.serialize()
  86773. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  86774. __decorate([
  86775. BABYLON.serialize()
  86776. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  86777. __decorate([
  86778. BABYLON.serialize()
  86779. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  86780. __decorate([
  86781. BABYLON.serializeAsColor4()
  86782. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  86783. __decorate([
  86784. BABYLON.serialize()
  86785. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  86786. __decorate([
  86787. BABYLON.serialize()
  86788. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  86789. __decorate([
  86790. BABYLON.serialize()
  86791. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  86792. __decorate([
  86793. BABYLON.serialize()
  86794. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  86795. __decorate([
  86796. BABYLON.serialize()
  86797. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  86798. return ImageProcessingConfiguration;
  86799. }());
  86800. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  86801. })(BABYLON || (BABYLON = {}));
  86802. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  86803. var BABYLON;
  86804. (function (BABYLON) {
  86805. /**
  86806. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  86807. * It can help converting any input color in a desired output one. This can then be used to create effects
  86808. * from sepia, black and white to sixties or futuristic rendering...
  86809. *
  86810. * The only supported format is currently 3dl.
  86811. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  86812. */
  86813. var ColorGradingTexture = /** @class */ (function (_super) {
  86814. __extends(ColorGradingTexture, _super);
  86815. /**
  86816. * Instantiates a ColorGradingTexture from the following parameters.
  86817. *
  86818. * @param url The location of the color gradind data (currently only supporting 3dl)
  86819. * @param scene The scene the texture will be used in
  86820. */
  86821. function ColorGradingTexture(url, scene) {
  86822. var _this = _super.call(this, scene) || this;
  86823. if (!url) {
  86824. return _this;
  86825. }
  86826. _this._engine = scene.getEngine();
  86827. _this._textureMatrix = BABYLON.Matrix.Identity();
  86828. _this.name = url;
  86829. _this.url = url;
  86830. _this.hasAlpha = false;
  86831. _this.isCube = false;
  86832. _this.is3D = _this._engine.webGLVersion > 1;
  86833. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86834. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86835. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86836. _this.anisotropicFilteringLevel = 1;
  86837. _this._texture = _this._getFromCache(url, true);
  86838. if (!_this._texture) {
  86839. if (!scene.useDelayedTextureLoading) {
  86840. _this.loadTexture();
  86841. }
  86842. else {
  86843. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86844. }
  86845. }
  86846. return _this;
  86847. }
  86848. /**
  86849. * Returns the texture matrix used in most of the material.
  86850. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  86851. */
  86852. ColorGradingTexture.prototype.getTextureMatrix = function () {
  86853. return this._textureMatrix;
  86854. };
  86855. /**
  86856. * Occurs when the file being loaded is a .3dl LUT file.
  86857. */
  86858. ColorGradingTexture.prototype.load3dlTexture = function () {
  86859. var engine = this._engine;
  86860. var texture;
  86861. if (engine.webGLVersion === 1) {
  86862. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86863. }
  86864. else {
  86865. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86866. }
  86867. this._texture = texture;
  86868. var callback = function (text) {
  86869. if (typeof text !== "string") {
  86870. return;
  86871. }
  86872. var data = null;
  86873. var tempData = null;
  86874. var line;
  86875. var lines = text.split('\n');
  86876. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  86877. var maxColor = 0;
  86878. for (var i = 0; i < lines.length; i++) {
  86879. line = lines[i];
  86880. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  86881. continue;
  86882. if (line.indexOf('#') === 0)
  86883. continue;
  86884. var words = line.split(" ");
  86885. if (size === 0) {
  86886. // Number of space + one
  86887. size = words.length;
  86888. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  86889. tempData = new Float32Array(size * size * size * 4);
  86890. continue;
  86891. }
  86892. if (size != 0) {
  86893. var r = Math.max(parseInt(words[0]), 0);
  86894. var g = Math.max(parseInt(words[1]), 0);
  86895. var b = Math.max(parseInt(words[2]), 0);
  86896. maxColor = Math.max(r, maxColor);
  86897. maxColor = Math.max(g, maxColor);
  86898. maxColor = Math.max(b, maxColor);
  86899. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  86900. if (tempData) {
  86901. tempData[pixelStorageIndex + 0] = r;
  86902. tempData[pixelStorageIndex + 1] = g;
  86903. tempData[pixelStorageIndex + 2] = b;
  86904. }
  86905. pixelIndexSlice++;
  86906. if (pixelIndexSlice % size == 0) {
  86907. pixelIndexH++;
  86908. pixelIndexSlice = 0;
  86909. if (pixelIndexH % size == 0) {
  86910. pixelIndexW++;
  86911. pixelIndexH = 0;
  86912. }
  86913. }
  86914. }
  86915. }
  86916. if (tempData && data) {
  86917. for (var i = 0; i < tempData.length; i++) {
  86918. if (i > 0 && (i + 1) % 4 === 0) {
  86919. data[i] = 255;
  86920. }
  86921. else {
  86922. var value = tempData[i];
  86923. data[i] = (value / maxColor * 255);
  86924. }
  86925. }
  86926. }
  86927. if (texture.is3D) {
  86928. texture.updateSize(size, size, size);
  86929. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  86930. }
  86931. else {
  86932. texture.updateSize(size * size, size);
  86933. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  86934. }
  86935. };
  86936. var scene = this.getScene();
  86937. if (scene) {
  86938. scene._loadFile(this.url, callback);
  86939. }
  86940. else {
  86941. this._engine._loadFile(this.url, callback);
  86942. }
  86943. return this._texture;
  86944. };
  86945. /**
  86946. * Starts the loading process of the texture.
  86947. */
  86948. ColorGradingTexture.prototype.loadTexture = function () {
  86949. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  86950. this.load3dlTexture();
  86951. }
  86952. };
  86953. /**
  86954. * Clones the color gradind texture.
  86955. */
  86956. ColorGradingTexture.prototype.clone = function () {
  86957. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  86958. // Base texture
  86959. newTexture.level = this.level;
  86960. return newTexture;
  86961. };
  86962. /**
  86963. * Called during delayed load for textures.
  86964. */
  86965. ColorGradingTexture.prototype.delayLoad = function () {
  86966. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  86967. return;
  86968. }
  86969. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  86970. this._texture = this._getFromCache(this.url, true);
  86971. if (!this._texture) {
  86972. this.loadTexture();
  86973. }
  86974. };
  86975. /**
  86976. * Parses a color grading texture serialized by Babylon.
  86977. * @param parsedTexture The texture information being parsedTexture
  86978. * @param scene The scene to load the texture in
  86979. * @param rootUrl The root url of the data assets to load
  86980. * @return A color gradind texture
  86981. */
  86982. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  86983. var texture = null;
  86984. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  86985. texture = new ColorGradingTexture(parsedTexture.name, scene);
  86986. texture.name = parsedTexture.name;
  86987. texture.level = parsedTexture.level;
  86988. }
  86989. return texture;
  86990. };
  86991. /**
  86992. * Serializes the LUT texture to json format.
  86993. */
  86994. ColorGradingTexture.prototype.serialize = function () {
  86995. if (!this.name) {
  86996. return null;
  86997. }
  86998. var serializationObject = {};
  86999. serializationObject.name = this.name;
  87000. serializationObject.level = this.level;
  87001. serializationObject.customType = "BABYLON.ColorGradingTexture";
  87002. return serializationObject;
  87003. };
  87004. /**
  87005. * Empty line regex stored for GC.
  87006. */
  87007. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  87008. return ColorGradingTexture;
  87009. }(BABYLON.BaseTexture));
  87010. BABYLON.ColorGradingTexture = ColorGradingTexture;
  87011. })(BABYLON || (BABYLON = {}));
  87012. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  87013. var BABYLON;
  87014. (function (BABYLON) {
  87015. /**
  87016. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87017. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87018. * 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;
  87019. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87020. */
  87021. var ColorCurves = /** @class */ (function () {
  87022. function ColorCurves() {
  87023. this._dirty = true;
  87024. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  87025. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  87026. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  87027. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  87028. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  87029. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  87030. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  87031. this._globalHue = 30;
  87032. this._globalDensity = 0;
  87033. this._globalSaturation = 0;
  87034. this._globalExposure = 0;
  87035. this._highlightsHue = 30;
  87036. this._highlightsDensity = 0;
  87037. this._highlightsSaturation = 0;
  87038. this._highlightsExposure = 0;
  87039. this._midtonesHue = 30;
  87040. this._midtonesDensity = 0;
  87041. this._midtonesSaturation = 0;
  87042. this._midtonesExposure = 0;
  87043. this._shadowsHue = 30;
  87044. this._shadowsDensity = 0;
  87045. this._shadowsSaturation = 0;
  87046. this._shadowsExposure = 0;
  87047. }
  87048. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  87049. /**
  87050. * Gets the global Hue value.
  87051. * 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).
  87052. */
  87053. get: function () {
  87054. return this._globalHue;
  87055. },
  87056. /**
  87057. * Sets the global Hue value.
  87058. * 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).
  87059. */
  87060. set: function (value) {
  87061. this._globalHue = value;
  87062. this._dirty = true;
  87063. },
  87064. enumerable: true,
  87065. configurable: true
  87066. });
  87067. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  87068. /**
  87069. * Gets the global Density value.
  87070. * 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.
  87071. * Values less than zero provide a filter of opposite hue.
  87072. */
  87073. get: function () {
  87074. return this._globalDensity;
  87075. },
  87076. /**
  87077. * Sets the global Density value.
  87078. * 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.
  87079. * Values less than zero provide a filter of opposite hue.
  87080. */
  87081. set: function (value) {
  87082. this._globalDensity = value;
  87083. this._dirty = true;
  87084. },
  87085. enumerable: true,
  87086. configurable: true
  87087. });
  87088. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  87089. /**
  87090. * Gets the global Saturation value.
  87091. * 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.
  87092. */
  87093. get: function () {
  87094. return this._globalSaturation;
  87095. },
  87096. /**
  87097. * Sets the global Saturation value.
  87098. * 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.
  87099. */
  87100. set: function (value) {
  87101. this._globalSaturation = value;
  87102. this._dirty = true;
  87103. },
  87104. enumerable: true,
  87105. configurable: true
  87106. });
  87107. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  87108. /**
  87109. * Gets the global Exposure value.
  87110. * 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.
  87111. */
  87112. get: function () {
  87113. return this._globalExposure;
  87114. },
  87115. /**
  87116. * Sets the global Exposure value.
  87117. * 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.
  87118. */
  87119. set: function (value) {
  87120. this._globalExposure = value;
  87121. this._dirty = true;
  87122. },
  87123. enumerable: true,
  87124. configurable: true
  87125. });
  87126. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  87127. /**
  87128. * Gets the highlights Hue value.
  87129. * 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).
  87130. */
  87131. get: function () {
  87132. return this._highlightsHue;
  87133. },
  87134. /**
  87135. * Sets the highlights Hue value.
  87136. * 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).
  87137. */
  87138. set: function (value) {
  87139. this._highlightsHue = value;
  87140. this._dirty = true;
  87141. },
  87142. enumerable: true,
  87143. configurable: true
  87144. });
  87145. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  87146. /**
  87147. * Gets the highlights Density value.
  87148. * 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.
  87149. * Values less than zero provide a filter of opposite hue.
  87150. */
  87151. get: function () {
  87152. return this._highlightsDensity;
  87153. },
  87154. /**
  87155. * Sets the highlights Density value.
  87156. * 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.
  87157. * Values less than zero provide a filter of opposite hue.
  87158. */
  87159. set: function (value) {
  87160. this._highlightsDensity = value;
  87161. this._dirty = true;
  87162. },
  87163. enumerable: true,
  87164. configurable: true
  87165. });
  87166. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  87167. /**
  87168. * Gets the highlights Saturation value.
  87169. * 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.
  87170. */
  87171. get: function () {
  87172. return this._highlightsSaturation;
  87173. },
  87174. /**
  87175. * Sets the highlights Saturation value.
  87176. * 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.
  87177. */
  87178. set: function (value) {
  87179. this._highlightsSaturation = value;
  87180. this._dirty = true;
  87181. },
  87182. enumerable: true,
  87183. configurable: true
  87184. });
  87185. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  87186. /**
  87187. * Gets the highlights Exposure value.
  87188. * 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.
  87189. */
  87190. get: function () {
  87191. return this._highlightsExposure;
  87192. },
  87193. /**
  87194. * Sets the highlights Exposure value.
  87195. * 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.
  87196. */
  87197. set: function (value) {
  87198. this._highlightsExposure = value;
  87199. this._dirty = true;
  87200. },
  87201. enumerable: true,
  87202. configurable: true
  87203. });
  87204. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  87205. /**
  87206. * Gets the midtones Hue value.
  87207. * 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).
  87208. */
  87209. get: function () {
  87210. return this._midtonesHue;
  87211. },
  87212. /**
  87213. * Sets the midtones Hue value.
  87214. * 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).
  87215. */
  87216. set: function (value) {
  87217. this._midtonesHue = value;
  87218. this._dirty = true;
  87219. },
  87220. enumerable: true,
  87221. configurable: true
  87222. });
  87223. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  87224. /**
  87225. * Gets the midtones Density value.
  87226. * 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.
  87227. * Values less than zero provide a filter of opposite hue.
  87228. */
  87229. get: function () {
  87230. return this._midtonesDensity;
  87231. },
  87232. /**
  87233. * Sets the midtones Density value.
  87234. * 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.
  87235. * Values less than zero provide a filter of opposite hue.
  87236. */
  87237. set: function (value) {
  87238. this._midtonesDensity = value;
  87239. this._dirty = true;
  87240. },
  87241. enumerable: true,
  87242. configurable: true
  87243. });
  87244. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  87245. /**
  87246. * Gets the midtones Saturation value.
  87247. * 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.
  87248. */
  87249. get: function () {
  87250. return this._midtonesSaturation;
  87251. },
  87252. /**
  87253. * Sets the midtones Saturation value.
  87254. * 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.
  87255. */
  87256. set: function (value) {
  87257. this._midtonesSaturation = value;
  87258. this._dirty = true;
  87259. },
  87260. enumerable: true,
  87261. configurable: true
  87262. });
  87263. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  87264. /**
  87265. * Gets the midtones Exposure value.
  87266. * 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.
  87267. */
  87268. get: function () {
  87269. return this._midtonesExposure;
  87270. },
  87271. /**
  87272. * Sets the midtones Exposure value.
  87273. * 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.
  87274. */
  87275. set: function (value) {
  87276. this._midtonesExposure = value;
  87277. this._dirty = true;
  87278. },
  87279. enumerable: true,
  87280. configurable: true
  87281. });
  87282. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  87283. /**
  87284. * Gets the shadows Hue value.
  87285. * 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).
  87286. */
  87287. get: function () {
  87288. return this._shadowsHue;
  87289. },
  87290. /**
  87291. * Sets the shadows Hue value.
  87292. * 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).
  87293. */
  87294. set: function (value) {
  87295. this._shadowsHue = value;
  87296. this._dirty = true;
  87297. },
  87298. enumerable: true,
  87299. configurable: true
  87300. });
  87301. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  87302. /**
  87303. * Gets the shadows Density value.
  87304. * 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.
  87305. * Values less than zero provide a filter of opposite hue.
  87306. */
  87307. get: function () {
  87308. return this._shadowsDensity;
  87309. },
  87310. /**
  87311. * Sets the shadows Density value.
  87312. * 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.
  87313. * Values less than zero provide a filter of opposite hue.
  87314. */
  87315. set: function (value) {
  87316. this._shadowsDensity = value;
  87317. this._dirty = true;
  87318. },
  87319. enumerable: true,
  87320. configurable: true
  87321. });
  87322. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  87323. /**
  87324. * Gets the shadows Saturation value.
  87325. * 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.
  87326. */
  87327. get: function () {
  87328. return this._shadowsSaturation;
  87329. },
  87330. /**
  87331. * Sets the shadows Saturation value.
  87332. * 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.
  87333. */
  87334. set: function (value) {
  87335. this._shadowsSaturation = value;
  87336. this._dirty = true;
  87337. },
  87338. enumerable: true,
  87339. configurable: true
  87340. });
  87341. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  87342. /**
  87343. * Gets the shadows Exposure value.
  87344. * 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.
  87345. */
  87346. get: function () {
  87347. return this._shadowsExposure;
  87348. },
  87349. /**
  87350. * Sets the shadows Exposure value.
  87351. * 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.
  87352. */
  87353. set: function (value) {
  87354. this._shadowsExposure = value;
  87355. this._dirty = true;
  87356. },
  87357. enumerable: true,
  87358. configurable: true
  87359. });
  87360. /**
  87361. * Returns the class name
  87362. * @returns The class name
  87363. */
  87364. ColorCurves.prototype.getClassName = function () {
  87365. return "ColorCurves";
  87366. };
  87367. /**
  87368. * Binds the color curves to the shader.
  87369. * @param colorCurves The color curve to bind
  87370. * @param effect The effect to bind to
  87371. * @param positiveUniform The positive uniform shader parameter
  87372. * @param neutralUniform The neutral uniform shader parameter
  87373. * @param negativeUniform The negative uniform shader parameter
  87374. */
  87375. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  87376. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  87377. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  87378. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  87379. if (colorCurves._dirty) {
  87380. colorCurves._dirty = false;
  87381. // Fill in global info.
  87382. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  87383. // Compute highlights info.
  87384. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  87385. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  87386. // Compute midtones info.
  87387. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  87388. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  87389. // Compute shadows info.
  87390. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  87391. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  87392. // Compute deltas (neutral is midtones).
  87393. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  87394. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  87395. }
  87396. if (effect) {
  87397. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  87398. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  87399. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  87400. }
  87401. };
  87402. /**
  87403. * Prepare the list of uniforms associated with the ColorCurves effects.
  87404. * @param uniformsList The list of uniforms used in the effect
  87405. */
  87406. ColorCurves.PrepareUniforms = function (uniformsList) {
  87407. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  87408. };
  87409. /**
  87410. * Returns color grading data based on a hue, density, saturation and exposure value.
  87411. * @param filterHue The hue of the color filter.
  87412. * @param filterDensity The density of the color filter.
  87413. * @param saturation The saturation.
  87414. * @param exposure The exposure.
  87415. * @param result The result data container.
  87416. */
  87417. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  87418. if (hue == null) {
  87419. return;
  87420. }
  87421. hue = ColorCurves.clamp(hue, 0, 360);
  87422. density = ColorCurves.clamp(density, -100, 100);
  87423. saturation = ColorCurves.clamp(saturation, -100, 100);
  87424. exposure = ColorCurves.clamp(exposure, -100, 100);
  87425. // Remap the slider/config filter density with non-linear mapping and also scale by half
  87426. // so that the maximum filter density is only 50% control. This provides fine control
  87427. // for small values and reasonable range.
  87428. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  87429. density *= 0.5;
  87430. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  87431. if (density < 0) {
  87432. density *= -1;
  87433. hue = (hue + 180) % 360;
  87434. }
  87435. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  87436. result.scaleToRef(2, result);
  87437. result.a = 1 + 0.01 * saturation;
  87438. };
  87439. /**
  87440. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  87441. * @param value The input slider value in range [-100,100].
  87442. * @returns Adjusted value.
  87443. */
  87444. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  87445. value /= 100;
  87446. var x = Math.abs(value);
  87447. x = Math.pow(x, 2);
  87448. if (value < 0) {
  87449. x *= -1;
  87450. }
  87451. x *= 100;
  87452. return x;
  87453. };
  87454. /**
  87455. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  87456. * @param hue The hue (H) input.
  87457. * @param saturation The saturation (S) input.
  87458. * @param brightness The brightness (B) input.
  87459. * @result An RGBA color represented as Vector4.
  87460. */
  87461. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  87462. var h = ColorCurves.clamp(hue, 0, 360);
  87463. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  87464. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  87465. if (s === 0) {
  87466. result.r = v;
  87467. result.g = v;
  87468. result.b = v;
  87469. }
  87470. else {
  87471. // sector 0 to 5
  87472. h /= 60;
  87473. var i = Math.floor(h);
  87474. // fractional part of h
  87475. var f = h - i;
  87476. var p = v * (1 - s);
  87477. var q = v * (1 - s * f);
  87478. var t = v * (1 - s * (1 - f));
  87479. switch (i) {
  87480. case 0:
  87481. result.r = v;
  87482. result.g = t;
  87483. result.b = p;
  87484. break;
  87485. case 1:
  87486. result.r = q;
  87487. result.g = v;
  87488. result.b = p;
  87489. break;
  87490. case 2:
  87491. result.r = p;
  87492. result.g = v;
  87493. result.b = t;
  87494. break;
  87495. case 3:
  87496. result.r = p;
  87497. result.g = q;
  87498. result.b = v;
  87499. break;
  87500. case 4:
  87501. result.r = t;
  87502. result.g = p;
  87503. result.b = v;
  87504. break;
  87505. default: // case 5:
  87506. result.r = v;
  87507. result.g = p;
  87508. result.b = q;
  87509. break;
  87510. }
  87511. }
  87512. result.a = 1;
  87513. };
  87514. /**
  87515. * Returns a value clamped between min and max
  87516. * @param value The value to clamp
  87517. * @param min The minimum of value
  87518. * @param max The maximum of value
  87519. * @returns The clamped value.
  87520. */
  87521. ColorCurves.clamp = function (value, min, max) {
  87522. return Math.min(Math.max(value, min), max);
  87523. };
  87524. /**
  87525. * Clones the current color curve instance.
  87526. * @return The cloned curves
  87527. */
  87528. ColorCurves.prototype.clone = function () {
  87529. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  87530. };
  87531. /**
  87532. * Serializes the current color curve instance to a json representation.
  87533. * @return a JSON representation
  87534. */
  87535. ColorCurves.prototype.serialize = function () {
  87536. return BABYLON.SerializationHelper.Serialize(this);
  87537. };
  87538. /**
  87539. * Parses the color curve from a json representation.
  87540. * @param source the JSON source to parse
  87541. * @return The parsed curves
  87542. */
  87543. ColorCurves.Parse = function (source) {
  87544. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  87545. };
  87546. __decorate([
  87547. BABYLON.serialize()
  87548. ], ColorCurves.prototype, "_globalHue", void 0);
  87549. __decorate([
  87550. BABYLON.serialize()
  87551. ], ColorCurves.prototype, "_globalDensity", void 0);
  87552. __decorate([
  87553. BABYLON.serialize()
  87554. ], ColorCurves.prototype, "_globalSaturation", void 0);
  87555. __decorate([
  87556. BABYLON.serialize()
  87557. ], ColorCurves.prototype, "_globalExposure", void 0);
  87558. __decorate([
  87559. BABYLON.serialize()
  87560. ], ColorCurves.prototype, "_highlightsHue", void 0);
  87561. __decorate([
  87562. BABYLON.serialize()
  87563. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  87564. __decorate([
  87565. BABYLON.serialize()
  87566. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  87567. __decorate([
  87568. BABYLON.serialize()
  87569. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  87570. __decorate([
  87571. BABYLON.serialize()
  87572. ], ColorCurves.prototype, "_midtonesHue", void 0);
  87573. __decorate([
  87574. BABYLON.serialize()
  87575. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  87576. __decorate([
  87577. BABYLON.serialize()
  87578. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  87579. __decorate([
  87580. BABYLON.serialize()
  87581. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  87582. return ColorCurves;
  87583. }());
  87584. BABYLON.ColorCurves = ColorCurves;
  87585. })(BABYLON || (BABYLON = {}));
  87586. //# sourceMappingURL=babylon.colorCurves.js.map
  87587. var BABYLON;
  87588. (function (BABYLON) {
  87589. /**
  87590. * Post process which applies a refractin texture
  87591. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  87592. */
  87593. var RefractionPostProcess = /** @class */ (function (_super) {
  87594. __extends(RefractionPostProcess, _super);
  87595. /**
  87596. * Initializes the RefractionPostProcess
  87597. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  87598. * @param name The name of the effect.
  87599. * @param refractionTextureUrl Url of the refraction texture to use
  87600. * @param color the base color of the refraction (used to taint the rendering)
  87601. * @param depth simulated refraction depth
  87602. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  87603. * @param camera The camera to apply the render pass to.
  87604. * @param options The required width/height ratio to downsize to before computing the render pass.
  87605. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87606. * @param engine The engine which the post process will be applied. (default: current engine)
  87607. * @param reusable If the post process can be reused on the same frame. (default: false)
  87608. */
  87609. function RefractionPostProcess(name, refractionTextureUrl,
  87610. /** the base color of the refraction (used to taint the rendering) */
  87611. color,
  87612. /** simulated refraction depth */
  87613. depth,
  87614. /** the coefficient of the base color (0 to remove base color tainting) */
  87615. colorLevel, options, camera, samplingMode, engine, reusable) {
  87616. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  87617. _this.color = color;
  87618. _this.depth = depth;
  87619. _this.colorLevel = colorLevel;
  87620. _this._ownRefractionTexture = true;
  87621. _this.onActivateObservable.add(function (cam) {
  87622. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  87623. });
  87624. _this.onApplyObservable.add(function (effect) {
  87625. effect.setColor3("baseColor", _this.color);
  87626. effect.setFloat("depth", _this.depth);
  87627. effect.setFloat("colorLevel", _this.colorLevel);
  87628. effect.setTexture("refractionSampler", _this._refTexture);
  87629. });
  87630. return _this;
  87631. }
  87632. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  87633. /**
  87634. * Gets or sets the refraction texture
  87635. * Please note that you are responsible for disposing the texture if you set it manually
  87636. */
  87637. get: function () {
  87638. return this._refTexture;
  87639. },
  87640. set: function (value) {
  87641. if (this._refTexture && this._ownRefractionTexture) {
  87642. this._refTexture.dispose();
  87643. }
  87644. this._refTexture = value;
  87645. this._ownRefractionTexture = false;
  87646. },
  87647. enumerable: true,
  87648. configurable: true
  87649. });
  87650. // Methods
  87651. /**
  87652. * Disposes of the post process
  87653. * @param camera Camera to dispose post process on
  87654. */
  87655. RefractionPostProcess.prototype.dispose = function (camera) {
  87656. if (this._refTexture && this._ownRefractionTexture) {
  87657. this._refTexture.dispose();
  87658. this._refTexture = null;
  87659. }
  87660. _super.prototype.dispose.call(this, camera);
  87661. };
  87662. return RefractionPostProcess;
  87663. }(BABYLON.PostProcess));
  87664. BABYLON.RefractionPostProcess = RefractionPostProcess;
  87665. })(BABYLON || (BABYLON = {}));
  87666. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  87667. var BABYLON;
  87668. (function (BABYLON) {
  87669. /**
  87670. * Post process used to render in black and white
  87671. */
  87672. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  87673. __extends(BlackAndWhitePostProcess, _super);
  87674. /**
  87675. * Creates a black and white post process
  87676. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  87677. * @param name The name of the effect.
  87678. * @param options The required width/height ratio to downsize to before computing the render pass.
  87679. * @param camera The camera to apply the render pass to.
  87680. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87681. * @param engine The engine which the post process will be applied. (default: current engine)
  87682. * @param reusable If the post process can be reused on the same frame. (default: false)
  87683. */
  87684. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  87685. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  87686. /**
  87687. * Linear about to convert he result to black and white (default: 1)
  87688. */
  87689. _this.degree = 1;
  87690. _this.onApplyObservable.add(function (effect) {
  87691. effect.setFloat("degree", _this.degree);
  87692. });
  87693. return _this;
  87694. }
  87695. return BlackAndWhitePostProcess;
  87696. }(BABYLON.PostProcess));
  87697. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  87698. })(BABYLON || (BABYLON = {}));
  87699. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  87700. var BABYLON;
  87701. (function (BABYLON) {
  87702. /**
  87703. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  87704. * input texture to perform effects such as edge detection or sharpening
  87705. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  87706. */
  87707. var ConvolutionPostProcess = /** @class */ (function (_super) {
  87708. __extends(ConvolutionPostProcess, _super);
  87709. /**
  87710. * Creates a new instance ConvolutionPostProcess
  87711. * @param name The name of the effect.
  87712. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  87713. * @param options The required width/height ratio to downsize to before computing the render pass.
  87714. * @param camera The camera to apply the render pass to.
  87715. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87716. * @param engine The engine which the post process will be applied. (default: current engine)
  87717. * @param reusable If the post process can be reused on the same frame. (default: false)
  87718. * @param textureType Type of textures used when performing the post process. (default: 0)
  87719. */
  87720. function ConvolutionPostProcess(name,
  87721. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  87722. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  87723. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87724. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  87725. _this.kernel = kernel;
  87726. _this.onApply = function (effect) {
  87727. effect.setFloat2("screenSize", _this.width, _this.height);
  87728. effect.setArray("kernel", _this.kernel);
  87729. };
  87730. return _this;
  87731. }
  87732. // Statics
  87733. /**
  87734. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87735. */
  87736. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  87737. /**
  87738. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87739. */
  87740. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  87741. /**
  87742. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87743. */
  87744. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  87745. /**
  87746. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87747. */
  87748. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  87749. /**
  87750. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87751. */
  87752. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  87753. /**
  87754. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87755. */
  87756. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  87757. return ConvolutionPostProcess;
  87758. }(BABYLON.PostProcess));
  87759. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  87760. })(BABYLON || (BABYLON = {}));
  87761. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  87762. var BABYLON;
  87763. (function (BABYLON) {
  87764. /**
  87765. * Applies a kernel filter to the image
  87766. */
  87767. var FilterPostProcess = /** @class */ (function (_super) {
  87768. __extends(FilterPostProcess, _super);
  87769. /**
  87770. *
  87771. * @param name The name of the effect.
  87772. * @param kernelMatrix The matrix to be applied to the image
  87773. * @param options The required width/height ratio to downsize to before computing the render pass.
  87774. * @param camera The camera to apply the render pass to.
  87775. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87776. * @param engine The engine which the post process will be applied. (default: current engine)
  87777. * @param reusable If the post process can be reused on the same frame. (default: false)
  87778. */
  87779. function FilterPostProcess(name,
  87780. /** The matrix to be applied to the image */
  87781. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  87782. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  87783. _this.kernelMatrix = kernelMatrix;
  87784. _this.onApply = function (effect) {
  87785. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  87786. };
  87787. return _this;
  87788. }
  87789. return FilterPostProcess;
  87790. }(BABYLON.PostProcess));
  87791. BABYLON.FilterPostProcess = FilterPostProcess;
  87792. })(BABYLON || (BABYLON = {}));
  87793. //# sourceMappingURL=babylon.filterPostProcess.js.map
  87794. var BABYLON;
  87795. (function (BABYLON) {
  87796. /**
  87797. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  87798. */
  87799. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  87800. __extends(VolumetricLightScatteringPostProcess, _super);
  87801. /**
  87802. * @constructor
  87803. * @param {string} name - The post-process name
  87804. * @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)
  87805. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  87806. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  87807. * @param {number} samples - The post-process quality, default 100
  87808. * @param {number} samplingMode - The post-process filtering mode
  87809. * @param {BABYLON.Engine} engine - The babylon engine
  87810. * @param {boolean} reusable - If the post-process is reusable
  87811. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  87812. */
  87813. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  87814. if (samples === void 0) { samples = 100; }
  87815. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87816. 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;
  87817. _this._screenCoordinates = BABYLON.Vector2.Zero();
  87818. /**
  87819. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  87820. */
  87821. _this.customMeshPosition = BABYLON.Vector3.Zero();
  87822. /**
  87823. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  87824. */
  87825. _this.useCustomMeshPosition = false;
  87826. /**
  87827. * If the post-process should inverse the light scattering direction
  87828. */
  87829. _this.invert = true;
  87830. /**
  87831. * Array containing the excluded meshes not rendered in the internal pass
  87832. */
  87833. _this.excludedMeshes = new Array();
  87834. /**
  87835. * Controls the overall intensity of the post-process
  87836. */
  87837. _this.exposure = 0.3;
  87838. /**
  87839. * Dissipates each sample's contribution in range [0, 1]
  87840. */
  87841. _this.decay = 0.96815;
  87842. /**
  87843. * Controls the overall intensity of each sample
  87844. */
  87845. _this.weight = 0.58767;
  87846. /**
  87847. * Controls the density of each sample
  87848. */
  87849. _this.density = 0.926;
  87850. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  87851. engine = scene.getEngine();
  87852. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  87853. // Configure mesh
  87854. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  87855. // Configure
  87856. _this._createPass(scene, ratio.passRatio || ratio);
  87857. _this.onActivate = function (camera) {
  87858. if (!_this.isSupported) {
  87859. _this.dispose(camera);
  87860. }
  87861. _this.onActivate = null;
  87862. };
  87863. _this.onApplyObservable.add(function (effect) {
  87864. _this._updateMeshScreenCoordinates(scene);
  87865. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  87866. effect.setFloat("exposure", _this.exposure);
  87867. effect.setFloat("decay", _this.decay);
  87868. effect.setFloat("weight", _this.weight);
  87869. effect.setFloat("density", _this.density);
  87870. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  87871. });
  87872. return _this;
  87873. }
  87874. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  87875. /**
  87876. * @hidden
  87877. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  87878. */
  87879. get: function () {
  87880. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  87881. return false;
  87882. },
  87883. set: function (useDiffuseColor) {
  87884. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  87885. },
  87886. enumerable: true,
  87887. configurable: true
  87888. });
  87889. /**
  87890. * Returns the string "VolumetricLightScatteringPostProcess"
  87891. * @returns "VolumetricLightScatteringPostProcess"
  87892. */
  87893. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  87894. return "VolumetricLightScatteringPostProcess";
  87895. };
  87896. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  87897. var mesh = subMesh.getMesh();
  87898. // Render this.mesh as default
  87899. if (mesh === this.mesh && mesh.material) {
  87900. return mesh.material.isReady(mesh);
  87901. }
  87902. var defines = [];
  87903. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87904. var material = subMesh.getMaterial();
  87905. // Alpha test
  87906. if (material) {
  87907. if (material.needAlphaTesting()) {
  87908. defines.push("#define ALPHATEST");
  87909. }
  87910. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  87911. attribs.push(BABYLON.VertexBuffer.UVKind);
  87912. defines.push("#define UV1");
  87913. }
  87914. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  87915. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87916. defines.push("#define UV2");
  87917. }
  87918. }
  87919. // Bones
  87920. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  87921. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  87922. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  87923. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  87924. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  87925. }
  87926. else {
  87927. defines.push("#define NUM_BONE_INFLUENCERS 0");
  87928. }
  87929. // Instances
  87930. if (useInstances) {
  87931. defines.push("#define INSTANCES");
  87932. attribs.push("world0");
  87933. attribs.push("world1");
  87934. attribs.push("world2");
  87935. attribs.push("world3");
  87936. }
  87937. // Get correct effect
  87938. var join = defines.join("\n");
  87939. if (this._cachedDefines !== join) {
  87940. this._cachedDefines = join;
  87941. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  87942. }
  87943. return this._volumetricLightScatteringPass.isReady();
  87944. };
  87945. /**
  87946. * Sets the new light position for light scattering effect
  87947. * @param position The new custom light position
  87948. */
  87949. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  87950. this.customMeshPosition = position;
  87951. };
  87952. /**
  87953. * Returns the light position for light scattering effect
  87954. * @return {BABYLON.Vector3} The custom light position
  87955. */
  87956. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  87957. return this.customMeshPosition;
  87958. };
  87959. /**
  87960. * Disposes the internal assets and detaches the post-process from the camera
  87961. */
  87962. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  87963. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  87964. if (rttIndex !== -1) {
  87965. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  87966. }
  87967. this._volumetricLightScatteringRTT.dispose();
  87968. _super.prototype.dispose.call(this, camera);
  87969. };
  87970. /**
  87971. * Returns the render target texture used by the post-process
  87972. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  87973. */
  87974. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  87975. return this._volumetricLightScatteringRTT;
  87976. };
  87977. // Private methods
  87978. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  87979. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  87980. return true;
  87981. }
  87982. return false;
  87983. };
  87984. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  87985. var _this = this;
  87986. var engine = scene.getEngine();
  87987. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87988. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87989. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87990. this._volumetricLightScatteringRTT.renderList = null;
  87991. this._volumetricLightScatteringRTT.renderParticles = false;
  87992. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  87993. var camera = this.getCamera();
  87994. if (camera) {
  87995. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  87996. }
  87997. else {
  87998. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  87999. }
  88000. // Custom render function for submeshes
  88001. var renderSubMesh = function (subMesh) {
  88002. var mesh = subMesh.getRenderingMesh();
  88003. if (_this._meshExcluded(mesh)) {
  88004. return;
  88005. }
  88006. var material = subMesh.getMaterial();
  88007. if (!material) {
  88008. return;
  88009. }
  88010. var scene = mesh.getScene();
  88011. var engine = scene.getEngine();
  88012. // Culling
  88013. engine.setState(material.backFaceCulling);
  88014. // Managing instances
  88015. var batch = mesh._getInstancesRenderList(subMesh._id);
  88016. if (batch.mustReturn) {
  88017. return;
  88018. }
  88019. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  88020. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  88021. var effect = _this._volumetricLightScatteringPass;
  88022. if (mesh === _this.mesh) {
  88023. if (subMesh.effect) {
  88024. effect = subMesh.effect;
  88025. }
  88026. else {
  88027. effect = material.getEffect();
  88028. }
  88029. }
  88030. engine.enableEffect(effect);
  88031. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  88032. if (mesh === _this.mesh) {
  88033. material.bind(mesh.getWorldMatrix(), mesh);
  88034. }
  88035. else {
  88036. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  88037. // Alpha test
  88038. if (material && material.needAlphaTesting()) {
  88039. var alphaTexture = material.getAlphaTestTexture();
  88040. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  88041. if (alphaTexture) {
  88042. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  88043. }
  88044. }
  88045. // Bones
  88046. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  88047. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  88048. }
  88049. }
  88050. // Draw
  88051. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  88052. }
  88053. };
  88054. // Render target texture callbacks
  88055. var savedSceneClearColor;
  88056. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  88057. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  88058. savedSceneClearColor = scene.clearColor;
  88059. scene.clearColor = sceneClearColor;
  88060. });
  88061. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  88062. scene.clearColor = savedSceneClearColor;
  88063. });
  88064. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  88065. var engine = scene.getEngine();
  88066. var index;
  88067. if (depthOnlySubMeshes.length) {
  88068. engine.setColorWrite(false);
  88069. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  88070. renderSubMesh(depthOnlySubMeshes.data[index]);
  88071. }
  88072. engine.setColorWrite(true);
  88073. }
  88074. for (index = 0; index < opaqueSubMeshes.length; index++) {
  88075. renderSubMesh(opaqueSubMeshes.data[index]);
  88076. }
  88077. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  88078. renderSubMesh(alphaTestSubMeshes.data[index]);
  88079. }
  88080. if (transparentSubMeshes.length) {
  88081. // Sort sub meshes
  88082. for (index = 0; index < transparentSubMeshes.length; index++) {
  88083. var submesh = transparentSubMeshes.data[index];
  88084. var boundingInfo = submesh.getBoundingInfo();
  88085. if (boundingInfo && scene.activeCamera) {
  88086. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  88087. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  88088. }
  88089. }
  88090. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  88091. sortedArray.sort(function (a, b) {
  88092. // Alpha index first
  88093. if (a._alphaIndex > b._alphaIndex) {
  88094. return 1;
  88095. }
  88096. if (a._alphaIndex < b._alphaIndex) {
  88097. return -1;
  88098. }
  88099. // Then distance to camera
  88100. if (a._distanceToCamera < b._distanceToCamera) {
  88101. return 1;
  88102. }
  88103. if (a._distanceToCamera > b._distanceToCamera) {
  88104. return -1;
  88105. }
  88106. return 0;
  88107. });
  88108. // Render sub meshes
  88109. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  88110. for (index = 0; index < sortedArray.length; index++) {
  88111. renderSubMesh(sortedArray[index]);
  88112. }
  88113. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88114. }
  88115. };
  88116. };
  88117. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  88118. var transform = scene.getTransformMatrix();
  88119. var meshPosition;
  88120. if (this.useCustomMeshPosition) {
  88121. meshPosition = this.customMeshPosition;
  88122. }
  88123. else if (this.attachedNode) {
  88124. meshPosition = this.attachedNode.position;
  88125. }
  88126. else {
  88127. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  88128. }
  88129. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  88130. this._screenCoordinates.x = pos.x / this._viewPort.width;
  88131. this._screenCoordinates.y = pos.y / this._viewPort.height;
  88132. if (this.invert)
  88133. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  88134. };
  88135. // Static methods
  88136. /**
  88137. * Creates a default mesh for the Volumeric Light Scattering post-process
  88138. * @param name The mesh name
  88139. * @param scene The scene where to create the mesh
  88140. * @return {BABYLON.Mesh} the default mesh
  88141. */
  88142. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  88143. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  88144. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  88145. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  88146. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  88147. mesh.material = material;
  88148. return mesh;
  88149. };
  88150. __decorate([
  88151. BABYLON.serializeAsVector3()
  88152. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  88153. __decorate([
  88154. BABYLON.serialize()
  88155. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  88156. __decorate([
  88157. BABYLON.serialize()
  88158. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  88159. __decorate([
  88160. BABYLON.serializeAsMeshReference()
  88161. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  88162. __decorate([
  88163. BABYLON.serialize()
  88164. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  88165. __decorate([
  88166. BABYLON.serialize()
  88167. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  88168. __decorate([
  88169. BABYLON.serialize()
  88170. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  88171. __decorate([
  88172. BABYLON.serialize()
  88173. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  88174. __decorate([
  88175. BABYLON.serialize()
  88176. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  88177. return VolumetricLightScatteringPostProcess;
  88178. }(BABYLON.PostProcess));
  88179. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  88180. })(BABYLON || (BABYLON = {}));
  88181. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  88182. var BABYLON;
  88183. (function (BABYLON) {
  88184. /**
  88185. *
  88186. * This post-process allows the modification of rendered colors by using
  88187. * a 'look-up table' (LUT). This effect is also called Color Grading.
  88188. *
  88189. * The object needs to be provided an url to a texture containing the color
  88190. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  88191. * Use an image editing software to tweak the LUT to match your needs.
  88192. *
  88193. * For an example of a color LUT, see here:
  88194. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  88195. * For explanations on color grading, see here:
  88196. * @see http://udn.epicgames.com/Three/ColorGrading.html
  88197. *
  88198. */
  88199. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  88200. __extends(ColorCorrectionPostProcess, _super);
  88201. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  88202. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  88203. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  88204. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  88205. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88206. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88207. _this.onApply = function (effect) {
  88208. effect.setTexture("colorTable", _this._colorTableTexture);
  88209. };
  88210. return _this;
  88211. }
  88212. return ColorCorrectionPostProcess;
  88213. }(BABYLON.PostProcess));
  88214. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  88215. })(BABYLON || (BABYLON = {}));
  88216. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  88217. var BABYLON;
  88218. (function (BABYLON) {
  88219. /** Defines operator used for tonemapping */
  88220. var TonemappingOperator;
  88221. (function (TonemappingOperator) {
  88222. /** Hable */
  88223. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  88224. /** Reinhard */
  88225. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  88226. /** HejiDawson */
  88227. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  88228. /** Photographic */
  88229. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  88230. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  88231. ;
  88232. /**
  88233. * Defines a post process to apply tone mapping
  88234. */
  88235. var TonemapPostProcess = /** @class */ (function (_super) {
  88236. __extends(TonemapPostProcess, _super);
  88237. /**
  88238. * Creates a new TonemapPostProcess
  88239. * @param name defines the name of the postprocess
  88240. * @param _operator defines the operator to use
  88241. * @param exposureAdjustment defines the required exposure adjustement
  88242. * @param camera defines the camera to use (can be null)
  88243. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  88244. * @param engine defines the hosting engine (can be ignore if camera is set)
  88245. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  88246. */
  88247. function TonemapPostProcess(name, _operator,
  88248. /** Defines the required exposure adjustement */
  88249. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  88250. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  88251. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88252. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  88253. _this._operator = _operator;
  88254. _this.exposureAdjustment = exposureAdjustment;
  88255. var defines = "#define ";
  88256. if (_this._operator === TonemappingOperator.Hable)
  88257. defines += "HABLE_TONEMAPPING";
  88258. else if (_this._operator === TonemappingOperator.Reinhard)
  88259. defines += "REINHARD_TONEMAPPING";
  88260. else if (_this._operator === TonemappingOperator.HejiDawson)
  88261. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  88262. else if (_this._operator === TonemappingOperator.Photographic)
  88263. defines += "PHOTOGRAPHIC_TONEMAPPING";
  88264. //sadly a second call to create the effect.
  88265. _this.updateEffect(defines);
  88266. _this.onApply = function (effect) {
  88267. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  88268. };
  88269. return _this;
  88270. }
  88271. return TonemapPostProcess;
  88272. }(BABYLON.PostProcess));
  88273. BABYLON.TonemapPostProcess = TonemapPostProcess;
  88274. })(BABYLON || (BABYLON = {}));
  88275. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  88276. var BABYLON;
  88277. (function (BABYLON) {
  88278. /**
  88279. * DisplayPassPostProcess which produces an output the same as it's input
  88280. */
  88281. var DisplayPassPostProcess = /** @class */ (function (_super) {
  88282. __extends(DisplayPassPostProcess, _super);
  88283. /**
  88284. * Creates the DisplayPassPostProcess
  88285. * @param name The name of the effect.
  88286. * @param options The required width/height ratio to downsize to before computing the render pass.
  88287. * @param camera The camera to apply the render pass to.
  88288. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88289. * @param engine The engine which the post process will be applied. (default: current engine)
  88290. * @param reusable If the post process can be reused on the same frame. (default: false)
  88291. */
  88292. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  88293. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  88294. }
  88295. return DisplayPassPostProcess;
  88296. }(BABYLON.PostProcess));
  88297. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  88298. })(BABYLON || (BABYLON = {}));
  88299. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  88300. var BABYLON;
  88301. (function (BABYLON) {
  88302. /**
  88303. * Extracts highlights from the image
  88304. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  88305. */
  88306. var HighlightsPostProcess = /** @class */ (function (_super) {
  88307. __extends(HighlightsPostProcess, _super);
  88308. /**
  88309. * Extracts highlights from the image
  88310. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  88311. * @param name The name of the effect.
  88312. * @param options The required width/height ratio to downsize to before computing the render pass.
  88313. * @param camera The camera to apply the render pass to.
  88314. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88315. * @param engine The engine which the post process will be applied. (default: current engine)
  88316. * @param reusable If the post process can be reused on the same frame. (default: false)
  88317. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  88318. */
  88319. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  88320. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88321. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  88322. }
  88323. return HighlightsPostProcess;
  88324. }(BABYLON.PostProcess));
  88325. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  88326. })(BABYLON || (BABYLON = {}));
  88327. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  88328. var BABYLON;
  88329. (function (BABYLON) {
  88330. /**
  88331. * ImageProcessingPostProcess
  88332. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  88333. */
  88334. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  88335. __extends(ImageProcessingPostProcess, _super);
  88336. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  88337. if (camera === void 0) { camera = null; }
  88338. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88339. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  88340. _this._fromLinearSpace = true;
  88341. /**
  88342. * Defines cache preventing GC.
  88343. */
  88344. _this._defines = {
  88345. IMAGEPROCESSING: false,
  88346. VIGNETTE: false,
  88347. VIGNETTEBLENDMODEMULTIPLY: false,
  88348. VIGNETTEBLENDMODEOPAQUE: false,
  88349. TONEMAPPING: false,
  88350. TONEMAPPING_ACES: false,
  88351. CONTRAST: false,
  88352. COLORCURVES: false,
  88353. COLORGRADING: false,
  88354. COLORGRADING3D: false,
  88355. FROMLINEARSPACE: false,
  88356. SAMPLER3DGREENDEPTH: false,
  88357. SAMPLER3DBGRMAP: false,
  88358. IMAGEPROCESSINGPOSTPROCESS: false,
  88359. EXPOSURE: false,
  88360. };
  88361. // Setup the configuration as forced by the constructor. This would then not force the
  88362. // scene materials output in linear space and let untouched the default forward pass.
  88363. if (imageProcessingConfiguration) {
  88364. imageProcessingConfiguration.applyByPostProcess = true;
  88365. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  88366. // This will cause the shader to be compiled
  88367. _this.fromLinearSpace = false;
  88368. }
  88369. // Setup the default processing configuration to the scene.
  88370. else {
  88371. _this._attachImageProcessingConfiguration(null, true);
  88372. _this.imageProcessingConfiguration.applyByPostProcess = true;
  88373. }
  88374. _this.onApply = function (effect) {
  88375. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  88376. };
  88377. return _this;
  88378. }
  88379. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  88380. /**
  88381. * Gets the image processing configuration used either in this material.
  88382. */
  88383. get: function () {
  88384. return this._imageProcessingConfiguration;
  88385. },
  88386. /**
  88387. * Sets the Default image processing configuration used either in the this material.
  88388. *
  88389. * If sets to null, the scene one is in use.
  88390. */
  88391. set: function (value) {
  88392. this._attachImageProcessingConfiguration(value);
  88393. },
  88394. enumerable: true,
  88395. configurable: true
  88396. });
  88397. /**
  88398. * Attaches a new image processing configuration to the PBR Material.
  88399. * @param configuration
  88400. */
  88401. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  88402. var _this = this;
  88403. if (doNotBuild === void 0) { doNotBuild = false; }
  88404. if (configuration === this._imageProcessingConfiguration) {
  88405. return;
  88406. }
  88407. // Detaches observer.
  88408. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88409. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88410. }
  88411. // Pick the scene configuration if needed.
  88412. if (!configuration) {
  88413. var scene = null;
  88414. var engine = this.getEngine();
  88415. var camera = this.getCamera();
  88416. if (camera) {
  88417. scene = camera.getScene();
  88418. }
  88419. else if (engine && engine.scenes) {
  88420. var scenes = engine.scenes;
  88421. scene = scenes[scenes.length - 1];
  88422. }
  88423. else {
  88424. scene = BABYLON.Engine.LastCreatedScene;
  88425. }
  88426. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  88427. }
  88428. else {
  88429. this._imageProcessingConfiguration = configuration;
  88430. }
  88431. // Attaches observer.
  88432. if (this._imageProcessingConfiguration) {
  88433. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88434. _this._updateParameters();
  88435. });
  88436. }
  88437. // Ensure the effect will be rebuilt.
  88438. if (!doNotBuild) {
  88439. this._updateParameters();
  88440. }
  88441. };
  88442. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  88443. /**
  88444. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  88445. */
  88446. get: function () {
  88447. return this.imageProcessingConfiguration.colorCurves;
  88448. },
  88449. /**
  88450. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  88451. */
  88452. set: function (value) {
  88453. this.imageProcessingConfiguration.colorCurves = value;
  88454. },
  88455. enumerable: true,
  88456. configurable: true
  88457. });
  88458. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  88459. /**
  88460. * Gets wether the color curves effect is enabled.
  88461. */
  88462. get: function () {
  88463. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88464. },
  88465. /**
  88466. * Sets wether the color curves effect is enabled.
  88467. */
  88468. set: function (value) {
  88469. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88470. },
  88471. enumerable: true,
  88472. configurable: true
  88473. });
  88474. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  88475. /**
  88476. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  88477. */
  88478. get: function () {
  88479. return this.imageProcessingConfiguration.colorGradingTexture;
  88480. },
  88481. /**
  88482. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  88483. */
  88484. set: function (value) {
  88485. this.imageProcessingConfiguration.colorGradingTexture = value;
  88486. },
  88487. enumerable: true,
  88488. configurable: true
  88489. });
  88490. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  88491. /**
  88492. * Gets wether the color grading effect is enabled.
  88493. */
  88494. get: function () {
  88495. return this.imageProcessingConfiguration.colorGradingEnabled;
  88496. },
  88497. /**
  88498. * Gets wether the color grading effect is enabled.
  88499. */
  88500. set: function (value) {
  88501. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88502. },
  88503. enumerable: true,
  88504. configurable: true
  88505. });
  88506. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  88507. /**
  88508. * Gets exposure used in the effect.
  88509. */
  88510. get: function () {
  88511. return this.imageProcessingConfiguration.exposure;
  88512. },
  88513. /**
  88514. * Sets exposure used in the effect.
  88515. */
  88516. set: function (value) {
  88517. this.imageProcessingConfiguration.exposure = value;
  88518. },
  88519. enumerable: true,
  88520. configurable: true
  88521. });
  88522. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  88523. /**
  88524. * Gets wether tonemapping is enabled or not.
  88525. */
  88526. get: function () {
  88527. return this._imageProcessingConfiguration.toneMappingEnabled;
  88528. },
  88529. /**
  88530. * Sets wether tonemapping is enabled or not
  88531. */
  88532. set: function (value) {
  88533. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88534. },
  88535. enumerable: true,
  88536. configurable: true
  88537. });
  88538. ;
  88539. ;
  88540. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  88541. /**
  88542. * Gets contrast used in the effect.
  88543. */
  88544. get: function () {
  88545. return this.imageProcessingConfiguration.contrast;
  88546. },
  88547. /**
  88548. * Sets contrast used in the effect.
  88549. */
  88550. set: function (value) {
  88551. this.imageProcessingConfiguration.contrast = value;
  88552. },
  88553. enumerable: true,
  88554. configurable: true
  88555. });
  88556. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  88557. /**
  88558. * Gets Vignette stretch size.
  88559. */
  88560. get: function () {
  88561. return this.imageProcessingConfiguration.vignetteStretch;
  88562. },
  88563. /**
  88564. * Sets Vignette stretch size.
  88565. */
  88566. set: function (value) {
  88567. this.imageProcessingConfiguration.vignetteStretch = value;
  88568. },
  88569. enumerable: true,
  88570. configurable: true
  88571. });
  88572. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  88573. /**
  88574. * Gets Vignette centre X Offset.
  88575. */
  88576. get: function () {
  88577. return this.imageProcessingConfiguration.vignetteCentreX;
  88578. },
  88579. /**
  88580. * Sets Vignette centre X Offset.
  88581. */
  88582. set: function (value) {
  88583. this.imageProcessingConfiguration.vignetteCentreX = value;
  88584. },
  88585. enumerable: true,
  88586. configurable: true
  88587. });
  88588. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  88589. /**
  88590. * Gets Vignette centre Y Offset.
  88591. */
  88592. get: function () {
  88593. return this.imageProcessingConfiguration.vignetteCentreY;
  88594. },
  88595. /**
  88596. * Sets Vignette centre Y Offset.
  88597. */
  88598. set: function (value) {
  88599. this.imageProcessingConfiguration.vignetteCentreY = value;
  88600. },
  88601. enumerable: true,
  88602. configurable: true
  88603. });
  88604. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  88605. /**
  88606. * Gets Vignette weight or intensity of the vignette effect.
  88607. */
  88608. get: function () {
  88609. return this.imageProcessingConfiguration.vignetteWeight;
  88610. },
  88611. /**
  88612. * Sets Vignette weight or intensity of the vignette effect.
  88613. */
  88614. set: function (value) {
  88615. this.imageProcessingConfiguration.vignetteWeight = value;
  88616. },
  88617. enumerable: true,
  88618. configurable: true
  88619. });
  88620. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  88621. /**
  88622. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88623. * if vignetteEnabled is set to true.
  88624. */
  88625. get: function () {
  88626. return this.imageProcessingConfiguration.vignetteColor;
  88627. },
  88628. /**
  88629. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88630. * if vignetteEnabled is set to true.
  88631. */
  88632. set: function (value) {
  88633. this.imageProcessingConfiguration.vignetteColor = value;
  88634. },
  88635. enumerable: true,
  88636. configurable: true
  88637. });
  88638. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  88639. /**
  88640. * Gets Camera field of view used by the Vignette effect.
  88641. */
  88642. get: function () {
  88643. return this.imageProcessingConfiguration.vignetteCameraFov;
  88644. },
  88645. /**
  88646. * Sets Camera field of view used by the Vignette effect.
  88647. */
  88648. set: function (value) {
  88649. this.imageProcessingConfiguration.vignetteCameraFov = value;
  88650. },
  88651. enumerable: true,
  88652. configurable: true
  88653. });
  88654. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  88655. /**
  88656. * Gets the vignette blend mode allowing different kind of effect.
  88657. */
  88658. get: function () {
  88659. return this.imageProcessingConfiguration.vignetteBlendMode;
  88660. },
  88661. /**
  88662. * Sets the vignette blend mode allowing different kind of effect.
  88663. */
  88664. set: function (value) {
  88665. this.imageProcessingConfiguration.vignetteBlendMode = value;
  88666. },
  88667. enumerable: true,
  88668. configurable: true
  88669. });
  88670. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  88671. /**
  88672. * Gets wether the vignette effect is enabled.
  88673. */
  88674. get: function () {
  88675. return this.imageProcessingConfiguration.vignetteEnabled;
  88676. },
  88677. /**
  88678. * Sets wether the vignette effect is enabled.
  88679. */
  88680. set: function (value) {
  88681. this.imageProcessingConfiguration.vignetteEnabled = value;
  88682. },
  88683. enumerable: true,
  88684. configurable: true
  88685. });
  88686. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  88687. /**
  88688. * Gets wether the input of the processing is in Gamma or Linear Space.
  88689. */
  88690. get: function () {
  88691. return this._fromLinearSpace;
  88692. },
  88693. /**
  88694. * Sets wether the input of the processing is in Gamma or Linear Space.
  88695. */
  88696. set: function (value) {
  88697. if (this._fromLinearSpace === value) {
  88698. return;
  88699. }
  88700. this._fromLinearSpace = value;
  88701. this._updateParameters();
  88702. },
  88703. enumerable: true,
  88704. configurable: true
  88705. });
  88706. /**
  88707. * "ImageProcessingPostProcess"
  88708. * @returns "ImageProcessingPostProcess"
  88709. */
  88710. ImageProcessingPostProcess.prototype.getClassName = function () {
  88711. return "ImageProcessingPostProcess";
  88712. };
  88713. ImageProcessingPostProcess.prototype._updateParameters = function () {
  88714. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  88715. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  88716. var defines = "";
  88717. for (var define in this._defines) {
  88718. if (this._defines[define]) {
  88719. defines += "#define " + define + ";\r\n";
  88720. }
  88721. }
  88722. var samplers = ["textureSampler"];
  88723. var uniforms = ["scale"];
  88724. if (BABYLON.ImageProcessingConfiguration) {
  88725. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  88726. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  88727. }
  88728. this.updateEffect(defines, uniforms, samplers);
  88729. };
  88730. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  88731. _super.prototype.dispose.call(this, camera);
  88732. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88733. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88734. }
  88735. if (this._imageProcessingConfiguration) {
  88736. this.imageProcessingConfiguration.applyByPostProcess = false;
  88737. }
  88738. };
  88739. __decorate([
  88740. BABYLON.serialize()
  88741. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  88742. return ImageProcessingPostProcess;
  88743. }(BABYLON.PostProcess));
  88744. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  88745. })(BABYLON || (BABYLON = {}));
  88746. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  88747. var BABYLON;
  88748. (function (BABYLON) {
  88749. /**
  88750. * Class used to store bone information
  88751. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  88752. */
  88753. var Bone = /** @class */ (function (_super) {
  88754. __extends(Bone, _super);
  88755. /**
  88756. * Create a new bone
  88757. * @param name defines the bone name
  88758. * @param skeleton defines the parent skeleton
  88759. * @param parentBone defines the parent (can be null if the bone is the root)
  88760. * @param localMatrix defines the local matrix
  88761. * @param restPose defines the rest pose matrix
  88762. * @param baseMatrix defines the base matrix
  88763. * @param index defines index of the bone in the hiearchy
  88764. */
  88765. function Bone(
  88766. /**
  88767. * defines the bone name
  88768. */
  88769. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  88770. if (parentBone === void 0) { parentBone = null; }
  88771. if (localMatrix === void 0) { localMatrix = null; }
  88772. if (restPose === void 0) { restPose = null; }
  88773. if (baseMatrix === void 0) { baseMatrix = null; }
  88774. if (index === void 0) { index = null; }
  88775. var _this = _super.call(this, name, skeleton.getScene()) || this;
  88776. _this.name = name;
  88777. /**
  88778. * Gets the list of child bones
  88779. */
  88780. _this.children = new Array();
  88781. /** Gets the animations associated with this bone */
  88782. _this.animations = new Array();
  88783. /**
  88784. * @hidden Internal only
  88785. * Set this value to map this bone to a different index in the transform matrices
  88786. * Set this value to -1 to exclude the bone from the transform matrices
  88787. */
  88788. _this._index = null;
  88789. _this._absoluteTransform = new BABYLON.Matrix();
  88790. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  88791. _this._scalingDeterminant = 1;
  88792. _this._worldTransform = new BABYLON.Matrix();
  88793. _this._needToDecompose = true;
  88794. _this._needToCompose = false;
  88795. _this._skeleton = skeleton;
  88796. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  88797. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  88798. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  88799. _this._index = index;
  88800. skeleton.bones.push(_this);
  88801. _this.setParent(parentBone, false);
  88802. if (baseMatrix || localMatrix) {
  88803. _this._updateDifferenceMatrix();
  88804. }
  88805. return _this;
  88806. }
  88807. Object.defineProperty(Bone.prototype, "_matrix", {
  88808. /** @hidden */
  88809. get: function () {
  88810. this._compose();
  88811. return this._localMatrix;
  88812. },
  88813. /** @hidden */
  88814. set: function (value) {
  88815. this._localMatrix.copyFrom(value);
  88816. this._needToDecompose = true;
  88817. },
  88818. enumerable: true,
  88819. configurable: true
  88820. });
  88821. // Members
  88822. /**
  88823. * Gets the parent skeleton
  88824. * @returns a skeleton
  88825. */
  88826. Bone.prototype.getSkeleton = function () {
  88827. return this._skeleton;
  88828. };
  88829. /**
  88830. * Gets parent bone
  88831. * @returns a bone or null if the bone is the root of the bone hierarchy
  88832. */
  88833. Bone.prototype.getParent = function () {
  88834. return this._parent;
  88835. };
  88836. /**
  88837. * Sets the parent bone
  88838. * @param parent defines the parent (can be null if the bone is the root)
  88839. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  88840. */
  88841. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  88842. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  88843. if (this._parent === parent) {
  88844. return;
  88845. }
  88846. if (this._parent) {
  88847. var index = this._parent.children.indexOf(this);
  88848. if (index !== -1) {
  88849. this._parent.children.splice(index, 1);
  88850. }
  88851. }
  88852. this._parent = parent;
  88853. if (this._parent) {
  88854. this._parent.children.push(this);
  88855. }
  88856. if (updateDifferenceMatrix) {
  88857. this._updateDifferenceMatrix();
  88858. }
  88859. this.markAsDirty();
  88860. };
  88861. /**
  88862. * Gets the local matrix
  88863. * @returns a matrix
  88864. */
  88865. Bone.prototype.getLocalMatrix = function () {
  88866. this._compose();
  88867. return this._localMatrix;
  88868. };
  88869. /**
  88870. * Gets the base matrix (initial matrix which remains unchanged)
  88871. * @returns a matrix
  88872. */
  88873. Bone.prototype.getBaseMatrix = function () {
  88874. return this._baseMatrix;
  88875. };
  88876. /**
  88877. * Gets the rest pose matrix
  88878. * @returns a matrix
  88879. */
  88880. Bone.prototype.getRestPose = function () {
  88881. return this._restPose;
  88882. };
  88883. /**
  88884. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  88885. */
  88886. Bone.prototype.getWorldMatrix = function () {
  88887. return this._worldTransform;
  88888. };
  88889. /**
  88890. * Sets the local matrix to rest pose matrix
  88891. */
  88892. Bone.prototype.returnToRest = function () {
  88893. this.updateMatrix(this._restPose.clone());
  88894. };
  88895. /**
  88896. * Gets the inverse of the absolute transform matrix.
  88897. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  88898. * @returns a matrix
  88899. */
  88900. Bone.prototype.getInvertedAbsoluteTransform = function () {
  88901. return this._invertedAbsoluteTransform;
  88902. };
  88903. /**
  88904. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  88905. * @returns a matrix
  88906. */
  88907. Bone.prototype.getAbsoluteTransform = function () {
  88908. return this._absoluteTransform;
  88909. };
  88910. Object.defineProperty(Bone.prototype, "position", {
  88911. // Properties (matches AbstractMesh properties)
  88912. /** Gets or sets current position (in local space) */
  88913. get: function () {
  88914. this._decompose();
  88915. return this._localPosition;
  88916. },
  88917. set: function (newPosition) {
  88918. this._decompose();
  88919. this._localPosition.copyFrom(newPosition);
  88920. this._markAsDirtyAndCompose();
  88921. },
  88922. enumerable: true,
  88923. configurable: true
  88924. });
  88925. Object.defineProperty(Bone.prototype, "rotation", {
  88926. /** Gets or sets current rotation (in local space) */
  88927. get: function () {
  88928. return this.getRotation();
  88929. },
  88930. set: function (newRotation) {
  88931. this.setRotation(newRotation);
  88932. },
  88933. enumerable: true,
  88934. configurable: true
  88935. });
  88936. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  88937. /** Gets or sets current rotation quaternion (in local space) */
  88938. get: function () {
  88939. this._decompose();
  88940. return this._localRotation;
  88941. },
  88942. set: function (newRotation) {
  88943. this.setRotationQuaternion(newRotation);
  88944. },
  88945. enumerable: true,
  88946. configurable: true
  88947. });
  88948. Object.defineProperty(Bone.prototype, "scaling", {
  88949. /** Gets or sets current scaling (in local space) */
  88950. get: function () {
  88951. return this.getScale();
  88952. },
  88953. set: function (newScaling) {
  88954. this.setScale(newScaling);
  88955. },
  88956. enumerable: true,
  88957. configurable: true
  88958. });
  88959. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  88960. /**
  88961. * Gets the animation properties override
  88962. */
  88963. get: function () {
  88964. return this._skeleton.animationPropertiesOverride;
  88965. },
  88966. enumerable: true,
  88967. configurable: true
  88968. });
  88969. // Methods
  88970. Bone.prototype._decompose = function () {
  88971. if (!this._needToDecompose) {
  88972. return;
  88973. }
  88974. this._needToDecompose = false;
  88975. if (!this._localScaling) {
  88976. this._localScaling = BABYLON.Vector3.Zero();
  88977. this._localRotation = BABYLON.Quaternion.Zero();
  88978. this._localPosition = BABYLON.Vector3.Zero();
  88979. }
  88980. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  88981. };
  88982. Bone.prototype._compose = function () {
  88983. if (!this._needToCompose) {
  88984. return;
  88985. }
  88986. this._needToCompose = false;
  88987. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  88988. };
  88989. /**
  88990. * Update the base and local matrices
  88991. * @param matrix defines the new base or local matrix
  88992. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  88993. * @param updateLocalMatrix defines if the local matrix should be updated
  88994. */
  88995. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  88996. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  88997. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  88998. this._baseMatrix.copyFrom(matrix);
  88999. if (updateDifferenceMatrix) {
  89000. this._updateDifferenceMatrix();
  89001. }
  89002. if (updateLocalMatrix) {
  89003. this._localMatrix.copyFrom(matrix);
  89004. this._markAsDirtyAndDecompose();
  89005. }
  89006. else {
  89007. this.markAsDirty();
  89008. }
  89009. };
  89010. /** @hidden */
  89011. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  89012. if (updateChildren === void 0) { updateChildren = true; }
  89013. if (!rootMatrix) {
  89014. rootMatrix = this._baseMatrix;
  89015. }
  89016. if (this._parent) {
  89017. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  89018. }
  89019. else {
  89020. this._absoluteTransform.copyFrom(rootMatrix);
  89021. }
  89022. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  89023. if (updateChildren) {
  89024. for (var index = 0; index < this.children.length; index++) {
  89025. this.children[index]._updateDifferenceMatrix();
  89026. }
  89027. }
  89028. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  89029. };
  89030. /**
  89031. * Flag the bone as dirty (Forcing it to update everything)
  89032. */
  89033. Bone.prototype.markAsDirty = function () {
  89034. this._currentRenderId++;
  89035. this._childRenderId++;
  89036. this._skeleton._markAsDirty();
  89037. };
  89038. Bone.prototype._markAsDirtyAndCompose = function () {
  89039. this.markAsDirty();
  89040. this._needToCompose = true;
  89041. };
  89042. Bone.prototype._markAsDirtyAndDecompose = function () {
  89043. this.markAsDirty();
  89044. this._needToDecompose = true;
  89045. };
  89046. /**
  89047. * Copy an animation range from another bone
  89048. * @param source defines the source bone
  89049. * @param rangeName defines the range name to copy
  89050. * @param frameOffset defines the frame offset
  89051. * @param rescaleAsRequired defines if rescaling must be applied if required
  89052. * @param skelDimensionsRatio defines the scaling ratio
  89053. * @returns true if operation was successful
  89054. */
  89055. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  89056. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  89057. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  89058. // all animation may be coming from a library skeleton, so may need to create animation
  89059. if (this.animations.length === 0) {
  89060. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  89061. this.animations[0].setKeys([]);
  89062. }
  89063. // get animation info / verify there is such a range from the source bone
  89064. var sourceRange = source.animations[0].getRange(rangeName);
  89065. if (!sourceRange) {
  89066. return false;
  89067. }
  89068. var from = sourceRange.from;
  89069. var to = sourceRange.to;
  89070. var sourceKeys = source.animations[0].getKeys();
  89071. // rescaling prep
  89072. var sourceBoneLength = source.length;
  89073. var sourceParent = source.getParent();
  89074. var parent = this.getParent();
  89075. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  89076. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  89077. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  89078. var destKeys = this.animations[0].getKeys();
  89079. // loop vars declaration
  89080. var orig;
  89081. var origTranslation;
  89082. var mat;
  89083. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  89084. orig = sourceKeys[key];
  89085. if (orig.frame >= from && orig.frame <= to) {
  89086. if (rescaleAsRequired) {
  89087. mat = orig.value.clone();
  89088. // scale based on parent ratio, when bone has parent
  89089. if (parentScalingReqd) {
  89090. origTranslation = mat.getTranslation();
  89091. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  89092. // scale based on skeleton dimension ratio when root bone, and value is passed
  89093. }
  89094. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  89095. origTranslation = mat.getTranslation();
  89096. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  89097. // use original when root bone, and no data for skelDimensionsRatio
  89098. }
  89099. else {
  89100. mat = orig.value;
  89101. }
  89102. }
  89103. else {
  89104. mat = orig.value;
  89105. }
  89106. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  89107. }
  89108. }
  89109. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  89110. return true;
  89111. };
  89112. /**
  89113. * Translate the bone in local or world space
  89114. * @param vec The amount to translate the bone
  89115. * @param space The space that the translation is in
  89116. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89117. */
  89118. Bone.prototype.translate = function (vec, space, mesh) {
  89119. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89120. var lm = this.getLocalMatrix();
  89121. if (space == BABYLON.Space.LOCAL) {
  89122. lm.m[12] += vec.x;
  89123. lm.m[13] += vec.y;
  89124. lm.m[14] += vec.z;
  89125. }
  89126. else {
  89127. var wm = null;
  89128. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89129. if (mesh) {
  89130. wm = mesh.getWorldMatrix();
  89131. }
  89132. this._skeleton.computeAbsoluteTransforms();
  89133. var tmat = Bone._tmpMats[0];
  89134. var tvec = Bone._tmpVecs[0];
  89135. if (this._parent) {
  89136. if (mesh && wm) {
  89137. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89138. tmat.multiplyToRef(wm, tmat);
  89139. }
  89140. else {
  89141. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89142. }
  89143. }
  89144. tmat.m[12] = 0;
  89145. tmat.m[13] = 0;
  89146. tmat.m[14] = 0;
  89147. tmat.invert();
  89148. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  89149. lm.m[12] += tvec.x;
  89150. lm.m[13] += tvec.y;
  89151. lm.m[14] += tvec.z;
  89152. }
  89153. this._markAsDirtyAndDecompose();
  89154. };
  89155. /**
  89156. * Set the postion of the bone in local or world space
  89157. * @param position The position to set the bone
  89158. * @param space The space that the position is in
  89159. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89160. */
  89161. Bone.prototype.setPosition = function (position, space, mesh) {
  89162. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89163. var lm = this.getLocalMatrix();
  89164. if (space == BABYLON.Space.LOCAL) {
  89165. lm.m[12] = position.x;
  89166. lm.m[13] = position.y;
  89167. lm.m[14] = position.z;
  89168. }
  89169. else {
  89170. var wm = null;
  89171. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89172. if (mesh) {
  89173. wm = mesh.getWorldMatrix();
  89174. }
  89175. this._skeleton.computeAbsoluteTransforms();
  89176. var tmat = Bone._tmpMats[0];
  89177. var vec = Bone._tmpVecs[0];
  89178. if (this._parent) {
  89179. if (mesh && wm) {
  89180. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89181. tmat.multiplyToRef(wm, tmat);
  89182. }
  89183. else {
  89184. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89185. }
  89186. }
  89187. tmat.invert();
  89188. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  89189. lm.m[12] = vec.x;
  89190. lm.m[13] = vec.y;
  89191. lm.m[14] = vec.z;
  89192. }
  89193. this._markAsDirtyAndDecompose();
  89194. };
  89195. /**
  89196. * Set the absolute position of the bone (world space)
  89197. * @param position The position to set the bone
  89198. * @param mesh The mesh that this bone is attached to
  89199. */
  89200. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  89201. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  89202. };
  89203. /**
  89204. * Scale the bone on the x, y and z axes (in local space)
  89205. * @param x The amount to scale the bone on the x axis
  89206. * @param y The amount to scale the bone on the y axis
  89207. * @param z The amount to scale the bone on the z axis
  89208. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  89209. */
  89210. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  89211. if (scaleChildren === void 0) { scaleChildren = false; }
  89212. var locMat = this.getLocalMatrix();
  89213. // Apply new scaling on top of current local matrix
  89214. var scaleMat = Bone._tmpMats[0];
  89215. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  89216. scaleMat.multiplyToRef(locMat, locMat);
  89217. // Invert scaling matrix and apply the inverse to all children
  89218. scaleMat.invert();
  89219. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  89220. var child = _a[_i];
  89221. var cm = child.getLocalMatrix();
  89222. cm.multiplyToRef(scaleMat, cm);
  89223. cm.m[12] *= x;
  89224. cm.m[13] *= y;
  89225. cm.m[14] *= z;
  89226. child._markAsDirtyAndDecompose();
  89227. }
  89228. this._markAsDirtyAndDecompose();
  89229. if (scaleChildren) {
  89230. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  89231. var child = _c[_b];
  89232. child.scale(x, y, z, scaleChildren);
  89233. }
  89234. }
  89235. };
  89236. /**
  89237. * Set the bone scaling in local space
  89238. * @param scale defines the scaling vector
  89239. */
  89240. Bone.prototype.setScale = function (scale) {
  89241. this._decompose();
  89242. this._localScaling.copyFrom(scale);
  89243. this._markAsDirtyAndCompose();
  89244. };
  89245. /**
  89246. * Gets the current scaling in local space
  89247. * @returns the current scaling vector
  89248. */
  89249. Bone.prototype.getScale = function () {
  89250. this._decompose();
  89251. return this._localScaling;
  89252. };
  89253. /**
  89254. * Gets the current scaling in local space and stores it in a target vector
  89255. * @param result defines the target vector
  89256. */
  89257. Bone.prototype.getScaleToRef = function (result) {
  89258. this._decompose();
  89259. result.copyFrom(this._localScaling);
  89260. };
  89261. /**
  89262. * Set the yaw, pitch, and roll of the bone in local or world space
  89263. * @param yaw The rotation of the bone on the y axis
  89264. * @param pitch The rotation of the bone on the x axis
  89265. * @param roll The rotation of the bone on the z axis
  89266. * @param space The space that the axes of rotation are in
  89267. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89268. */
  89269. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  89270. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89271. if (space === BABYLON.Space.LOCAL) {
  89272. var quat = Bone._tmpQuat;
  89273. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  89274. this.setRotationQuaternion(quat, space, mesh);
  89275. return;
  89276. }
  89277. var rotMatInv = Bone._tmpMats[0];
  89278. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89279. return;
  89280. }
  89281. var rotMat = Bone._tmpMats[1];
  89282. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  89283. rotMatInv.multiplyToRef(rotMat, rotMat);
  89284. this._rotateWithMatrix(rotMat, space, mesh);
  89285. };
  89286. /**
  89287. * Add a rotation to the bone on an axis in local or world space
  89288. * @param axis The axis to rotate the bone on
  89289. * @param amount The amount to rotate the bone
  89290. * @param space The space that the axis is in
  89291. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89292. */
  89293. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  89294. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89295. var rmat = Bone._tmpMats[0];
  89296. rmat.m[12] = 0;
  89297. rmat.m[13] = 0;
  89298. rmat.m[14] = 0;
  89299. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  89300. this._rotateWithMatrix(rmat, space, mesh);
  89301. };
  89302. /**
  89303. * Set the rotation of the bone to a particular axis angle in local or world space
  89304. * @param axis The axis to rotate the bone on
  89305. * @param angle The angle that the bone should be rotated to
  89306. * @param space The space that the axis is in
  89307. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89308. */
  89309. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  89310. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89311. if (space === BABYLON.Space.LOCAL) {
  89312. var quat = Bone._tmpQuat;
  89313. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  89314. this.setRotationQuaternion(quat, space, mesh);
  89315. return;
  89316. }
  89317. var rotMatInv = Bone._tmpMats[0];
  89318. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89319. return;
  89320. }
  89321. var rotMat = Bone._tmpMats[1];
  89322. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  89323. rotMatInv.multiplyToRef(rotMat, rotMat);
  89324. this._rotateWithMatrix(rotMat, space, mesh);
  89325. };
  89326. /**
  89327. * Set the euler rotation of the bone in local of world space
  89328. * @param rotation The euler rotation that the bone should be set to
  89329. * @param space The space that the rotation is in
  89330. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89331. */
  89332. Bone.prototype.setRotation = function (rotation, space, mesh) {
  89333. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89334. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  89335. };
  89336. /**
  89337. * Set the quaternion rotation of the bone in local of world space
  89338. * @param quat The quaternion rotation that the bone should be set to
  89339. * @param space The space that the rotation is in
  89340. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89341. */
  89342. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  89343. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89344. if (space === BABYLON.Space.LOCAL) {
  89345. this._decompose();
  89346. this._localRotation.copyFrom(quat);
  89347. this._markAsDirtyAndCompose();
  89348. return;
  89349. }
  89350. var rotMatInv = Bone._tmpMats[0];
  89351. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89352. return;
  89353. }
  89354. var rotMat = Bone._tmpMats[1];
  89355. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  89356. rotMatInv.multiplyToRef(rotMat, rotMat);
  89357. this._rotateWithMatrix(rotMat, space, mesh);
  89358. };
  89359. /**
  89360. * Set the rotation matrix of the bone in local of world space
  89361. * @param rotMat The rotation matrix that the bone should be set to
  89362. * @param space The space that the rotation is in
  89363. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89364. */
  89365. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  89366. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89367. if (space === BABYLON.Space.LOCAL) {
  89368. var quat = Bone._tmpQuat;
  89369. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  89370. this.setRotationQuaternion(quat, space, mesh);
  89371. return;
  89372. }
  89373. var rotMatInv = Bone._tmpMats[0];
  89374. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89375. return;
  89376. }
  89377. var rotMat2 = Bone._tmpMats[1];
  89378. rotMat2.copyFrom(rotMat);
  89379. rotMatInv.multiplyToRef(rotMat, rotMat2);
  89380. this._rotateWithMatrix(rotMat2, space, mesh);
  89381. };
  89382. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  89383. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89384. var lmat = this.getLocalMatrix();
  89385. var lx = lmat.m[12];
  89386. var ly = lmat.m[13];
  89387. var lz = lmat.m[14];
  89388. var parent = this.getParent();
  89389. var parentScale = Bone._tmpMats[3];
  89390. var parentScaleInv = Bone._tmpMats[4];
  89391. if (parent && space == BABYLON.Space.WORLD) {
  89392. if (mesh) {
  89393. parentScale.copyFrom(mesh.getWorldMatrix());
  89394. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  89395. }
  89396. else {
  89397. parentScale.copyFrom(parent.getAbsoluteTransform());
  89398. }
  89399. parentScaleInv.copyFrom(parentScale);
  89400. parentScaleInv.invert();
  89401. lmat.multiplyToRef(parentScale, lmat);
  89402. lmat.multiplyToRef(rmat, lmat);
  89403. lmat.multiplyToRef(parentScaleInv, lmat);
  89404. }
  89405. else {
  89406. if (space == BABYLON.Space.WORLD && mesh) {
  89407. parentScale.copyFrom(mesh.getWorldMatrix());
  89408. parentScaleInv.copyFrom(parentScale);
  89409. parentScaleInv.invert();
  89410. lmat.multiplyToRef(parentScale, lmat);
  89411. lmat.multiplyToRef(rmat, lmat);
  89412. lmat.multiplyToRef(parentScaleInv, lmat);
  89413. }
  89414. else {
  89415. lmat.multiplyToRef(rmat, lmat);
  89416. }
  89417. }
  89418. lmat.m[12] = lx;
  89419. lmat.m[13] = ly;
  89420. lmat.m[14] = lz;
  89421. this.computeAbsoluteTransforms();
  89422. this._markAsDirtyAndDecompose();
  89423. };
  89424. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  89425. var scaleMatrix = Bone._tmpMats[2];
  89426. rotMatInv.copyFrom(this.getAbsoluteTransform());
  89427. if (mesh) {
  89428. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  89429. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  89430. }
  89431. rotMatInv.invert();
  89432. if (isNaN(rotMatInv.m[0])) {
  89433. // Matrix failed to invert.
  89434. // This can happen if scale is zero for example.
  89435. return false;
  89436. }
  89437. scaleMatrix.m[0] *= this._scalingDeterminant;
  89438. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  89439. return true;
  89440. };
  89441. /**
  89442. * Get the position of the bone in local or world space
  89443. * @param space The space that the returned position is in
  89444. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89445. * @returns The position of the bone
  89446. */
  89447. Bone.prototype.getPosition = function (space, mesh) {
  89448. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89449. if (mesh === void 0) { mesh = null; }
  89450. var pos = BABYLON.Vector3.Zero();
  89451. this.getPositionToRef(space, mesh, pos);
  89452. return pos;
  89453. };
  89454. /**
  89455. * Copy the position of the bone to a vector3 in local or world space
  89456. * @param space The space that the returned position is in
  89457. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89458. * @param result The vector3 to copy the position to
  89459. */
  89460. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  89461. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89462. if (space == BABYLON.Space.LOCAL) {
  89463. var lm = this.getLocalMatrix();
  89464. result.x = lm.m[12];
  89465. result.y = lm.m[13];
  89466. result.z = lm.m[14];
  89467. }
  89468. else {
  89469. var wm = null;
  89470. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89471. if (mesh) {
  89472. wm = mesh.getWorldMatrix();
  89473. }
  89474. this._skeleton.computeAbsoluteTransforms();
  89475. var tmat = Bone._tmpMats[0];
  89476. if (mesh && wm) {
  89477. tmat.copyFrom(this.getAbsoluteTransform());
  89478. tmat.multiplyToRef(wm, tmat);
  89479. }
  89480. else {
  89481. tmat = this.getAbsoluteTransform();
  89482. }
  89483. result.x = tmat.m[12];
  89484. result.y = tmat.m[13];
  89485. result.z = tmat.m[14];
  89486. }
  89487. };
  89488. /**
  89489. * Get the absolute position of the bone (world space)
  89490. * @param mesh The mesh that this bone is attached to
  89491. * @returns The absolute position of the bone
  89492. */
  89493. Bone.prototype.getAbsolutePosition = function (mesh) {
  89494. if (mesh === void 0) { mesh = null; }
  89495. var pos = BABYLON.Vector3.Zero();
  89496. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  89497. return pos;
  89498. };
  89499. /**
  89500. * Copy the absolute position of the bone (world space) to the result param
  89501. * @param mesh The mesh that this bone is attached to
  89502. * @param result The vector3 to copy the absolute position to
  89503. */
  89504. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  89505. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  89506. };
  89507. /**
  89508. * Compute the absolute transforms of this bone and its children
  89509. */
  89510. Bone.prototype.computeAbsoluteTransforms = function () {
  89511. this._compose();
  89512. if (this._parent) {
  89513. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  89514. }
  89515. else {
  89516. this._absoluteTransform.copyFrom(this._localMatrix);
  89517. var poseMatrix = this._skeleton.getPoseMatrix();
  89518. if (poseMatrix) {
  89519. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  89520. }
  89521. }
  89522. var children = this.children;
  89523. var len = children.length;
  89524. for (var i = 0; i < len; i++) {
  89525. children[i].computeAbsoluteTransforms();
  89526. }
  89527. };
  89528. /**
  89529. * Get the world direction from an axis that is in the local space of the bone
  89530. * @param localAxis The local direction that is used to compute the world direction
  89531. * @param mesh The mesh that this bone is attached to
  89532. * @returns The world direction
  89533. */
  89534. Bone.prototype.getDirection = function (localAxis, mesh) {
  89535. if (mesh === void 0) { mesh = null; }
  89536. var result = BABYLON.Vector3.Zero();
  89537. this.getDirectionToRef(localAxis, mesh, result);
  89538. return result;
  89539. };
  89540. /**
  89541. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  89542. * @param localAxis The local direction that is used to compute the world direction
  89543. * @param mesh The mesh that this bone is attached to
  89544. * @param result The vector3 that the world direction will be copied to
  89545. */
  89546. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  89547. if (mesh === void 0) { mesh = null; }
  89548. var wm = null;
  89549. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89550. if (mesh) {
  89551. wm = mesh.getWorldMatrix();
  89552. }
  89553. this._skeleton.computeAbsoluteTransforms();
  89554. var mat = Bone._tmpMats[0];
  89555. mat.copyFrom(this.getAbsoluteTransform());
  89556. if (mesh && wm) {
  89557. mat.multiplyToRef(wm, mat);
  89558. }
  89559. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  89560. result.normalize();
  89561. };
  89562. /**
  89563. * Get the euler rotation of the bone in local or world space
  89564. * @param space The space that the rotation should be in
  89565. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89566. * @returns The euler rotation
  89567. */
  89568. Bone.prototype.getRotation = function (space, mesh) {
  89569. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89570. if (mesh === void 0) { mesh = null; }
  89571. var result = BABYLON.Vector3.Zero();
  89572. this.getRotationToRef(space, mesh, result);
  89573. return result;
  89574. };
  89575. /**
  89576. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  89577. * @param space The space that the rotation should be in
  89578. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89579. * @param result The vector3 that the rotation should be copied to
  89580. */
  89581. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  89582. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89583. if (mesh === void 0) { mesh = null; }
  89584. var quat = Bone._tmpQuat;
  89585. this.getRotationQuaternionToRef(space, mesh, quat);
  89586. quat.toEulerAnglesToRef(result);
  89587. };
  89588. /**
  89589. * Get the quaternion rotation of the bone in either local or world space
  89590. * @param space The space that the rotation should be in
  89591. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89592. * @returns The quaternion rotation
  89593. */
  89594. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  89595. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89596. if (mesh === void 0) { mesh = null; }
  89597. var result = BABYLON.Quaternion.Identity();
  89598. this.getRotationQuaternionToRef(space, mesh, result);
  89599. return result;
  89600. };
  89601. /**
  89602. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  89603. * @param space The space that the rotation should be in
  89604. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89605. * @param result The quaternion that the rotation should be copied to
  89606. */
  89607. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  89608. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89609. if (mesh === void 0) { mesh = null; }
  89610. if (space == BABYLON.Space.LOCAL) {
  89611. this._decompose();
  89612. result.copyFrom(this._localRotation);
  89613. }
  89614. else {
  89615. var mat = Bone._tmpMats[0];
  89616. var amat = this.getAbsoluteTransform();
  89617. if (mesh) {
  89618. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  89619. }
  89620. else {
  89621. mat.copyFrom(amat);
  89622. }
  89623. mat.m[0] *= this._scalingDeterminant;
  89624. mat.m[1] *= this._scalingDeterminant;
  89625. mat.m[2] *= this._scalingDeterminant;
  89626. mat.decompose(undefined, result, undefined);
  89627. }
  89628. };
  89629. /**
  89630. * Get the rotation matrix of the bone in local or world space
  89631. * @param space The space that the rotation should be in
  89632. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89633. * @returns The rotation matrix
  89634. */
  89635. Bone.prototype.getRotationMatrix = function (space, mesh) {
  89636. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89637. var result = BABYLON.Matrix.Identity();
  89638. this.getRotationMatrixToRef(space, mesh, result);
  89639. return result;
  89640. };
  89641. /**
  89642. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  89643. * @param space The space that the rotation should be in
  89644. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89645. * @param result The quaternion that the rotation should be copied to
  89646. */
  89647. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  89648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89649. if (space == BABYLON.Space.LOCAL) {
  89650. this.getLocalMatrix().getRotationMatrixToRef(result);
  89651. }
  89652. else {
  89653. var mat = Bone._tmpMats[0];
  89654. var amat = this.getAbsoluteTransform();
  89655. if (mesh) {
  89656. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  89657. }
  89658. else {
  89659. mat.copyFrom(amat);
  89660. }
  89661. mat.m[0] *= this._scalingDeterminant;
  89662. mat.m[1] *= this._scalingDeterminant;
  89663. mat.m[2] *= this._scalingDeterminant;
  89664. mat.getRotationMatrixToRef(result);
  89665. }
  89666. };
  89667. /**
  89668. * Get the world position of a point that is in the local space of the bone
  89669. * @param position The local position
  89670. * @param mesh The mesh that this bone is attached to
  89671. * @returns The world position
  89672. */
  89673. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  89674. if (mesh === void 0) { mesh = null; }
  89675. var result = BABYLON.Vector3.Zero();
  89676. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  89677. return result;
  89678. };
  89679. /**
  89680. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  89681. * @param position The local position
  89682. * @param mesh The mesh that this bone is attached to
  89683. * @param result The vector3 that the world position should be copied to
  89684. */
  89685. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  89686. if (mesh === void 0) { mesh = null; }
  89687. var wm = null;
  89688. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89689. if (mesh) {
  89690. wm = mesh.getWorldMatrix();
  89691. }
  89692. this._skeleton.computeAbsoluteTransforms();
  89693. var tmat = Bone._tmpMats[0];
  89694. if (mesh && wm) {
  89695. tmat.copyFrom(this.getAbsoluteTransform());
  89696. tmat.multiplyToRef(wm, tmat);
  89697. }
  89698. else {
  89699. tmat = this.getAbsoluteTransform();
  89700. }
  89701. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  89702. };
  89703. /**
  89704. * Get the local position of a point that is in world space
  89705. * @param position The world position
  89706. * @param mesh The mesh that this bone is attached to
  89707. * @returns The local position
  89708. */
  89709. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  89710. if (mesh === void 0) { mesh = null; }
  89711. var result = BABYLON.Vector3.Zero();
  89712. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  89713. return result;
  89714. };
  89715. /**
  89716. * Get the local position of a point that is in world space and copy it to the result param
  89717. * @param position The world position
  89718. * @param mesh The mesh that this bone is attached to
  89719. * @param result The vector3 that the local position should be copied to
  89720. */
  89721. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  89722. if (mesh === void 0) { mesh = null; }
  89723. var wm = null;
  89724. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89725. if (mesh) {
  89726. wm = mesh.getWorldMatrix();
  89727. }
  89728. this._skeleton.computeAbsoluteTransforms();
  89729. var tmat = Bone._tmpMats[0];
  89730. tmat.copyFrom(this.getAbsoluteTransform());
  89731. if (mesh && wm) {
  89732. tmat.multiplyToRef(wm, tmat);
  89733. }
  89734. tmat.invert();
  89735. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  89736. };
  89737. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89738. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  89739. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  89740. return Bone;
  89741. }(BABYLON.Node));
  89742. BABYLON.Bone = Bone;
  89743. })(BABYLON || (BABYLON = {}));
  89744. //# sourceMappingURL=babylon.bone.js.map
  89745. var BABYLON;
  89746. (function (BABYLON) {
  89747. /**
  89748. * Class used to apply inverse kinematics to bones
  89749. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  89750. */
  89751. var BoneIKController = /** @class */ (function () {
  89752. /**
  89753. * Creates a new BoneIKController
  89754. * @param mesh defines the mesh to control
  89755. * @param bone defines the bone to control
  89756. * @param options defines options to set up the controller
  89757. */
  89758. function BoneIKController(mesh, bone, options) {
  89759. /**
  89760. * Gets or sets the target position
  89761. */
  89762. this.targetPosition = BABYLON.Vector3.Zero();
  89763. /**
  89764. * Gets or sets the pole target position
  89765. */
  89766. this.poleTargetPosition = BABYLON.Vector3.Zero();
  89767. /**
  89768. * Gets or sets the pole target local offset
  89769. */
  89770. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  89771. /**
  89772. * Gets or sets the pole angle
  89773. */
  89774. this.poleAngle = 0;
  89775. /**
  89776. * 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)
  89777. */
  89778. this.slerpAmount = 1;
  89779. this._bone1Quat = BABYLON.Quaternion.Identity();
  89780. this._bone1Mat = BABYLON.Matrix.Identity();
  89781. this._bone2Ang = Math.PI;
  89782. this._maxAngle = Math.PI;
  89783. this._rightHandedSystem = false;
  89784. this._bendAxis = BABYLON.Vector3.Right();
  89785. this._slerping = false;
  89786. this._adjustRoll = 0;
  89787. this._bone2 = bone;
  89788. this._bone1 = bone.getParent();
  89789. if (!this._bone1) {
  89790. return;
  89791. }
  89792. this.mesh = mesh;
  89793. var bonePos = bone.getPosition();
  89794. if (bone.getAbsoluteTransform().determinant() > 0) {
  89795. this._rightHandedSystem = true;
  89796. this._bendAxis.x = 0;
  89797. this._bendAxis.y = 0;
  89798. this._bendAxis.z = -1;
  89799. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  89800. this._adjustRoll = Math.PI * .5;
  89801. this._bendAxis.z = 1;
  89802. }
  89803. }
  89804. if (this._bone1.length) {
  89805. var boneScale1 = this._bone1.getScale();
  89806. var boneScale2 = this._bone2.getScale();
  89807. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  89808. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  89809. }
  89810. else if (this._bone1.children[0]) {
  89811. mesh.computeWorldMatrix(true);
  89812. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  89813. var pos2 = this._bone2.getAbsolutePosition(mesh);
  89814. var pos3 = this._bone1.getAbsolutePosition(mesh);
  89815. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  89816. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  89817. }
  89818. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  89819. this.maxAngle = Math.PI;
  89820. if (options) {
  89821. if (options.targetMesh) {
  89822. this.targetMesh = options.targetMesh;
  89823. this.targetMesh.computeWorldMatrix(true);
  89824. }
  89825. if (options.poleTargetMesh) {
  89826. this.poleTargetMesh = options.poleTargetMesh;
  89827. this.poleTargetMesh.computeWorldMatrix(true);
  89828. }
  89829. else if (options.poleTargetBone) {
  89830. this.poleTargetBone = options.poleTargetBone;
  89831. }
  89832. else if (this._bone1.getParent()) {
  89833. this.poleTargetBone = this._bone1.getParent();
  89834. }
  89835. if (options.poleTargetLocalOffset) {
  89836. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  89837. }
  89838. if (options.poleAngle) {
  89839. this.poleAngle = options.poleAngle;
  89840. }
  89841. if (options.bendAxis) {
  89842. this._bendAxis.copyFrom(options.bendAxis);
  89843. }
  89844. if (options.maxAngle) {
  89845. this.maxAngle = options.maxAngle;
  89846. }
  89847. if (options.slerpAmount) {
  89848. this.slerpAmount = options.slerpAmount;
  89849. }
  89850. }
  89851. }
  89852. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  89853. /**
  89854. * Gets or sets maximum allowed angle
  89855. */
  89856. get: function () {
  89857. return this._maxAngle;
  89858. },
  89859. set: function (value) {
  89860. this._setMaxAngle(value);
  89861. },
  89862. enumerable: true,
  89863. configurable: true
  89864. });
  89865. BoneIKController.prototype._setMaxAngle = function (ang) {
  89866. if (ang < 0) {
  89867. ang = 0;
  89868. }
  89869. if (ang > Math.PI || ang == undefined) {
  89870. ang = Math.PI;
  89871. }
  89872. this._maxAngle = ang;
  89873. var a = this._bone1Length;
  89874. var b = this._bone2Length;
  89875. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  89876. };
  89877. /**
  89878. * Force the controller to update the bones
  89879. */
  89880. BoneIKController.prototype.update = function () {
  89881. var bone1 = this._bone1;
  89882. if (!bone1) {
  89883. return;
  89884. }
  89885. var target = this.targetPosition;
  89886. var poleTarget = this.poleTargetPosition;
  89887. var mat1 = BoneIKController._tmpMats[0];
  89888. var mat2 = BoneIKController._tmpMats[1];
  89889. if (this.targetMesh) {
  89890. target.copyFrom(this.targetMesh.getAbsolutePosition());
  89891. }
  89892. if (this.poleTargetBone) {
  89893. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  89894. }
  89895. else if (this.poleTargetMesh) {
  89896. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  89897. }
  89898. var bonePos = BoneIKController._tmpVecs[0];
  89899. var zaxis = BoneIKController._tmpVecs[1];
  89900. var xaxis = BoneIKController._tmpVecs[2];
  89901. var yaxis = BoneIKController._tmpVecs[3];
  89902. var upAxis = BoneIKController._tmpVecs[4];
  89903. var _tmpQuat = BoneIKController._tmpQuat;
  89904. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  89905. poleTarget.subtractToRef(bonePos, upAxis);
  89906. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  89907. upAxis.y = 1;
  89908. }
  89909. else {
  89910. upAxis.normalize();
  89911. }
  89912. target.subtractToRef(bonePos, yaxis);
  89913. yaxis.normalize();
  89914. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  89915. zaxis.normalize();
  89916. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  89917. xaxis.normalize();
  89918. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  89919. var a = this._bone1Length;
  89920. var b = this._bone2Length;
  89921. var c = BABYLON.Vector3.Distance(bonePos, target);
  89922. if (this._maxReach > 0) {
  89923. c = Math.min(this._maxReach, c);
  89924. }
  89925. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  89926. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  89927. if (acosa > 1) {
  89928. acosa = 1;
  89929. }
  89930. if (acosb > 1) {
  89931. acosb = 1;
  89932. }
  89933. if (acosa < -1) {
  89934. acosa = -1;
  89935. }
  89936. if (acosb < -1) {
  89937. acosb = -1;
  89938. }
  89939. var angA = Math.acos(acosa);
  89940. var angB = Math.acos(acosb);
  89941. var angC = -angA - angB;
  89942. if (this._rightHandedSystem) {
  89943. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  89944. mat2.multiplyToRef(mat1, mat1);
  89945. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  89946. mat2.multiplyToRef(mat1, mat1);
  89947. }
  89948. else {
  89949. var _tmpVec = BoneIKController._tmpVecs[5];
  89950. _tmpVec.copyFrom(this._bendAxis);
  89951. _tmpVec.x *= -1;
  89952. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  89953. mat2.multiplyToRef(mat1, mat1);
  89954. }
  89955. if (this.poleAngle) {
  89956. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  89957. mat1.multiplyToRef(mat2, mat1);
  89958. }
  89959. if (this._bone1) {
  89960. if (this.slerpAmount < 1) {
  89961. if (!this._slerping) {
  89962. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  89963. }
  89964. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  89965. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  89966. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  89967. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  89968. this._slerping = true;
  89969. }
  89970. else {
  89971. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  89972. this._bone1Mat.copyFrom(mat1);
  89973. this._slerping = false;
  89974. }
  89975. }
  89976. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  89977. this._bone2Ang = angC;
  89978. };
  89979. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89980. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  89981. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  89982. return BoneIKController;
  89983. }());
  89984. BABYLON.BoneIKController = BoneIKController;
  89985. })(BABYLON || (BABYLON = {}));
  89986. //# sourceMappingURL=babylon.boneIKController.js.map
  89987. var BABYLON;
  89988. (function (BABYLON) {
  89989. /**
  89990. * Class used to make a bone look toward a point in space
  89991. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  89992. */
  89993. var BoneLookController = /** @class */ (function () {
  89994. /**
  89995. * Create a BoneLookController
  89996. * @param mesh the mesh that the bone belongs to
  89997. * @param bone the bone that will be looking to the target
  89998. * @param target the target Vector3 to look at
  89999. * @param settings optional settings:
  90000. * * maxYaw: the maximum angle the bone will yaw to
  90001. * * minYaw: the minimum angle the bone will yaw to
  90002. * * maxPitch: the maximum angle the bone will pitch to
  90003. * * minPitch: the minimum angle the bone will yaw to
  90004. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  90005. * * upAxis: the up axis of the coordinate system
  90006. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  90007. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  90008. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  90009. * * adjustYaw: used to make an adjustment to the yaw of the bone
  90010. * * adjustPitch: used to make an adjustment to the pitch of the bone
  90011. * * adjustRoll: used to make an adjustment to the roll of the bone
  90012. **/
  90013. function BoneLookController(mesh, bone, target, options) {
  90014. /**
  90015. * The up axis of the coordinate system that is used when the bone is rotated
  90016. */
  90017. this.upAxis = BABYLON.Vector3.Up();
  90018. /**
  90019. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  90020. */
  90021. this.upAxisSpace = BABYLON.Space.LOCAL;
  90022. /**
  90023. * Used to make an adjustment to the yaw of the bone
  90024. */
  90025. this.adjustYaw = 0;
  90026. /**
  90027. * Used to make an adjustment to the pitch of the bone
  90028. */
  90029. this.adjustPitch = 0;
  90030. /**
  90031. * Used to make an adjustment to the roll of the bone
  90032. */
  90033. this.adjustRoll = 0;
  90034. /**
  90035. * 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)
  90036. */
  90037. this.slerpAmount = 1;
  90038. this._boneQuat = BABYLON.Quaternion.Identity();
  90039. this._slerping = false;
  90040. this._firstFrameSkipped = false;
  90041. this._fowardAxis = BABYLON.Vector3.Forward();
  90042. this.mesh = mesh;
  90043. this.bone = bone;
  90044. this.target = target;
  90045. if (options) {
  90046. if (options.adjustYaw) {
  90047. this.adjustYaw = options.adjustYaw;
  90048. }
  90049. if (options.adjustPitch) {
  90050. this.adjustPitch = options.adjustPitch;
  90051. }
  90052. if (options.adjustRoll) {
  90053. this.adjustRoll = options.adjustRoll;
  90054. }
  90055. if (options.maxYaw != null) {
  90056. this.maxYaw = options.maxYaw;
  90057. }
  90058. else {
  90059. this.maxYaw = Math.PI;
  90060. }
  90061. if (options.minYaw != null) {
  90062. this.minYaw = options.minYaw;
  90063. }
  90064. else {
  90065. this.minYaw = -Math.PI;
  90066. }
  90067. if (options.maxPitch != null) {
  90068. this.maxPitch = options.maxPitch;
  90069. }
  90070. else {
  90071. this.maxPitch = Math.PI;
  90072. }
  90073. if (options.minPitch != null) {
  90074. this.minPitch = options.minPitch;
  90075. }
  90076. else {
  90077. this.minPitch = -Math.PI;
  90078. }
  90079. if (options.slerpAmount != null) {
  90080. this.slerpAmount = options.slerpAmount;
  90081. }
  90082. if (options.upAxis != null) {
  90083. this.upAxis = options.upAxis;
  90084. }
  90085. if (options.upAxisSpace != null) {
  90086. this.upAxisSpace = options.upAxisSpace;
  90087. }
  90088. if (options.yawAxis != null || options.pitchAxis != null) {
  90089. var newYawAxis = BABYLON.Axis.Y;
  90090. var newPitchAxis = BABYLON.Axis.X;
  90091. if (options.yawAxis != null) {
  90092. newYawAxis = options.yawAxis.clone();
  90093. newYawAxis.normalize();
  90094. }
  90095. if (options.pitchAxis != null) {
  90096. newPitchAxis = options.pitchAxis.clone();
  90097. newPitchAxis.normalize();
  90098. }
  90099. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  90100. this._transformYawPitch = BABYLON.Matrix.Identity();
  90101. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  90102. this._transformYawPitchInv = this._transformYawPitch.clone();
  90103. this._transformYawPitch.invert();
  90104. }
  90105. }
  90106. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  90107. this.upAxisSpace = BABYLON.Space.LOCAL;
  90108. }
  90109. }
  90110. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  90111. /**
  90112. * Gets or sets the minimum yaw angle that the bone can look to
  90113. */
  90114. get: function () {
  90115. return this._minYaw;
  90116. },
  90117. set: function (value) {
  90118. this._minYaw = value;
  90119. this._minYawSin = Math.sin(value);
  90120. this._minYawCos = Math.cos(value);
  90121. if (this._maxYaw != null) {
  90122. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  90123. this._yawRange = this._maxYaw - this._minYaw;
  90124. }
  90125. },
  90126. enumerable: true,
  90127. configurable: true
  90128. });
  90129. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  90130. /**
  90131. * Gets or sets the maximum yaw angle that the bone can look to
  90132. */
  90133. get: function () {
  90134. return this._maxYaw;
  90135. },
  90136. set: function (value) {
  90137. this._maxYaw = value;
  90138. this._maxYawSin = Math.sin(value);
  90139. this._maxYawCos = Math.cos(value);
  90140. if (this._minYaw != null) {
  90141. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  90142. this._yawRange = this._maxYaw - this._minYaw;
  90143. }
  90144. },
  90145. enumerable: true,
  90146. configurable: true
  90147. });
  90148. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  90149. /**
  90150. * Gets or sets the minimum pitch angle that the bone can look to
  90151. */
  90152. get: function () {
  90153. return this._minPitch;
  90154. },
  90155. set: function (value) {
  90156. this._minPitch = value;
  90157. this._minPitchTan = Math.tan(value);
  90158. },
  90159. enumerable: true,
  90160. configurable: true
  90161. });
  90162. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  90163. /**
  90164. * Gets or sets the maximum pitch angle that the bone can look to
  90165. */
  90166. get: function () {
  90167. return this._maxPitch;
  90168. },
  90169. set: function (value) {
  90170. this._maxPitch = value;
  90171. this._maxPitchTan = Math.tan(value);
  90172. },
  90173. enumerable: true,
  90174. configurable: true
  90175. });
  90176. /**
  90177. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  90178. */
  90179. BoneLookController.prototype.update = function () {
  90180. //skip the first frame when slerping so that the mesh rotation is correct
  90181. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  90182. this._firstFrameSkipped = true;
  90183. return;
  90184. }
  90185. var bone = this.bone;
  90186. var bonePos = BoneLookController._tmpVecs[0];
  90187. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  90188. var target = this.target;
  90189. var _tmpMat1 = BoneLookController._tmpMats[0];
  90190. var _tmpMat2 = BoneLookController._tmpMats[1];
  90191. var mesh = this.mesh;
  90192. var parentBone = bone.getParent();
  90193. var upAxis = BoneLookController._tmpVecs[1];
  90194. upAxis.copyFrom(this.upAxis);
  90195. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  90196. if (this._transformYawPitch) {
  90197. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  90198. }
  90199. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  90200. }
  90201. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  90202. mesh.getDirectionToRef(upAxis, upAxis);
  90203. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  90204. upAxis.normalize();
  90205. }
  90206. }
  90207. var checkYaw = false;
  90208. var checkPitch = false;
  90209. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  90210. checkYaw = true;
  90211. }
  90212. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  90213. checkPitch = true;
  90214. }
  90215. if (checkYaw || checkPitch) {
  90216. var spaceMat = BoneLookController._tmpMats[2];
  90217. var spaceMatInv = BoneLookController._tmpMats[3];
  90218. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  90219. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  90220. }
  90221. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  90222. spaceMat.copyFrom(mesh.getWorldMatrix());
  90223. }
  90224. else {
  90225. var forwardAxis = BoneLookController._tmpVecs[2];
  90226. forwardAxis.copyFrom(this._fowardAxis);
  90227. if (this._transformYawPitch) {
  90228. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  90229. }
  90230. if (parentBone) {
  90231. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  90232. }
  90233. else {
  90234. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  90235. }
  90236. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  90237. rightAxis.normalize();
  90238. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  90239. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  90240. }
  90241. spaceMat.invertToRef(spaceMatInv);
  90242. var xzlen = null;
  90243. if (checkPitch) {
  90244. var localTarget = BoneLookController._tmpVecs[3];
  90245. target.subtractToRef(bonePos, localTarget);
  90246. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  90247. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  90248. var pitch = Math.atan2(localTarget.y, xzlen);
  90249. var newPitch = pitch;
  90250. if (pitch > this._maxPitch) {
  90251. localTarget.y = this._maxPitchTan * xzlen;
  90252. newPitch = this._maxPitch;
  90253. }
  90254. else if (pitch < this._minPitch) {
  90255. localTarget.y = this._minPitchTan * xzlen;
  90256. newPitch = this._minPitch;
  90257. }
  90258. if (pitch != newPitch) {
  90259. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  90260. localTarget.addInPlace(bonePos);
  90261. target = localTarget;
  90262. }
  90263. }
  90264. if (checkYaw) {
  90265. var localTarget = BoneLookController._tmpVecs[4];
  90266. target.subtractToRef(bonePos, localTarget);
  90267. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  90268. var yaw = Math.atan2(localTarget.x, localTarget.z);
  90269. var newYaw = yaw;
  90270. if (yaw > this._maxYaw || yaw < this._minYaw) {
  90271. if (xzlen == null) {
  90272. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  90273. }
  90274. if (this._yawRange > Math.PI) {
  90275. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  90276. localTarget.z = this._maxYawCos * xzlen;
  90277. localTarget.x = this._maxYawSin * xzlen;
  90278. newYaw = this._maxYaw;
  90279. }
  90280. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  90281. localTarget.z = this._minYawCos * xzlen;
  90282. localTarget.x = this._minYawSin * xzlen;
  90283. newYaw = this._minYaw;
  90284. }
  90285. }
  90286. else {
  90287. if (yaw > this._maxYaw) {
  90288. localTarget.z = this._maxYawCos * xzlen;
  90289. localTarget.x = this._maxYawSin * xzlen;
  90290. newYaw = this._maxYaw;
  90291. }
  90292. else if (yaw < this._minYaw) {
  90293. localTarget.z = this._minYawCos * xzlen;
  90294. localTarget.x = this._minYawSin * xzlen;
  90295. newYaw = this._minYaw;
  90296. }
  90297. }
  90298. }
  90299. if (this._slerping && this._yawRange > Math.PI) {
  90300. //are we going to be crossing into the min/max region?
  90301. var boneFwd = BoneLookController._tmpVecs[8];
  90302. boneFwd.copyFrom(BABYLON.Axis.Z);
  90303. if (this._transformYawPitch) {
  90304. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  90305. }
  90306. var boneRotMat = BoneLookController._tmpMats[4];
  90307. this._boneQuat.toRotationMatrix(boneRotMat);
  90308. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  90309. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  90310. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  90311. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  90312. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  90313. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  90314. if (angBtwTar > angBtwMidYaw) {
  90315. if (xzlen == null) {
  90316. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  90317. }
  90318. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  90319. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  90320. if (angBtwMin < angBtwMax) {
  90321. newYaw = boneYaw + Math.PI * .75;
  90322. localTarget.z = Math.cos(newYaw) * xzlen;
  90323. localTarget.x = Math.sin(newYaw) * xzlen;
  90324. }
  90325. else {
  90326. newYaw = boneYaw - Math.PI * .75;
  90327. localTarget.z = Math.cos(newYaw) * xzlen;
  90328. localTarget.x = Math.sin(newYaw) * xzlen;
  90329. }
  90330. }
  90331. }
  90332. if (yaw != newYaw) {
  90333. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  90334. localTarget.addInPlace(bonePos);
  90335. target = localTarget;
  90336. }
  90337. }
  90338. }
  90339. var zaxis = BoneLookController._tmpVecs[5];
  90340. var xaxis = BoneLookController._tmpVecs[6];
  90341. var yaxis = BoneLookController._tmpVecs[7];
  90342. var _tmpQuat = BoneLookController._tmpQuat;
  90343. target.subtractToRef(bonePos, zaxis);
  90344. zaxis.normalize();
  90345. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  90346. xaxis.normalize();
  90347. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  90348. yaxis.normalize();
  90349. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  90350. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  90351. return;
  90352. }
  90353. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  90354. return;
  90355. }
  90356. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  90357. return;
  90358. }
  90359. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  90360. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  90361. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  90362. }
  90363. if (this.slerpAmount < 1) {
  90364. if (!this._slerping) {
  90365. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  90366. }
  90367. if (this._transformYawPitch) {
  90368. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  90369. }
  90370. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  90371. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  90372. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  90373. this._slerping = true;
  90374. }
  90375. else {
  90376. if (this._transformYawPitch) {
  90377. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  90378. }
  90379. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  90380. this._slerping = false;
  90381. }
  90382. };
  90383. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  90384. var angDiff = ang2 - ang1;
  90385. angDiff %= Math.PI * 2;
  90386. if (angDiff > Math.PI) {
  90387. angDiff -= Math.PI * 2;
  90388. }
  90389. else if (angDiff < -Math.PI) {
  90390. angDiff += Math.PI * 2;
  90391. }
  90392. return angDiff;
  90393. };
  90394. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  90395. ang1 %= (2 * Math.PI);
  90396. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  90397. ang2 %= (2 * Math.PI);
  90398. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  90399. var ab = 0;
  90400. if (ang1 < ang2) {
  90401. ab = ang2 - ang1;
  90402. }
  90403. else {
  90404. ab = ang1 - ang2;
  90405. }
  90406. if (ab > Math.PI) {
  90407. ab = Math.PI * 2 - ab;
  90408. }
  90409. return ab;
  90410. };
  90411. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  90412. ang %= (2 * Math.PI);
  90413. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  90414. ang1 %= (2 * Math.PI);
  90415. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  90416. ang2 %= (2 * Math.PI);
  90417. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  90418. if (ang1 < ang2) {
  90419. if (ang > ang1 && ang < ang2) {
  90420. return true;
  90421. }
  90422. }
  90423. else {
  90424. if (ang > ang2 && ang < ang1) {
  90425. return true;
  90426. }
  90427. }
  90428. return false;
  90429. };
  90430. 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()];
  90431. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  90432. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  90433. return BoneLookController;
  90434. }());
  90435. BABYLON.BoneLookController = BoneLookController;
  90436. })(BABYLON || (BABYLON = {}));
  90437. //# sourceMappingURL=babylon.boneLookController.js.map
  90438. var BABYLON;
  90439. (function (BABYLON) {
  90440. /**
  90441. * Class used to handle skinning animations
  90442. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  90443. */
  90444. var Skeleton = /** @class */ (function () {
  90445. /**
  90446. * Creates a new skeleton
  90447. * @param name defines the skeleton name
  90448. * @param id defines the skeleton Id
  90449. * @param scene defines the hosting scene
  90450. */
  90451. function Skeleton(
  90452. /** defines the skeleton name */
  90453. name,
  90454. /** defines the skeleton Id */
  90455. id, scene) {
  90456. this.name = name;
  90457. this.id = id;
  90458. /**
  90459. * Gets the list of child bones
  90460. */
  90461. this.bones = new Array();
  90462. /**
  90463. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  90464. */
  90465. this.needInitialSkinMatrix = false;
  90466. this._isDirty = true;
  90467. this._meshesWithPoseMatrix = new Array();
  90468. this._identity = BABYLON.Matrix.Identity();
  90469. this._ranges = {};
  90470. this._lastAbsoluteTransformsUpdateId = -1;
  90471. /**
  90472. * Specifies if the skeleton should be serialized
  90473. */
  90474. this.doNotSerialize = false;
  90475. this._animationPropertiesOverride = null;
  90476. // Events
  90477. /**
  90478. * An observable triggered before computing the skeleton's matrices
  90479. */
  90480. this.onBeforeComputeObservable = new BABYLON.Observable();
  90481. this.bones = [];
  90482. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90483. scene.skeletons.push(this);
  90484. //make sure it will recalculate the matrix next time prepare is called.
  90485. this._isDirty = true;
  90486. }
  90487. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  90488. /**
  90489. * Gets or sets the animation properties override
  90490. */
  90491. get: function () {
  90492. if (!this._animationPropertiesOverride) {
  90493. return this._scene.animationPropertiesOverride;
  90494. }
  90495. return this._animationPropertiesOverride;
  90496. },
  90497. set: function (value) {
  90498. this._animationPropertiesOverride = value;
  90499. },
  90500. enumerable: true,
  90501. configurable: true
  90502. });
  90503. // Members
  90504. /**
  90505. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  90506. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  90507. * @returns a Float32Array containing matrices data
  90508. */
  90509. Skeleton.prototype.getTransformMatrices = function (mesh) {
  90510. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  90511. return mesh._bonesTransformMatrices;
  90512. }
  90513. if (!this._transformMatrices) {
  90514. this.prepare();
  90515. }
  90516. return this._transformMatrices;
  90517. };
  90518. /**
  90519. * Gets the current hosting scene
  90520. * @returns a scene object
  90521. */
  90522. Skeleton.prototype.getScene = function () {
  90523. return this._scene;
  90524. };
  90525. // Methods
  90526. /**
  90527. * Gets a string representing the current skeleton data
  90528. * @param fullDetails defines a boolean indicating if we want a verbose version
  90529. * @returns a string representing the current skeleton data
  90530. */
  90531. Skeleton.prototype.toString = function (fullDetails) {
  90532. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  90533. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  90534. if (fullDetails) {
  90535. ret += ", Ranges: {";
  90536. var first = true;
  90537. for (var name_1 in this._ranges) {
  90538. if (first) {
  90539. ret += ", ";
  90540. first = false;
  90541. }
  90542. ret += name_1;
  90543. }
  90544. ret += "}";
  90545. }
  90546. return ret;
  90547. };
  90548. /**
  90549. * Get bone's index searching by name
  90550. * @param name defines bone's name to search for
  90551. * @return the indice of the bone. Returns -1 if not found
  90552. */
  90553. Skeleton.prototype.getBoneIndexByName = function (name) {
  90554. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  90555. if (this.bones[boneIndex].name === name) {
  90556. return boneIndex;
  90557. }
  90558. }
  90559. return -1;
  90560. };
  90561. /**
  90562. * Creater a new animation range
  90563. * @param name defines the name of the range
  90564. * @param from defines the start key
  90565. * @param to defines the end key
  90566. */
  90567. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  90568. // check name not already in use
  90569. if (!this._ranges[name]) {
  90570. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  90571. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  90572. if (this.bones[i].animations[0]) {
  90573. this.bones[i].animations[0].createRange(name, from, to);
  90574. }
  90575. }
  90576. }
  90577. };
  90578. /**
  90579. * Delete a specific animation range
  90580. * @param name defines the name of the range
  90581. * @param deleteFrames defines if frames must be removed as well
  90582. */
  90583. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  90584. if (deleteFrames === void 0) { deleteFrames = true; }
  90585. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  90586. if (this.bones[i].animations[0]) {
  90587. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  90588. }
  90589. }
  90590. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  90591. };
  90592. /**
  90593. * Gets a specific animation range
  90594. * @param name defines the name of the range to look for
  90595. * @returns the requested animation range or null if not found
  90596. */
  90597. Skeleton.prototype.getAnimationRange = function (name) {
  90598. return this._ranges[name];
  90599. };
  90600. /**
  90601. * Gets the list of all animation ranges defined on this skeleton
  90602. * @returns an array
  90603. */
  90604. Skeleton.prototype.getAnimationRanges = function () {
  90605. var animationRanges = [];
  90606. var name;
  90607. var i = 0;
  90608. for (name in this._ranges) {
  90609. animationRanges[i] = this._ranges[name];
  90610. i++;
  90611. }
  90612. return animationRanges;
  90613. };
  90614. /**
  90615. * Copy animation range from a source skeleton.
  90616. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  90617. * @param source defines the source skeleton
  90618. * @param name defines the name of the range to copy
  90619. * @param rescaleAsRequired defines if rescaling must be applied if required
  90620. * @returns true if operation was successful
  90621. */
  90622. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  90623. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  90624. if (this._ranges[name] || !source.getAnimationRange(name)) {
  90625. return false;
  90626. }
  90627. var ret = true;
  90628. var frameOffset = this._getHighestAnimationFrame() + 1;
  90629. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  90630. var boneDict = {};
  90631. var sourceBones = source.bones;
  90632. var nBones;
  90633. var i;
  90634. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  90635. boneDict[sourceBones[i].name] = sourceBones[i];
  90636. }
  90637. if (this.bones.length !== sourceBones.length) {
  90638. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  90639. ret = false;
  90640. }
  90641. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  90642. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  90643. var boneName = this.bones[i].name;
  90644. var sourceBone = boneDict[boneName];
  90645. if (sourceBone) {
  90646. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  90647. }
  90648. else {
  90649. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  90650. ret = false;
  90651. }
  90652. }
  90653. // do not call createAnimationRange(), since it also is done to bones, which was already done
  90654. var range = source.getAnimationRange(name);
  90655. if (range) {
  90656. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  90657. }
  90658. return ret;
  90659. };
  90660. /**
  90661. * Forces the skeleton to go to rest pose
  90662. */
  90663. Skeleton.prototype.returnToRest = function () {
  90664. for (var index = 0; index < this.bones.length; index++) {
  90665. this.bones[index].returnToRest();
  90666. }
  90667. };
  90668. Skeleton.prototype._getHighestAnimationFrame = function () {
  90669. var ret = 0;
  90670. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  90671. if (this.bones[i].animations[0]) {
  90672. var highest = this.bones[i].animations[0].getHighestFrame();
  90673. if (ret < highest) {
  90674. ret = highest;
  90675. }
  90676. }
  90677. }
  90678. return ret;
  90679. };
  90680. /**
  90681. * Begin a specific animation range
  90682. * @param name defines the name of the range to start
  90683. * @param loop defines if looping must be turned on (false by default)
  90684. * @param speedRatio defines the speed ratio to apply (1 by default)
  90685. * @param onAnimationEnd defines a callback which will be called when animation will end
  90686. * @returns a new animatable
  90687. */
  90688. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  90689. var range = this.getAnimationRange(name);
  90690. if (!range) {
  90691. return null;
  90692. }
  90693. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  90694. };
  90695. /** @hidden */
  90696. Skeleton.prototype._markAsDirty = function () {
  90697. this._isDirty = true;
  90698. };
  90699. /** @hidden */
  90700. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  90701. this._meshesWithPoseMatrix.push(mesh);
  90702. };
  90703. /** @hidden */
  90704. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  90705. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  90706. if (index > -1) {
  90707. this._meshesWithPoseMatrix.splice(index, 1);
  90708. }
  90709. };
  90710. /** @hidden */
  90711. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  90712. this.onBeforeComputeObservable.notifyObservers(this);
  90713. for (var index = 0; index < this.bones.length; index++) {
  90714. var bone = this.bones[index];
  90715. var parentBone = bone.getParent();
  90716. if (parentBone) {
  90717. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  90718. }
  90719. else {
  90720. if (initialSkinMatrix) {
  90721. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  90722. }
  90723. else {
  90724. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  90725. }
  90726. }
  90727. if (bone._index !== -1) {
  90728. var mappedIndex = bone._index === null ? index : bone._index;
  90729. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  90730. }
  90731. }
  90732. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  90733. };
  90734. /**
  90735. * Build all resources required to render a skeleton
  90736. */
  90737. Skeleton.prototype.prepare = function () {
  90738. if (!this._isDirty) {
  90739. return;
  90740. }
  90741. if (this.needInitialSkinMatrix) {
  90742. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  90743. var mesh = this._meshesWithPoseMatrix[index];
  90744. var poseMatrix = mesh.getPoseMatrix();
  90745. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  90746. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  90747. }
  90748. if (this._synchronizedWithMesh !== mesh) {
  90749. this._synchronizedWithMesh = mesh;
  90750. // Prepare bones
  90751. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  90752. var bone = this.bones[boneIndex];
  90753. if (!bone.getParent()) {
  90754. var matrix = bone.getBaseMatrix();
  90755. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  90756. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  90757. }
  90758. }
  90759. }
  90760. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  90761. }
  90762. }
  90763. else {
  90764. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  90765. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  90766. }
  90767. this._computeTransformMatrices(this._transformMatrices, null);
  90768. }
  90769. this._isDirty = false;
  90770. this._scene._activeBones.addCount(this.bones.length, false);
  90771. };
  90772. /**
  90773. * Gets the list of animatables currently running for this skeleton
  90774. * @returns an array of animatables
  90775. */
  90776. Skeleton.prototype.getAnimatables = function () {
  90777. if (!this._animatables || this._animatables.length !== this.bones.length) {
  90778. this._animatables = [];
  90779. for (var index = 0; index < this.bones.length; index++) {
  90780. this._animatables.push(this.bones[index]);
  90781. }
  90782. }
  90783. return this._animatables;
  90784. };
  90785. /**
  90786. * Clone the current skeleton
  90787. * @param name defines the name of the new skeleton
  90788. * @param id defines the id of the enw skeleton
  90789. * @returns the new skeleton
  90790. */
  90791. Skeleton.prototype.clone = function (name, id) {
  90792. var result = new Skeleton(name, id || name, this._scene);
  90793. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  90794. for (var index = 0; index < this.bones.length; index++) {
  90795. var source = this.bones[index];
  90796. var parentBone = null;
  90797. var parent_1 = source.getParent();
  90798. if (parent_1) {
  90799. var parentIndex = this.bones.indexOf(parent_1);
  90800. parentBone = result.bones[parentIndex];
  90801. }
  90802. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  90803. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  90804. }
  90805. if (this._ranges) {
  90806. result._ranges = {};
  90807. for (var rangeName in this._ranges) {
  90808. var range = this._ranges[rangeName];
  90809. if (range) {
  90810. result._ranges[rangeName] = range.clone();
  90811. }
  90812. }
  90813. }
  90814. this._isDirty = true;
  90815. return result;
  90816. };
  90817. /**
  90818. * Enable animation blending for this skeleton
  90819. * @param blendingSpeed defines the blending speed to apply
  90820. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  90821. */
  90822. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  90823. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  90824. this.bones.forEach(function (bone) {
  90825. bone.animations.forEach(function (animation) {
  90826. animation.enableBlending = true;
  90827. animation.blendingSpeed = blendingSpeed;
  90828. });
  90829. });
  90830. };
  90831. /**
  90832. * Releases all resources associated with the current skeleton
  90833. */
  90834. Skeleton.prototype.dispose = function () {
  90835. this._meshesWithPoseMatrix = [];
  90836. // Animations
  90837. this.getScene().stopAnimation(this);
  90838. // Remove from scene
  90839. this.getScene().removeSkeleton(this);
  90840. };
  90841. /**
  90842. * Serialize the skeleton in a JSON object
  90843. * @returns a JSON object
  90844. */
  90845. Skeleton.prototype.serialize = function () {
  90846. var serializationObject = {};
  90847. serializationObject.name = this.name;
  90848. serializationObject.id = this.id;
  90849. if (this.dimensionsAtRest) {
  90850. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  90851. }
  90852. serializationObject.bones = [];
  90853. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  90854. for (var index = 0; index < this.bones.length; index++) {
  90855. var bone = this.bones[index];
  90856. var parent_2 = bone.getParent();
  90857. var serializedBone = {
  90858. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  90859. name: bone.name,
  90860. matrix: bone.getBaseMatrix().toArray(),
  90861. rest: bone.getRestPose().toArray()
  90862. };
  90863. serializationObject.bones.push(serializedBone);
  90864. if (bone.length) {
  90865. serializedBone.length = bone.length;
  90866. }
  90867. if (bone.metadata) {
  90868. serializedBone.metadata = bone.metadata;
  90869. }
  90870. if (bone.animations && bone.animations.length > 0) {
  90871. serializedBone.animation = bone.animations[0].serialize();
  90872. }
  90873. serializationObject.ranges = [];
  90874. for (var name in this._ranges) {
  90875. var source = this._ranges[name];
  90876. if (!source) {
  90877. continue;
  90878. }
  90879. var range = {};
  90880. range.name = name;
  90881. range.from = source.from;
  90882. range.to = source.to;
  90883. serializationObject.ranges.push(range);
  90884. }
  90885. }
  90886. return serializationObject;
  90887. };
  90888. /**
  90889. * Creates a new skeleton from serialized data
  90890. * @param parsedSkeleton defines the serialized data
  90891. * @param scene defines the hosting scene
  90892. * @returns a new skeleton
  90893. */
  90894. Skeleton.Parse = function (parsedSkeleton, scene) {
  90895. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  90896. if (parsedSkeleton.dimensionsAtRest) {
  90897. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  90898. }
  90899. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  90900. var index;
  90901. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  90902. var parsedBone = parsedSkeleton.bones[index];
  90903. var parentBone = null;
  90904. if (parsedBone.parentBoneIndex > -1) {
  90905. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  90906. }
  90907. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  90908. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  90909. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  90910. bone.id = parsedBone.id;
  90911. }
  90912. if (parsedBone.length) {
  90913. bone.length = parsedBone.length;
  90914. }
  90915. if (parsedBone.metadata) {
  90916. bone.metadata = parsedBone.metadata;
  90917. }
  90918. if (parsedBone.animation) {
  90919. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  90920. }
  90921. }
  90922. // placed after bones, so createAnimationRange can cascade down
  90923. if (parsedSkeleton.ranges) {
  90924. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  90925. var data = parsedSkeleton.ranges[index];
  90926. skeleton.createAnimationRange(data.name, data.from, data.to);
  90927. }
  90928. }
  90929. return skeleton;
  90930. };
  90931. /**
  90932. * Compute all node absolute transforms
  90933. * @param forceUpdate defines if computation must be done even if cache is up to date
  90934. */
  90935. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  90936. if (forceUpdate === void 0) { forceUpdate = false; }
  90937. var renderId = this._scene.getRenderId();
  90938. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  90939. this.bones[0].computeAbsoluteTransforms();
  90940. this._lastAbsoluteTransformsUpdateId = renderId;
  90941. }
  90942. };
  90943. /**
  90944. * Gets the root pose matrix
  90945. * @returns a matrix
  90946. */
  90947. Skeleton.prototype.getPoseMatrix = function () {
  90948. var poseMatrix = null;
  90949. if (this._meshesWithPoseMatrix.length > 0) {
  90950. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  90951. }
  90952. return poseMatrix;
  90953. };
  90954. /**
  90955. * Sorts bones per internal index
  90956. */
  90957. Skeleton.prototype.sortBones = function () {
  90958. var bones = new Array();
  90959. var visited = new Array(this.bones.length);
  90960. for (var index = 0; index < this.bones.length; index++) {
  90961. this._sortBones(index, bones, visited);
  90962. }
  90963. this.bones = bones;
  90964. };
  90965. Skeleton.prototype._sortBones = function (index, bones, visited) {
  90966. if (visited[index]) {
  90967. return;
  90968. }
  90969. visited[index] = true;
  90970. var bone = this.bones[index];
  90971. if (bone._index === undefined) {
  90972. bone._index = index;
  90973. }
  90974. var parentBone = bone.getParent();
  90975. if (parentBone) {
  90976. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  90977. }
  90978. bones.push(bone);
  90979. };
  90980. return Skeleton;
  90981. }());
  90982. BABYLON.Skeleton = Skeleton;
  90983. })(BABYLON || (BABYLON = {}));
  90984. //# sourceMappingURL=babylon.skeleton.js.map
  90985. var BABYLON;
  90986. (function (BABYLON) {
  90987. ;
  90988. /**
  90989. * This groups tools to convert HDR texture to native colors array.
  90990. */
  90991. var HDRTools = /** @class */ (function () {
  90992. function HDRTools() {
  90993. }
  90994. HDRTools.Ldexp = function (mantissa, exponent) {
  90995. if (exponent > 1023) {
  90996. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  90997. }
  90998. if (exponent < -1074) {
  90999. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  91000. }
  91001. return mantissa * Math.pow(2, exponent);
  91002. };
  91003. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  91004. if (exponent > 0) { /*nonzero pixel*/
  91005. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  91006. float32array[index + 0] = red * exponent;
  91007. float32array[index + 1] = green * exponent;
  91008. float32array[index + 2] = blue * exponent;
  91009. }
  91010. else {
  91011. float32array[index + 0] = 0;
  91012. float32array[index + 1] = 0;
  91013. float32array[index + 2] = 0;
  91014. }
  91015. };
  91016. HDRTools.readStringLine = function (uint8array, startIndex) {
  91017. var line = "";
  91018. var character = "";
  91019. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  91020. character = String.fromCharCode(uint8array[i]);
  91021. if (character == "\n") {
  91022. break;
  91023. }
  91024. line += character;
  91025. }
  91026. return line;
  91027. };
  91028. /**
  91029. * Reads header information from an RGBE texture stored in a native array.
  91030. * More information on this format are available here:
  91031. * https://en.wikipedia.org/wiki/RGBE_image_format
  91032. *
  91033. * @param uint8array The binary file stored in native array.
  91034. * @return The header information.
  91035. */
  91036. HDRTools.RGBE_ReadHeader = function (uint8array) {
  91037. var height = 0;
  91038. var width = 0;
  91039. var line = this.readStringLine(uint8array, 0);
  91040. if (line[0] != '#' || line[1] != '?') {
  91041. throw "Bad HDR Format.";
  91042. }
  91043. var endOfHeader = false;
  91044. var findFormat = false;
  91045. var lineIndex = 0;
  91046. do {
  91047. lineIndex += (line.length + 1);
  91048. line = this.readStringLine(uint8array, lineIndex);
  91049. if (line == "FORMAT=32-bit_rle_rgbe") {
  91050. findFormat = true;
  91051. }
  91052. else if (line.length == 0) {
  91053. endOfHeader = true;
  91054. }
  91055. } while (!endOfHeader);
  91056. if (!findFormat) {
  91057. throw "HDR Bad header format, unsupported FORMAT";
  91058. }
  91059. lineIndex += (line.length + 1);
  91060. line = this.readStringLine(uint8array, lineIndex);
  91061. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  91062. var match = sizeRegexp.exec(line);
  91063. // TODO. Support +Y and -X if needed.
  91064. if (!match || match.length < 3) {
  91065. throw "HDR Bad header format, no size";
  91066. }
  91067. width = parseInt(match[2]);
  91068. height = parseInt(match[1]);
  91069. if (width < 8 || width > 0x7fff) {
  91070. throw "HDR Bad header format, unsupported size";
  91071. }
  91072. lineIndex += (line.length + 1);
  91073. return {
  91074. height: height,
  91075. width: width,
  91076. dataPosition: lineIndex
  91077. };
  91078. };
  91079. /**
  91080. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  91081. * This RGBE texture needs to store the information as a panorama.
  91082. *
  91083. * More information on this format are available here:
  91084. * https://en.wikipedia.org/wiki/RGBE_image_format
  91085. *
  91086. * @param buffer The binary file stored in an array buffer.
  91087. * @param size The expected size of the extracted cubemap.
  91088. * @return The Cube Map information.
  91089. */
  91090. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  91091. var uint8array = new Uint8Array(buffer);
  91092. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  91093. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  91094. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  91095. return cubeMapData;
  91096. };
  91097. /**
  91098. * Returns the pixels data extracted from an RGBE texture.
  91099. * This pixels will be stored left to right up to down in the R G B order in one array.
  91100. *
  91101. * More information on this format are available here:
  91102. * https://en.wikipedia.org/wiki/RGBE_image_format
  91103. *
  91104. * @param uint8array The binary file stored in an array buffer.
  91105. * @param hdrInfo The header information of the file.
  91106. * @return The pixels data in RGB right to left up to down order.
  91107. */
  91108. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  91109. // Keep for multi format supports.
  91110. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  91111. };
  91112. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  91113. var num_scanlines = hdrInfo.height;
  91114. var scanline_width = hdrInfo.width;
  91115. var a, b, c, d, count;
  91116. var dataIndex = hdrInfo.dataPosition;
  91117. var index = 0, endIndex = 0, i = 0;
  91118. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  91119. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  91120. // 3 channels of 4 bytes per pixel in float.
  91121. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  91122. var resultArray = new Float32Array(resultBuffer);
  91123. // read in each successive scanline
  91124. while (num_scanlines > 0) {
  91125. a = uint8array[dataIndex++];
  91126. b = uint8array[dataIndex++];
  91127. c = uint8array[dataIndex++];
  91128. d = uint8array[dataIndex++];
  91129. if (a != 2 || b != 2 || (c & 0x80)) {
  91130. // this file is not run length encoded
  91131. throw "HDR Bad header format, not RLE";
  91132. }
  91133. if (((c << 8) | d) != scanline_width) {
  91134. throw "HDR Bad header format, wrong scan line width";
  91135. }
  91136. index = 0;
  91137. // read each of the four channels for the scanline into the buffer
  91138. for (i = 0; i < 4; i++) {
  91139. endIndex = (i + 1) * scanline_width;
  91140. while (index < endIndex) {
  91141. a = uint8array[dataIndex++];
  91142. b = uint8array[dataIndex++];
  91143. if (a > 128) {
  91144. // a run of the same value
  91145. count = a - 128;
  91146. if ((count == 0) || (count > endIndex - index)) {
  91147. throw "HDR Bad Format, bad scanline data (run)";
  91148. }
  91149. while (count-- > 0) {
  91150. scanLineArray[index++] = b;
  91151. }
  91152. }
  91153. else {
  91154. // a non-run
  91155. count = a;
  91156. if ((count == 0) || (count > endIndex - index)) {
  91157. throw "HDR Bad Format, bad scanline data (non-run)";
  91158. }
  91159. scanLineArray[index++] = b;
  91160. if (--count > 0) {
  91161. for (var j = 0; j < count; j++) {
  91162. scanLineArray[index++] = uint8array[dataIndex++];
  91163. }
  91164. }
  91165. }
  91166. }
  91167. }
  91168. // now convert data from buffer into floats
  91169. for (i = 0; i < scanline_width; i++) {
  91170. a = scanLineArray[i];
  91171. b = scanLineArray[i + scanline_width];
  91172. c = scanLineArray[i + 2 * scanline_width];
  91173. d = scanLineArray[i + 3 * scanline_width];
  91174. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  91175. }
  91176. num_scanlines--;
  91177. }
  91178. return resultArray;
  91179. };
  91180. return HDRTools;
  91181. }());
  91182. BABYLON.HDRTools = HDRTools;
  91183. })(BABYLON || (BABYLON = {}));
  91184. //# sourceMappingURL=babylon.hdr.js.map
  91185. var BABYLON;
  91186. (function (BABYLON) {
  91187. /**
  91188. * This represents a texture coming from an HDR input.
  91189. *
  91190. * The only supported format is currently panorama picture stored in RGBE format.
  91191. * Example of such files can be found on HDRLib: http://hdrlib.com/
  91192. */
  91193. var HDRCubeTexture = /** @class */ (function (_super) {
  91194. __extends(HDRCubeTexture, _super);
  91195. /**
  91196. * Instantiates an HDRTexture from the following parameters.
  91197. *
  91198. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  91199. * @param scene The scene the texture will be used in
  91200. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  91201. * @param noMipmap Forces to not generate the mipmap if true
  91202. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  91203. * @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)
  91204. * @param reserved Reserved flag for internal use.
  91205. */
  91206. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  91207. if (noMipmap === void 0) { noMipmap = false; }
  91208. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91209. if (gammaSpace === void 0) { gammaSpace = false; }
  91210. if (reserved === void 0) { reserved = false; }
  91211. if (onLoad === void 0) { onLoad = null; }
  91212. if (onError === void 0) { onError = null; }
  91213. var _this = _super.call(this, scene) || this;
  91214. _this._generateHarmonics = true;
  91215. _this._onLoad = null;
  91216. _this._onError = null;
  91217. /**
  91218. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  91219. */
  91220. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  91221. _this._isBlocking = true;
  91222. _this._rotationY = 0;
  91223. /**
  91224. * Gets or sets the center of the bounding box associated with the cube texture
  91225. * It must define where the camera used to render the texture was set
  91226. */
  91227. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  91228. if (!url) {
  91229. return _this;
  91230. }
  91231. _this.name = url;
  91232. _this.url = url;
  91233. _this.hasAlpha = false;
  91234. _this.isCube = true;
  91235. _this._textureMatrix = BABYLON.Matrix.Identity();
  91236. _this._onLoad = onLoad;
  91237. _this._onError = onError;
  91238. _this.gammaSpace = gammaSpace;
  91239. _this._noMipmap = noMipmap;
  91240. _this._size = size;
  91241. _this._texture = _this._getFromCache(url, _this._noMipmap);
  91242. if (!_this._texture) {
  91243. if (!scene.useDelayedTextureLoading) {
  91244. _this.loadTexture();
  91245. }
  91246. else {
  91247. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  91248. }
  91249. }
  91250. return _this;
  91251. }
  91252. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  91253. /**
  91254. * Gets wether or not the texture is blocking during loading.
  91255. */
  91256. get: function () {
  91257. return this._isBlocking;
  91258. },
  91259. /**
  91260. * Sets wether or not the texture is blocking during loading.
  91261. */
  91262. set: function (value) {
  91263. this._isBlocking = value;
  91264. },
  91265. enumerable: true,
  91266. configurable: true
  91267. });
  91268. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  91269. /**
  91270. * Gets texture matrix rotation angle around Y axis radians.
  91271. */
  91272. get: function () {
  91273. return this._rotationY;
  91274. },
  91275. /**
  91276. * Sets texture matrix rotation angle around Y axis in radians.
  91277. */
  91278. set: function (value) {
  91279. this._rotationY = value;
  91280. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  91281. },
  91282. enumerable: true,
  91283. configurable: true
  91284. });
  91285. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  91286. get: function () {
  91287. return this._boundingBoxSize;
  91288. },
  91289. /**
  91290. * Gets or sets the size of the bounding box associated with the cube texture
  91291. * When defined, the cubemap will switch to local mode
  91292. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  91293. * @example https://www.babylonjs-playground.com/#RNASML
  91294. */
  91295. set: function (value) {
  91296. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  91297. return;
  91298. }
  91299. this._boundingBoxSize = value;
  91300. var scene = this.getScene();
  91301. if (scene) {
  91302. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  91303. }
  91304. },
  91305. enumerable: true,
  91306. configurable: true
  91307. });
  91308. /**
  91309. * Occurs when the file is raw .hdr file.
  91310. */
  91311. HDRCubeTexture.prototype.loadTexture = function () {
  91312. var _this = this;
  91313. var callback = function (buffer) {
  91314. _this.lodGenerationOffset = 0.0;
  91315. _this.lodGenerationScale = 0.8;
  91316. var scene = _this.getScene();
  91317. if (!scene) {
  91318. return null;
  91319. }
  91320. // Extract the raw linear data.
  91321. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  91322. // Generate harmonics if needed.
  91323. if (_this._generateHarmonics) {
  91324. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  91325. _this.sphericalPolynomial = sphericalPolynomial;
  91326. }
  91327. var results = [];
  91328. var byteArray = null;
  91329. // Push each faces.
  91330. for (var j = 0; j < 6; j++) {
  91331. // Create uintarray fallback.
  91332. if (!scene.getEngine().getCaps().textureFloat) {
  91333. // 3 channels of 1 bytes per pixel in bytes.
  91334. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  91335. byteArray = new Uint8Array(byteBuffer);
  91336. }
  91337. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  91338. // If special cases.
  91339. if (_this.gammaSpace || byteArray) {
  91340. for (var i = 0; i < _this._size * _this._size; i++) {
  91341. // Put in gamma space if requested.
  91342. if (_this.gammaSpace) {
  91343. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  91344. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  91345. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  91346. }
  91347. // Convert to int texture for fallback.
  91348. if (byteArray) {
  91349. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  91350. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  91351. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  91352. // May use luminance instead if the result is not accurate.
  91353. var max = Math.max(Math.max(r, g), b);
  91354. if (max > 255) {
  91355. var scale = 255 / max;
  91356. r *= scale;
  91357. g *= scale;
  91358. b *= scale;
  91359. }
  91360. byteArray[(i * 3) + 0] = r;
  91361. byteArray[(i * 3) + 1] = g;
  91362. byteArray[(i * 3) + 2] = b;
  91363. }
  91364. }
  91365. }
  91366. if (byteArray) {
  91367. results.push(byteArray);
  91368. }
  91369. else {
  91370. results.push(dataFace);
  91371. }
  91372. }
  91373. return results;
  91374. };
  91375. var scene = this.getScene();
  91376. if (scene) {
  91377. 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);
  91378. }
  91379. };
  91380. HDRCubeTexture.prototype.clone = function () {
  91381. var scene = this.getScene();
  91382. if (!scene) {
  91383. return this;
  91384. }
  91385. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  91386. // Base texture
  91387. newTexture.level = this.level;
  91388. newTexture.wrapU = this.wrapU;
  91389. newTexture.wrapV = this.wrapV;
  91390. newTexture.coordinatesIndex = this.coordinatesIndex;
  91391. newTexture.coordinatesMode = this.coordinatesMode;
  91392. return newTexture;
  91393. };
  91394. // Methods
  91395. HDRCubeTexture.prototype.delayLoad = function () {
  91396. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  91397. return;
  91398. }
  91399. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  91400. this._texture = this._getFromCache(this.url, this._noMipmap);
  91401. if (!this._texture) {
  91402. this.loadTexture();
  91403. }
  91404. };
  91405. /**
  91406. * Get the texture reflection matrix used to rotate/transform the reflection.
  91407. * @returns the reflection matrix
  91408. */
  91409. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  91410. return this._textureMatrix;
  91411. };
  91412. /**
  91413. * Set the texture reflection matrix used to rotate/transform the reflection.
  91414. * @param value Define the reflection matrix to set
  91415. */
  91416. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  91417. this._textureMatrix = value;
  91418. };
  91419. /**
  91420. * Parses a JSON representation of an HDR Texture in order to create the texture
  91421. * @param parsedTexture Define the JSON representation
  91422. * @param scene Define the scene the texture should be created in
  91423. * @param rootUrl Define the root url in case we need to load relative dependencies
  91424. * @returns the newly created texture after parsing
  91425. */
  91426. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  91427. var texture = null;
  91428. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  91429. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  91430. texture.name = parsedTexture.name;
  91431. texture.hasAlpha = parsedTexture.hasAlpha;
  91432. texture.level = parsedTexture.level;
  91433. texture.coordinatesMode = parsedTexture.coordinatesMode;
  91434. texture.isBlocking = parsedTexture.isBlocking;
  91435. }
  91436. if (texture) {
  91437. if (parsedTexture.boundingBoxPosition) {
  91438. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  91439. }
  91440. if (parsedTexture.boundingBoxSize) {
  91441. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  91442. }
  91443. if (parsedTexture.rotationY) {
  91444. texture.rotationY = parsedTexture.rotationY;
  91445. }
  91446. }
  91447. return texture;
  91448. };
  91449. HDRCubeTexture.prototype.serialize = function () {
  91450. if (!this.name) {
  91451. return null;
  91452. }
  91453. var serializationObject = {};
  91454. serializationObject.name = this.name;
  91455. serializationObject.hasAlpha = this.hasAlpha;
  91456. serializationObject.isCube = true;
  91457. serializationObject.level = this.level;
  91458. serializationObject.size = this._size;
  91459. serializationObject.coordinatesMode = this.coordinatesMode;
  91460. serializationObject.useInGammaSpace = this.gammaSpace;
  91461. serializationObject.generateHarmonics = this._generateHarmonics;
  91462. serializationObject.customType = "BABYLON.HDRCubeTexture";
  91463. serializationObject.noMipmap = this._noMipmap;
  91464. serializationObject.isBlocking = this._isBlocking;
  91465. serializationObject.rotationY = this._rotationY;
  91466. return serializationObject;
  91467. };
  91468. HDRCubeTexture._facesMapping = [
  91469. "right",
  91470. "left",
  91471. "up",
  91472. "down",
  91473. "front",
  91474. "back"
  91475. ];
  91476. return HDRCubeTexture;
  91477. }(BABYLON.BaseTexture));
  91478. BABYLON.HDRCubeTexture = HDRCubeTexture;
  91479. })(BABYLON || (BABYLON = {}));
  91480. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  91481. var BABYLON;
  91482. (function (BABYLON) {
  91483. /**
  91484. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  91485. */
  91486. var PanoramaToCubeMapTools = /** @class */ (function () {
  91487. function PanoramaToCubeMapTools() {
  91488. }
  91489. /**
  91490. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  91491. *
  91492. * @param float32Array The source data.
  91493. * @param inputWidth The width of the input panorama.
  91494. * @param inputhHeight The height of the input panorama.
  91495. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  91496. * @return The cubemap data
  91497. */
  91498. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  91499. if (!float32Array) {
  91500. throw "ConvertPanoramaToCubemap: input cannot be null";
  91501. }
  91502. if (float32Array.length != inputWidth * inputHeight * 3) {
  91503. throw "ConvertPanoramaToCubemap: input size is wrong";
  91504. }
  91505. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  91506. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  91507. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  91508. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  91509. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  91510. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  91511. return {
  91512. front: textureFront,
  91513. back: textureBack,
  91514. left: textureLeft,
  91515. right: textureRight,
  91516. up: textureUp,
  91517. down: textureDown,
  91518. size: size,
  91519. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  91520. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  91521. gammaSpace: false,
  91522. };
  91523. };
  91524. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  91525. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  91526. var textureArray = new Float32Array(buffer);
  91527. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  91528. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  91529. var dy = 1 / texSize;
  91530. var fy = 0;
  91531. for (var y = 0; y < texSize; y++) {
  91532. var xv1 = faceData[0];
  91533. var xv2 = faceData[2];
  91534. for (var x = 0; x < texSize; x++) {
  91535. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  91536. v.normalize();
  91537. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  91538. // 3 channels per pixels
  91539. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  91540. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  91541. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  91542. xv1 = xv1.add(rotDX1);
  91543. xv2 = xv2.add(rotDX2);
  91544. }
  91545. fy += dy;
  91546. }
  91547. return textureArray;
  91548. };
  91549. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  91550. var theta = Math.atan2(vDir.z, vDir.x);
  91551. var phi = Math.acos(vDir.y);
  91552. while (theta < -Math.PI)
  91553. theta += 2 * Math.PI;
  91554. while (theta > Math.PI)
  91555. theta -= 2 * Math.PI;
  91556. var dx = theta / Math.PI;
  91557. var dy = phi / Math.PI;
  91558. // recenter.
  91559. dx = dx * 0.5 + 0.5;
  91560. var px = Math.round(dx * inputWidth);
  91561. if (px < 0)
  91562. px = 0;
  91563. else if (px >= inputWidth)
  91564. px = inputWidth - 1;
  91565. var py = Math.round(dy * inputHeight);
  91566. if (py < 0)
  91567. py = 0;
  91568. else if (py >= inputHeight)
  91569. py = inputHeight - 1;
  91570. var inputY = (inputHeight - py - 1);
  91571. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  91572. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  91573. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  91574. return {
  91575. r: r,
  91576. g: g,
  91577. b: b
  91578. };
  91579. };
  91580. PanoramaToCubeMapTools.FACE_FRONT = [
  91581. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  91582. new BABYLON.Vector3(1.0, -1.0, -1.0),
  91583. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  91584. new BABYLON.Vector3(1.0, 1.0, -1.0)
  91585. ];
  91586. PanoramaToCubeMapTools.FACE_BACK = [
  91587. new BABYLON.Vector3(1.0, -1.0, 1.0),
  91588. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  91589. new BABYLON.Vector3(1.0, 1.0, 1.0),
  91590. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  91591. ];
  91592. PanoramaToCubeMapTools.FACE_RIGHT = [
  91593. new BABYLON.Vector3(1.0, -1.0, -1.0),
  91594. new BABYLON.Vector3(1.0, -1.0, 1.0),
  91595. new BABYLON.Vector3(1.0, 1.0, -1.0),
  91596. new BABYLON.Vector3(1.0, 1.0, 1.0)
  91597. ];
  91598. PanoramaToCubeMapTools.FACE_LEFT = [
  91599. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  91600. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  91601. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  91602. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  91603. ];
  91604. PanoramaToCubeMapTools.FACE_DOWN = [
  91605. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  91606. new BABYLON.Vector3(1.0, 1.0, -1.0),
  91607. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  91608. new BABYLON.Vector3(1.0, 1.0, 1.0)
  91609. ];
  91610. PanoramaToCubeMapTools.FACE_UP = [
  91611. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  91612. new BABYLON.Vector3(1.0, -1.0, 1.0),
  91613. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  91614. new BABYLON.Vector3(1.0, -1.0, -1.0)
  91615. ];
  91616. return PanoramaToCubeMapTools;
  91617. }());
  91618. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  91619. })(BABYLON || (BABYLON = {}));
  91620. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  91621. var BABYLON;
  91622. (function (BABYLON) {
  91623. var IndexedVector2 = /** @class */ (function (_super) {
  91624. __extends(IndexedVector2, _super);
  91625. function IndexedVector2(original, index) {
  91626. var _this = _super.call(this, original.x, original.y) || this;
  91627. _this.index = index;
  91628. return _this;
  91629. }
  91630. return IndexedVector2;
  91631. }(BABYLON.Vector2));
  91632. var PolygonPoints = /** @class */ (function () {
  91633. function PolygonPoints() {
  91634. this.elements = new Array();
  91635. }
  91636. PolygonPoints.prototype.add = function (originalPoints) {
  91637. var _this = this;
  91638. var result = new Array();
  91639. originalPoints.forEach(function (point) {
  91640. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  91641. var newPoint = new IndexedVector2(point, _this.elements.length);
  91642. result.push(newPoint);
  91643. _this.elements.push(newPoint);
  91644. }
  91645. });
  91646. return result;
  91647. };
  91648. PolygonPoints.prototype.computeBounds = function () {
  91649. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  91650. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  91651. this.elements.forEach(function (point) {
  91652. // x
  91653. if (point.x < lmin.x) {
  91654. lmin.x = point.x;
  91655. }
  91656. else if (point.x > lmax.x) {
  91657. lmax.x = point.x;
  91658. }
  91659. // y
  91660. if (point.y < lmin.y) {
  91661. lmin.y = point.y;
  91662. }
  91663. else if (point.y > lmax.y) {
  91664. lmax.y = point.y;
  91665. }
  91666. });
  91667. return {
  91668. min: lmin,
  91669. max: lmax,
  91670. width: lmax.x - lmin.x,
  91671. height: lmax.y - lmin.y
  91672. };
  91673. };
  91674. return PolygonPoints;
  91675. }());
  91676. var Polygon = /** @class */ (function () {
  91677. function Polygon() {
  91678. }
  91679. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  91680. return [
  91681. new BABYLON.Vector2(xmin, ymin),
  91682. new BABYLON.Vector2(xmax, ymin),
  91683. new BABYLON.Vector2(xmax, ymax),
  91684. new BABYLON.Vector2(xmin, ymax)
  91685. ];
  91686. };
  91687. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  91688. if (cx === void 0) { cx = 0; }
  91689. if (cy === void 0) { cy = 0; }
  91690. if (numberOfSides === void 0) { numberOfSides = 32; }
  91691. var result = new Array();
  91692. var angle = 0;
  91693. var increment = (Math.PI * 2) / numberOfSides;
  91694. for (var i = 0; i < numberOfSides; i++) {
  91695. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  91696. angle -= increment;
  91697. }
  91698. return result;
  91699. };
  91700. Polygon.Parse = function (input) {
  91701. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  91702. var i, result = [];
  91703. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  91704. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  91705. }
  91706. return result;
  91707. };
  91708. Polygon.StartingAt = function (x, y) {
  91709. return BABYLON.Path2.StartingAt(x, y);
  91710. };
  91711. return Polygon;
  91712. }());
  91713. BABYLON.Polygon = Polygon;
  91714. var PolygonMeshBuilder = /** @class */ (function () {
  91715. function PolygonMeshBuilder(name, contours, scene) {
  91716. this._points = new PolygonPoints();
  91717. this._outlinepoints = new PolygonPoints();
  91718. this._holes = new Array();
  91719. this._epoints = new Array();
  91720. this._eholes = new Array();
  91721. this._name = name;
  91722. this._scene = scene;
  91723. var points;
  91724. if (contours instanceof BABYLON.Path2) {
  91725. points = contours.getPoints();
  91726. }
  91727. else {
  91728. points = contours;
  91729. }
  91730. this._addToepoint(points);
  91731. this._points.add(points);
  91732. this._outlinepoints.add(points);
  91733. if (typeof earcut === 'undefined') {
  91734. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  91735. }
  91736. }
  91737. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  91738. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  91739. var p = points_1[_i];
  91740. this._epoints.push(p.x, p.y);
  91741. }
  91742. };
  91743. PolygonMeshBuilder.prototype.addHole = function (hole) {
  91744. this._points.add(hole);
  91745. var holepoints = new PolygonPoints();
  91746. holepoints.add(hole);
  91747. this._holes.push(holepoints);
  91748. this._eholes.push(this._epoints.length / 2);
  91749. this._addToepoint(hole);
  91750. return this;
  91751. };
  91752. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  91753. var _this = this;
  91754. if (updatable === void 0) { updatable = false; }
  91755. if (depth === void 0) { depth = 0; }
  91756. var result = new BABYLON.Mesh(this._name, this._scene);
  91757. var normals = new Array();
  91758. var positions = new Array();
  91759. var uvs = new Array();
  91760. var bounds = this._points.computeBounds();
  91761. this._points.elements.forEach(function (p) {
  91762. normals.push(0, 1.0, 0);
  91763. positions.push(p.x, 0, p.y);
  91764. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  91765. });
  91766. var indices = new Array();
  91767. var res = earcut(this._epoints, this._eholes, 2);
  91768. for (var i = 0; i < res.length; i++) {
  91769. indices.push(res[i]);
  91770. }
  91771. if (depth > 0) {
  91772. var positionscount = (positions.length / 3); //get the current pointcount
  91773. this._points.elements.forEach(function (p) {
  91774. normals.push(0, -1.0, 0);
  91775. positions.push(p.x, -depth, p.y);
  91776. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  91777. });
  91778. var totalCount = indices.length;
  91779. for (var i = 0; i < totalCount; i += 3) {
  91780. var i0 = indices[i + 0];
  91781. var i1 = indices[i + 1];
  91782. var i2 = indices[i + 2];
  91783. indices.push(i2 + positionscount);
  91784. indices.push(i1 + positionscount);
  91785. indices.push(i0 + positionscount);
  91786. }
  91787. //Add the sides
  91788. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  91789. this._holes.forEach(function (hole) {
  91790. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  91791. });
  91792. }
  91793. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  91794. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  91795. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  91796. result.setIndices(indices);
  91797. return result;
  91798. };
  91799. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  91800. var StartIndex = positions.length / 3;
  91801. var ulength = 0;
  91802. for (var i = 0; i < points.elements.length; i++) {
  91803. var p = points.elements[i];
  91804. var p1;
  91805. if ((i + 1) > points.elements.length - 1) {
  91806. p1 = points.elements[0];
  91807. }
  91808. else {
  91809. p1 = points.elements[i + 1];
  91810. }
  91811. positions.push(p.x, 0, p.y);
  91812. positions.push(p.x, -depth, p.y);
  91813. positions.push(p1.x, 0, p1.y);
  91814. positions.push(p1.x, -depth, p1.y);
  91815. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  91816. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  91817. var v3 = v2.subtract(v1);
  91818. var v4 = new BABYLON.Vector3(0, 1, 0);
  91819. var vn = BABYLON.Vector3.Cross(v3, v4);
  91820. vn = vn.normalize();
  91821. uvs.push(ulength / bounds.width, 0);
  91822. uvs.push(ulength / bounds.width, 1);
  91823. ulength += v3.length();
  91824. uvs.push((ulength / bounds.width), 0);
  91825. uvs.push((ulength / bounds.width), 1);
  91826. if (!flip) {
  91827. normals.push(-vn.x, -vn.y, -vn.z);
  91828. normals.push(-vn.x, -vn.y, -vn.z);
  91829. normals.push(-vn.x, -vn.y, -vn.z);
  91830. normals.push(-vn.x, -vn.y, -vn.z);
  91831. indices.push(StartIndex);
  91832. indices.push(StartIndex + 1);
  91833. indices.push(StartIndex + 2);
  91834. indices.push(StartIndex + 1);
  91835. indices.push(StartIndex + 3);
  91836. indices.push(StartIndex + 2);
  91837. }
  91838. else {
  91839. normals.push(vn.x, vn.y, vn.z);
  91840. normals.push(vn.x, vn.y, vn.z);
  91841. normals.push(vn.x, vn.y, vn.z);
  91842. normals.push(vn.x, vn.y, vn.z);
  91843. indices.push(StartIndex);
  91844. indices.push(StartIndex + 2);
  91845. indices.push(StartIndex + 1);
  91846. indices.push(StartIndex + 1);
  91847. indices.push(StartIndex + 2);
  91848. indices.push(StartIndex + 3);
  91849. }
  91850. StartIndex += 4;
  91851. }
  91852. ;
  91853. };
  91854. return PolygonMeshBuilder;
  91855. }());
  91856. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  91857. })(BABYLON || (BABYLON = {}));
  91858. //# sourceMappingURL=babylon.polygonMesh.js.map
  91859. var BABYLON;
  91860. (function (BABYLON) {
  91861. /**
  91862. * Unique ID when we import meshes from Babylon to CSG
  91863. */
  91864. var currentCSGMeshId = 0;
  91865. /**
  91866. * Represents a vertex of a polygon. Use your own vertex class instead of this
  91867. * one to provide additional features like texture coordinates and vertex
  91868. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  91869. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  91870. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  91871. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  91872. * is not used anywhere else.
  91873. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  91874. */
  91875. var Vertex = /** @class */ (function () {
  91876. /**
  91877. * Initializes the vertex
  91878. * @param pos The position of the vertex
  91879. * @param normal The normal of the vertex
  91880. * @param uv The texture coordinate of the vertex
  91881. */
  91882. function Vertex(
  91883. /**
  91884. * The position of the vertex
  91885. */
  91886. pos,
  91887. /**
  91888. * The normal of the vertex
  91889. */
  91890. normal,
  91891. /**
  91892. * The texture coordinate of the vertex
  91893. */
  91894. uv) {
  91895. this.pos = pos;
  91896. this.normal = normal;
  91897. this.uv = uv;
  91898. }
  91899. /**
  91900. * Make a clone, or deep copy, of the vertex
  91901. * @returns A new Vertex
  91902. */
  91903. Vertex.prototype.clone = function () {
  91904. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  91905. };
  91906. /**
  91907. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  91908. * orientation of a polygon is flipped.
  91909. */
  91910. Vertex.prototype.flip = function () {
  91911. this.normal = this.normal.scale(-1);
  91912. };
  91913. /**
  91914. * Create a new vertex between this vertex and `other` by linearly
  91915. * interpolating all properties using a parameter of `t`. Subclasses should
  91916. * override this to interpolate additional properties.
  91917. * @param other the vertex to interpolate against
  91918. * @param t The factor used to linearly interpolate between the vertices
  91919. */
  91920. Vertex.prototype.interpolate = function (other, t) {
  91921. 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));
  91922. };
  91923. return Vertex;
  91924. }());
  91925. /**
  91926. * Represents a plane in 3D space.
  91927. */
  91928. var Plane = /** @class */ (function () {
  91929. /**
  91930. * Initializes the plane
  91931. * @param normal The normal for the plane
  91932. * @param w
  91933. */
  91934. function Plane(normal, w) {
  91935. this.normal = normal;
  91936. this.w = w;
  91937. }
  91938. /**
  91939. * Construct a plane from three points
  91940. * @param a Point a
  91941. * @param b Point b
  91942. * @param c Point c
  91943. */
  91944. Plane.FromPoints = function (a, b, c) {
  91945. var v0 = c.subtract(a);
  91946. var v1 = b.subtract(a);
  91947. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  91948. return null;
  91949. }
  91950. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  91951. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  91952. };
  91953. /**
  91954. * Clone, or make a deep copy of the plane
  91955. * @returns a new Plane
  91956. */
  91957. Plane.prototype.clone = function () {
  91958. return new Plane(this.normal.clone(), this.w);
  91959. };
  91960. /**
  91961. * Flip the face of the plane
  91962. */
  91963. Plane.prototype.flip = function () {
  91964. this.normal.scaleInPlace(-1);
  91965. this.w = -this.w;
  91966. };
  91967. /**
  91968. * Split `polygon` by this plane if needed, then put the polygon or polygon
  91969. * fragments in the appropriate lists. Coplanar polygons go into either
  91970. `* coplanarFront` or `coplanarBack` depending on their orientation with
  91971. * respect to this plane. Polygons in front or in back of this plane go into
  91972. * either `front` or `back`
  91973. * @param polygon The polygon to be split
  91974. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  91975. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  91976. * @param front Will contain the polygons in front of the plane
  91977. * @param back Will contain the polygons begind the plane
  91978. */
  91979. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  91980. var COPLANAR = 0;
  91981. var FRONT = 1;
  91982. var BACK = 2;
  91983. var SPANNING = 3;
  91984. // Classify each point as well as the entire polygon into one of the above
  91985. // four classes.
  91986. var polygonType = 0;
  91987. var types = [];
  91988. var i;
  91989. var t;
  91990. for (i = 0; i < polygon.vertices.length; i++) {
  91991. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  91992. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  91993. polygonType |= type;
  91994. types.push(type);
  91995. }
  91996. // Put the polygon in the correct list, splitting it when necessary
  91997. switch (polygonType) {
  91998. case COPLANAR:
  91999. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  92000. break;
  92001. case FRONT:
  92002. front.push(polygon);
  92003. break;
  92004. case BACK:
  92005. back.push(polygon);
  92006. break;
  92007. case SPANNING:
  92008. var f = [], b = [];
  92009. for (i = 0; i < polygon.vertices.length; i++) {
  92010. var j = (i + 1) % polygon.vertices.length;
  92011. var ti = types[i], tj = types[j];
  92012. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  92013. if (ti !== BACK)
  92014. f.push(vi);
  92015. if (ti !== FRONT)
  92016. b.push(ti !== BACK ? vi.clone() : vi);
  92017. if ((ti | tj) === SPANNING) {
  92018. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  92019. var v = vi.interpolate(vj, t);
  92020. f.push(v);
  92021. b.push(v.clone());
  92022. }
  92023. }
  92024. var poly;
  92025. if (f.length >= 3) {
  92026. poly = new Polygon(f, polygon.shared);
  92027. if (poly.plane)
  92028. front.push(poly);
  92029. }
  92030. if (b.length >= 3) {
  92031. poly = new Polygon(b, polygon.shared);
  92032. if (poly.plane)
  92033. back.push(poly);
  92034. }
  92035. break;
  92036. }
  92037. };
  92038. /**
  92039. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  92040. * point is on the plane
  92041. */
  92042. Plane.EPSILON = 1e-5;
  92043. return Plane;
  92044. }());
  92045. /**
  92046. * Represents a convex polygon. The vertices used to initialize a polygon must
  92047. * be coplanar and form a convex loop.
  92048. *
  92049. * Each convex polygon has a `shared` property, which is shared between all
  92050. * polygons that are clones of each other or were split from the same polygon.
  92051. * This can be used to define per-polygon properties (such as surface color)
  92052. */
  92053. var Polygon = /** @class */ (function () {
  92054. /**
  92055. * Initializes the polygon
  92056. * @param vertices The vertices of the polygon
  92057. * @param shared The properties shared across all polygons
  92058. */
  92059. function Polygon(vertices, shared) {
  92060. this.vertices = vertices;
  92061. this.shared = shared;
  92062. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  92063. }
  92064. /**
  92065. * Clones, or makes a deep copy, or the polygon
  92066. */
  92067. Polygon.prototype.clone = function () {
  92068. var vertices = this.vertices.map(function (v) { return v.clone(); });
  92069. return new Polygon(vertices, this.shared);
  92070. };
  92071. /**
  92072. * Flips the faces of the polygon
  92073. */
  92074. Polygon.prototype.flip = function () {
  92075. this.vertices.reverse().map(function (v) { v.flip(); });
  92076. this.plane.flip();
  92077. };
  92078. return Polygon;
  92079. }());
  92080. /**
  92081. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  92082. * by picking a polygon to split along. That polygon (and all other coplanar
  92083. * polygons) are added directly to that node and the other polygons are added to
  92084. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  92085. * no distinction between internal and leaf nodes
  92086. */
  92087. var Node = /** @class */ (function () {
  92088. /**
  92089. * Initializes the node
  92090. * @param polygons A collection of polygons held in the node
  92091. */
  92092. function Node(polygons) {
  92093. this.plane = null;
  92094. this.front = null;
  92095. this.back = null;
  92096. this.polygons = new Array();
  92097. if (polygons) {
  92098. this.build(polygons);
  92099. }
  92100. }
  92101. /**
  92102. * Clones, or makes a deep copy, of the node
  92103. * @returns The cloned node
  92104. */
  92105. Node.prototype.clone = function () {
  92106. var node = new Node();
  92107. node.plane = this.plane && this.plane.clone();
  92108. node.front = this.front && this.front.clone();
  92109. node.back = this.back && this.back.clone();
  92110. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  92111. return node;
  92112. };
  92113. /**
  92114. * Convert solid space to empty space and empty space to solid space
  92115. */
  92116. Node.prototype.invert = function () {
  92117. for (var i = 0; i < this.polygons.length; i++) {
  92118. this.polygons[i].flip();
  92119. }
  92120. if (this.plane) {
  92121. this.plane.flip();
  92122. }
  92123. if (this.front) {
  92124. this.front.invert();
  92125. }
  92126. if (this.back) {
  92127. this.back.invert();
  92128. }
  92129. var temp = this.front;
  92130. this.front = this.back;
  92131. this.back = temp;
  92132. };
  92133. /**
  92134. * Recursively remove all polygons in `polygons` that are inside this BSP
  92135. * tree.
  92136. * @param polygons Polygons to remove from the BSP
  92137. * @returns Polygons clipped from the BSP
  92138. */
  92139. Node.prototype.clipPolygons = function (polygons) {
  92140. if (!this.plane)
  92141. return polygons.slice();
  92142. var front = new Array(), back = new Array();
  92143. for (var i = 0; i < polygons.length; i++) {
  92144. this.plane.splitPolygon(polygons[i], front, back, front, back);
  92145. }
  92146. if (this.front) {
  92147. front = this.front.clipPolygons(front);
  92148. }
  92149. if (this.back) {
  92150. back = this.back.clipPolygons(back);
  92151. }
  92152. else {
  92153. back = [];
  92154. }
  92155. return front.concat(back);
  92156. };
  92157. /**
  92158. * Remove all polygons in this BSP tree that are inside the other BSP tree
  92159. * `bsp`.
  92160. * @param bsp BSP containing polygons to remove from this BSP
  92161. */
  92162. Node.prototype.clipTo = function (bsp) {
  92163. this.polygons = bsp.clipPolygons(this.polygons);
  92164. if (this.front)
  92165. this.front.clipTo(bsp);
  92166. if (this.back)
  92167. this.back.clipTo(bsp);
  92168. };
  92169. /**
  92170. * Return a list of all polygons in this BSP tree
  92171. * @returns List of all polygons in this BSP tree
  92172. */
  92173. Node.prototype.allPolygons = function () {
  92174. var polygons = this.polygons.slice();
  92175. if (this.front)
  92176. polygons = polygons.concat(this.front.allPolygons());
  92177. if (this.back)
  92178. polygons = polygons.concat(this.back.allPolygons());
  92179. return polygons;
  92180. };
  92181. /**
  92182. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  92183. * new polygons are filtered down to the bottom of the tree and become new
  92184. * nodes there. Each set of polygons is partitioned using the first polygon
  92185. * (no heuristic is used to pick a good split)
  92186. * @param polygons Polygons used to construct the BSP tree
  92187. */
  92188. Node.prototype.build = function (polygons) {
  92189. if (!polygons.length)
  92190. return;
  92191. if (!this.plane)
  92192. this.plane = polygons[0].plane.clone();
  92193. var front = new Array(), back = new Array();
  92194. for (var i = 0; i < polygons.length; i++) {
  92195. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  92196. }
  92197. if (front.length) {
  92198. if (!this.front)
  92199. this.front = new Node();
  92200. this.front.build(front);
  92201. }
  92202. if (back.length) {
  92203. if (!this.back)
  92204. this.back = new Node();
  92205. this.back.build(back);
  92206. }
  92207. };
  92208. return Node;
  92209. }());
  92210. /**
  92211. * Class for building Constructive Solid Geometry
  92212. */
  92213. var CSG = /** @class */ (function () {
  92214. function CSG() {
  92215. this.polygons = new Array();
  92216. }
  92217. /**
  92218. * Convert the BABYLON.Mesh to BABYLON.CSG
  92219. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  92220. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  92221. */
  92222. CSG.FromMesh = function (mesh) {
  92223. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  92224. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  92225. if (mesh instanceof BABYLON.Mesh) {
  92226. mesh.computeWorldMatrix(true);
  92227. matrix = mesh.getWorldMatrix();
  92228. meshPosition = mesh.position.clone();
  92229. meshRotation = mesh.rotation.clone();
  92230. if (mesh.rotationQuaternion) {
  92231. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  92232. }
  92233. meshScaling = mesh.scaling.clone();
  92234. }
  92235. else {
  92236. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  92237. }
  92238. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  92239. var subMeshes = mesh.subMeshes;
  92240. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  92241. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  92242. vertices = [];
  92243. for (var j = 0; j < 3; j++) {
  92244. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  92245. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  92246. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  92247. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  92248. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  92249. vertex = new Vertex(position, normal, uv);
  92250. vertices.push(vertex);
  92251. }
  92252. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  92253. // To handle the case of degenerated triangle
  92254. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  92255. if (polygon.plane)
  92256. polygons.push(polygon);
  92257. }
  92258. }
  92259. var csg = CSG.FromPolygons(polygons);
  92260. csg.matrix = matrix;
  92261. csg.position = meshPosition;
  92262. csg.rotation = meshRotation;
  92263. csg.scaling = meshScaling;
  92264. csg.rotationQuaternion = meshRotationQuaternion;
  92265. currentCSGMeshId++;
  92266. return csg;
  92267. };
  92268. /**
  92269. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  92270. * @param polygons Polygons used to construct a BABYLON.CSG solid
  92271. */
  92272. CSG.FromPolygons = function (polygons) {
  92273. var csg = new CSG();
  92274. csg.polygons = polygons;
  92275. return csg;
  92276. };
  92277. /**
  92278. * Clones, or makes a deep copy, of the BABYLON.CSG
  92279. * @returns A new BABYLON.CSG
  92280. */
  92281. CSG.prototype.clone = function () {
  92282. var csg = new CSG();
  92283. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  92284. csg.copyTransformAttributes(this);
  92285. return csg;
  92286. };
  92287. /**
  92288. * Unions this CSG with another CSG
  92289. * @param csg The CSG to union against this CSG
  92290. * @returns The unioned CSG
  92291. */
  92292. CSG.prototype.union = function (csg) {
  92293. var a = new Node(this.clone().polygons);
  92294. var b = new Node(csg.clone().polygons);
  92295. a.clipTo(b);
  92296. b.clipTo(a);
  92297. b.invert();
  92298. b.clipTo(a);
  92299. b.invert();
  92300. a.build(b.allPolygons());
  92301. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  92302. };
  92303. /**
  92304. * Unions this CSG with another CSG in place
  92305. * @param csg The CSG to union against this CSG
  92306. */
  92307. CSG.prototype.unionInPlace = function (csg) {
  92308. var a = new Node(this.polygons);
  92309. var b = new Node(csg.polygons);
  92310. a.clipTo(b);
  92311. b.clipTo(a);
  92312. b.invert();
  92313. b.clipTo(a);
  92314. b.invert();
  92315. a.build(b.allPolygons());
  92316. this.polygons = a.allPolygons();
  92317. };
  92318. /**
  92319. * Subtracts this CSG with another CSG
  92320. * @param csg The CSG to subtract against this CSG
  92321. * @returns A new BABYLON.CSG
  92322. */
  92323. CSG.prototype.subtract = function (csg) {
  92324. var a = new Node(this.clone().polygons);
  92325. var b = new Node(csg.clone().polygons);
  92326. a.invert();
  92327. a.clipTo(b);
  92328. b.clipTo(a);
  92329. b.invert();
  92330. b.clipTo(a);
  92331. b.invert();
  92332. a.build(b.allPolygons());
  92333. a.invert();
  92334. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  92335. };
  92336. /**
  92337. * Subtracts this CSG with another CSG in place
  92338. * @param csg The CSG to subtact against this CSG
  92339. */
  92340. CSG.prototype.subtractInPlace = function (csg) {
  92341. var a = new Node(this.polygons);
  92342. var b = new Node(csg.polygons);
  92343. a.invert();
  92344. a.clipTo(b);
  92345. b.clipTo(a);
  92346. b.invert();
  92347. b.clipTo(a);
  92348. b.invert();
  92349. a.build(b.allPolygons());
  92350. a.invert();
  92351. this.polygons = a.allPolygons();
  92352. };
  92353. /**
  92354. * Intersect this CSG with another CSG
  92355. * @param csg The CSG to intersect against this CSG
  92356. * @returns A new BABYLON.CSG
  92357. */
  92358. CSG.prototype.intersect = function (csg) {
  92359. var a = new Node(this.clone().polygons);
  92360. var b = new Node(csg.clone().polygons);
  92361. a.invert();
  92362. b.clipTo(a);
  92363. b.invert();
  92364. a.clipTo(b);
  92365. b.clipTo(a);
  92366. a.build(b.allPolygons());
  92367. a.invert();
  92368. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  92369. };
  92370. /**
  92371. * Intersects this CSG with another CSG in place
  92372. * @param csg The CSG to intersect against this CSG
  92373. */
  92374. CSG.prototype.intersectInPlace = function (csg) {
  92375. var a = new Node(this.polygons);
  92376. var b = new Node(csg.polygons);
  92377. a.invert();
  92378. b.clipTo(a);
  92379. b.invert();
  92380. a.clipTo(b);
  92381. b.clipTo(a);
  92382. a.build(b.allPolygons());
  92383. a.invert();
  92384. this.polygons = a.allPolygons();
  92385. };
  92386. /**
  92387. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  92388. * not modified.
  92389. * @returns A new BABYLON.CSG solid with solid and empty space switched
  92390. */
  92391. CSG.prototype.inverse = function () {
  92392. var csg = this.clone();
  92393. csg.inverseInPlace();
  92394. return csg;
  92395. };
  92396. /**
  92397. * Inverses the BABYLON.CSG in place
  92398. */
  92399. CSG.prototype.inverseInPlace = function () {
  92400. this.polygons.map(function (p) { p.flip(); });
  92401. };
  92402. /**
  92403. * This is used to keep meshes transformations so they can be restored
  92404. * when we build back a Babylon Mesh
  92405. * NB : All CSG operations are performed in world coordinates
  92406. * @param csg The BABYLON.CSG to copy the transform attributes from
  92407. * @returns This BABYLON.CSG
  92408. */
  92409. CSG.prototype.copyTransformAttributes = function (csg) {
  92410. this.matrix = csg.matrix;
  92411. this.position = csg.position;
  92412. this.rotation = csg.rotation;
  92413. this.scaling = csg.scaling;
  92414. this.rotationQuaternion = csg.rotationQuaternion;
  92415. return this;
  92416. };
  92417. /**
  92418. * Build Raw mesh from CSG
  92419. * Coordinates here are in world space
  92420. * @param name The name of the mesh geometry
  92421. * @param scene The BABYLON.Scene
  92422. * @param keepSubMeshes Specifies if the submeshes should be kept
  92423. * @returns A new BABYLON.Mesh
  92424. */
  92425. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  92426. var matrix = this.matrix.clone();
  92427. matrix.invert();
  92428. 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;
  92429. if (keepSubMeshes) {
  92430. // Sort Polygons, since subMeshes are indices range
  92431. polygons.sort(function (a, b) {
  92432. if (a.shared.meshId === b.shared.meshId) {
  92433. return a.shared.subMeshId - b.shared.subMeshId;
  92434. }
  92435. else {
  92436. return a.shared.meshId - b.shared.meshId;
  92437. }
  92438. });
  92439. }
  92440. for (var i = 0, il = polygons.length; i < il; i++) {
  92441. polygon = polygons[i];
  92442. // Building SubMeshes
  92443. if (!subMesh_dict[polygon.shared.meshId]) {
  92444. subMesh_dict[polygon.shared.meshId] = {};
  92445. }
  92446. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  92447. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  92448. indexStart: +Infinity,
  92449. indexEnd: -Infinity,
  92450. materialIndex: polygon.shared.materialIndex
  92451. };
  92452. }
  92453. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  92454. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  92455. polygonIndices[0] = 0;
  92456. polygonIndices[1] = j - 1;
  92457. polygonIndices[2] = j;
  92458. for (var k = 0; k < 3; k++) {
  92459. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  92460. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  92461. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  92462. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  92463. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  92464. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  92465. // Check if 2 points can be merged
  92466. if (!(typeof vertex_idx !== 'undefined' &&
  92467. normals[vertex_idx * 3] === localNormal.x &&
  92468. normals[vertex_idx * 3 + 1] === localNormal.y &&
  92469. normals[vertex_idx * 3 + 2] === localNormal.z &&
  92470. uvs[vertex_idx * 2] === uv.x &&
  92471. uvs[vertex_idx * 2 + 1] === uv.y)) {
  92472. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  92473. uvs.push(uv.x, uv.y);
  92474. normals.push(normal.x, normal.y, normal.z);
  92475. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  92476. }
  92477. indices.push(vertex_idx);
  92478. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  92479. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  92480. currentIndex++;
  92481. }
  92482. }
  92483. }
  92484. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  92485. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  92486. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  92487. mesh.setIndices(indices, null);
  92488. if (keepSubMeshes) {
  92489. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  92490. var materialIndexOffset = 0, materialMaxIndex;
  92491. mesh.subMeshes = new Array();
  92492. for (var m in subMesh_dict) {
  92493. materialMaxIndex = -1;
  92494. for (var sm in subMesh_dict[m]) {
  92495. subMesh_obj = subMesh_dict[m][sm];
  92496. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  92497. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  92498. }
  92499. materialIndexOffset += ++materialMaxIndex;
  92500. }
  92501. }
  92502. return mesh;
  92503. };
  92504. /**
  92505. * Build Mesh from CSG taking material and transforms into account
  92506. * @param name The name of the BABYLON.Mesh
  92507. * @param material The material of the BABYLON.Mesh
  92508. * @param scene The BABYLON.Scene
  92509. * @param keepSubMeshes Specifies if submeshes should be kept
  92510. * @returns The new BABYLON.Mesh
  92511. */
  92512. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  92513. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  92514. mesh.material = material;
  92515. mesh.position.copyFrom(this.position);
  92516. mesh.rotation.copyFrom(this.rotation);
  92517. if (this.rotationQuaternion) {
  92518. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  92519. }
  92520. mesh.scaling.copyFrom(this.scaling);
  92521. mesh.computeWorldMatrix(true);
  92522. return mesh;
  92523. };
  92524. return CSG;
  92525. }());
  92526. BABYLON.CSG = CSG;
  92527. })(BABYLON || (BABYLON = {}));
  92528. //# sourceMappingURL=babylon.csg.js.map
  92529. var BABYLON;
  92530. (function (BABYLON) {
  92531. /**
  92532. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  92533. * It controls one of the indiviual texture used in the effect.
  92534. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92535. */
  92536. var LensFlare = /** @class */ (function () {
  92537. /**
  92538. * Instantiates a new Lens Flare.
  92539. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  92540. * It controls one of the indiviual texture used in the effect.
  92541. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92542. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  92543. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  92544. * @param color Define the lens color
  92545. * @param imgUrl Define the lens texture url
  92546. * @param system Define the `lensFlareSystem` this flare is part of
  92547. */
  92548. function LensFlare(
  92549. /**
  92550. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  92551. */
  92552. size,
  92553. /**
  92554. * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  92555. */
  92556. position, color, imgUrl, system) {
  92557. this.size = size;
  92558. this.position = position;
  92559. /**
  92560. * Define the alpha mode to render this particular lens.
  92561. */
  92562. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  92563. this.color = color || new BABYLON.Color3(1, 1, 1);
  92564. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  92565. this._system = system;
  92566. system.lensFlares.push(this);
  92567. }
  92568. /**
  92569. * Creates a new Lens Flare.
  92570. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  92571. * It controls one of the indiviual texture used in the effect.
  92572. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92573. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  92574. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  92575. * @param color Define the lens color
  92576. * @param imgUrl Define the lens texture url
  92577. * @param system Define the `lensFlareSystem` this flare is part of
  92578. * @returns The newly created Lens Flare
  92579. */
  92580. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  92581. return new LensFlare(size, position, color, imgUrl, system);
  92582. };
  92583. /**
  92584. * Dispose and release the lens flare with its associated resources.
  92585. */
  92586. LensFlare.prototype.dispose = function () {
  92587. if (this.texture) {
  92588. this.texture.dispose();
  92589. }
  92590. // Remove from scene
  92591. var index = this._system.lensFlares.indexOf(this);
  92592. this._system.lensFlares.splice(index, 1);
  92593. };
  92594. ;
  92595. return LensFlare;
  92596. }());
  92597. BABYLON.LensFlare = LensFlare;
  92598. })(BABYLON || (BABYLON = {}));
  92599. //# sourceMappingURL=babylon.lensFlare.js.map
  92600. var BABYLON;
  92601. (function (BABYLON) {
  92602. // Adds the parser to the scene parsers.
  92603. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  92604. // Lens flares
  92605. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  92606. if (!container.lensFlareSystems) {
  92607. container.lensFlareSystems = new Array();
  92608. }
  92609. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  92610. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  92611. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  92612. container.lensFlareSystems.push(lf);
  92613. }
  92614. }
  92615. });
  92616. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  92617. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  92618. if (this.lensFlareSystems[index].name === name) {
  92619. return this.lensFlareSystems[index];
  92620. }
  92621. }
  92622. return null;
  92623. };
  92624. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  92625. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  92626. if (this.lensFlareSystems[index].id === id) {
  92627. return this.lensFlareSystems[index];
  92628. }
  92629. }
  92630. return null;
  92631. };
  92632. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  92633. var index = this.lensFlareSystems.indexOf(toRemove);
  92634. if (index !== -1) {
  92635. this.lensFlareSystems.splice(index, 1);
  92636. }
  92637. return index;
  92638. };
  92639. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  92640. this.lensFlareSystems.push(newLensFlareSystem);
  92641. };
  92642. /**
  92643. * Defines the lens flare scene component responsible to manage any lens flares
  92644. * in a given scene.
  92645. */
  92646. var LensFlareSystemSceneComponent = /** @class */ (function () {
  92647. /**
  92648. * Creates a new instance of the component for the given scene
  92649. * @param scene Defines the scene to register the component in
  92650. */
  92651. function LensFlareSystemSceneComponent(scene) {
  92652. /**
  92653. * The component name helpfull to identify the component in the list of scene components.
  92654. */
  92655. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  92656. this.scene = scene;
  92657. scene.lensFlareSystems = new Array();
  92658. }
  92659. /**
  92660. * Registers the component in a given scene
  92661. */
  92662. LensFlareSystemSceneComponent.prototype.register = function () {
  92663. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  92664. };
  92665. /**
  92666. * Rebuilds the elements related to this component in case of
  92667. * context lost for instance.
  92668. */
  92669. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  92670. // Nothing to do for lens flare
  92671. };
  92672. /**
  92673. * Adds all the element from the container to the scene
  92674. * @param container the container holding the elements
  92675. */
  92676. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  92677. var _this = this;
  92678. if (!container.lensFlareSystems) {
  92679. return;
  92680. }
  92681. container.lensFlareSystems.forEach(function (o) {
  92682. _this.scene.addLensFlareSystem(o);
  92683. });
  92684. };
  92685. /**
  92686. * Removes all the elements in the container from the scene
  92687. * @param container contains the elements to remove
  92688. */
  92689. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  92690. var _this = this;
  92691. if (!container.lensFlareSystems) {
  92692. return;
  92693. }
  92694. container.lensFlareSystems.forEach(function (o) {
  92695. _this.scene.removeLensFlareSystem(o);
  92696. });
  92697. };
  92698. /**
  92699. * Serializes the component data to the specified json object
  92700. * @param serializationObject The object to serialize to
  92701. */
  92702. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  92703. // Lens flares
  92704. serializationObject.lensFlareSystems = [];
  92705. var lensFlareSystems = this.scene.lensFlareSystems;
  92706. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  92707. var lensFlareSystem = lensFlareSystems_1[_i];
  92708. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  92709. }
  92710. };
  92711. /**
  92712. * Disposes the component and the associated ressources.
  92713. */
  92714. LensFlareSystemSceneComponent.prototype.dispose = function () {
  92715. var lensFlareSystems = this.scene.lensFlareSystems;
  92716. while (lensFlareSystems.length) {
  92717. lensFlareSystems[0].dispose();
  92718. }
  92719. };
  92720. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  92721. // Lens flares
  92722. if (this.scene.lensFlaresEnabled) {
  92723. var lensFlareSystems = this.scene.lensFlareSystems;
  92724. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  92725. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  92726. var lensFlareSystem = lensFlareSystems_2[_i];
  92727. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  92728. lensFlareSystem.render();
  92729. }
  92730. }
  92731. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  92732. }
  92733. };
  92734. return LensFlareSystemSceneComponent;
  92735. }());
  92736. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  92737. })(BABYLON || (BABYLON = {}));
  92738. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  92739. var BABYLON;
  92740. (function (BABYLON) {
  92741. /**
  92742. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  92743. * It is usually composed of several `BABYLON.lensFlare`.
  92744. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92745. */
  92746. var LensFlareSystem = /** @class */ (function () {
  92747. /**
  92748. * Instantiates a lens flare system.
  92749. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  92750. * It is usually composed of several `BABYLON.lensFlare`.
  92751. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92752. * @param name Define the name of the lens flare system in the scene
  92753. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  92754. * @param scene Define the scene the lens flare system belongs to
  92755. */
  92756. function LensFlareSystem(
  92757. /**
  92758. * Define the name of the lens flare system
  92759. */
  92760. name, emitter, scene) {
  92761. this.name = name;
  92762. /**
  92763. * List of lens flares used in this system.
  92764. */
  92765. this.lensFlares = new Array();
  92766. /**
  92767. * Define a limit from the border the lens flare can be visible.
  92768. */
  92769. this.borderLimit = 300;
  92770. /**
  92771. * Define a viewport border we do not want to see the lens flare in.
  92772. */
  92773. this.viewportBorder = 0;
  92774. /**
  92775. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  92776. */
  92777. this.layerMask = 0x0FFFFFFF;
  92778. this._vertexBuffers = {};
  92779. this._isEnabled = true;
  92780. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92781. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  92782. if (!component) {
  92783. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  92784. scene._addComponent(component);
  92785. }
  92786. this._emitter = emitter;
  92787. this.id = name;
  92788. scene.lensFlareSystems.push(this);
  92789. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  92790. var engine = scene.getEngine();
  92791. // VBO
  92792. var vertices = [];
  92793. vertices.push(1, 1);
  92794. vertices.push(-1, 1);
  92795. vertices.push(-1, -1);
  92796. vertices.push(1, -1);
  92797. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92798. // Indices
  92799. var indices = [];
  92800. indices.push(0);
  92801. indices.push(1);
  92802. indices.push(2);
  92803. indices.push(0);
  92804. indices.push(2);
  92805. indices.push(3);
  92806. this._indexBuffer = engine.createIndexBuffer(indices);
  92807. // Effects
  92808. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  92809. }
  92810. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  92811. /**
  92812. * Define if the lens flare system is enabled.
  92813. */
  92814. get: function () {
  92815. return this._isEnabled;
  92816. },
  92817. set: function (value) {
  92818. this._isEnabled = value;
  92819. },
  92820. enumerable: true,
  92821. configurable: true
  92822. });
  92823. /**
  92824. * Get the scene the effects belongs to.
  92825. * @returns the scene holding the lens flare system
  92826. */
  92827. LensFlareSystem.prototype.getScene = function () {
  92828. return this._scene;
  92829. };
  92830. /**
  92831. * Get the emitter of the lens flare system.
  92832. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  92833. * @returns the emitter of the lens flare system
  92834. */
  92835. LensFlareSystem.prototype.getEmitter = function () {
  92836. return this._emitter;
  92837. };
  92838. /**
  92839. * Set the emitter of the lens flare system.
  92840. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  92841. * @param newEmitter Define the new emitter of the system
  92842. */
  92843. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  92844. this._emitter = newEmitter;
  92845. };
  92846. /**
  92847. * Get the lens flare system emitter position.
  92848. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  92849. * @returns the position
  92850. */
  92851. LensFlareSystem.prototype.getEmitterPosition = function () {
  92852. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  92853. };
  92854. /**
  92855. * @hidden
  92856. */
  92857. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  92858. var position = this.getEmitterPosition();
  92859. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  92860. this._positionX = position.x;
  92861. this._positionY = position.y;
  92862. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  92863. if (this.viewportBorder > 0) {
  92864. globalViewport.x -= this.viewportBorder;
  92865. globalViewport.y -= this.viewportBorder;
  92866. globalViewport.width += this.viewportBorder * 2;
  92867. globalViewport.height += this.viewportBorder * 2;
  92868. position.x += this.viewportBorder;
  92869. position.y += this.viewportBorder;
  92870. this._positionX += this.viewportBorder;
  92871. this._positionY += this.viewportBorder;
  92872. }
  92873. if (position.z > 0) {
  92874. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  92875. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  92876. return true;
  92877. }
  92878. return true;
  92879. }
  92880. return false;
  92881. };
  92882. /** @hidden */
  92883. LensFlareSystem.prototype._isVisible = function () {
  92884. if (!this._isEnabled || !this._scene.activeCamera) {
  92885. return false;
  92886. }
  92887. var emitterPosition = this.getEmitterPosition();
  92888. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  92889. var distance = direction.length();
  92890. direction.normalize();
  92891. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  92892. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  92893. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  92894. };
  92895. /**
  92896. * @hidden
  92897. */
  92898. LensFlareSystem.prototype.render = function () {
  92899. if (!this._effect.isReady() || !this._scene.activeCamera)
  92900. return false;
  92901. var engine = this._scene.getEngine();
  92902. var viewport = this._scene.activeCamera.viewport;
  92903. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  92904. // Position
  92905. if (!this.computeEffectivePosition(globalViewport)) {
  92906. return false;
  92907. }
  92908. // Visibility
  92909. if (!this._isVisible()) {
  92910. return false;
  92911. }
  92912. // Intensity
  92913. var awayX;
  92914. var awayY;
  92915. if (this._positionX < this.borderLimit + globalViewport.x) {
  92916. awayX = this.borderLimit + globalViewport.x - this._positionX;
  92917. }
  92918. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  92919. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  92920. }
  92921. else {
  92922. awayX = 0;
  92923. }
  92924. if (this._positionY < this.borderLimit + globalViewport.y) {
  92925. awayY = this.borderLimit + globalViewport.y - this._positionY;
  92926. }
  92927. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  92928. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  92929. }
  92930. else {
  92931. awayY = 0;
  92932. }
  92933. var away = (awayX > awayY) ? awayX : awayY;
  92934. away -= this.viewportBorder;
  92935. if (away > this.borderLimit) {
  92936. away = this.borderLimit;
  92937. }
  92938. var intensity = 1.0 - (away / this.borderLimit);
  92939. if (intensity < 0) {
  92940. return false;
  92941. }
  92942. if (intensity > 1.0) {
  92943. intensity = 1.0;
  92944. }
  92945. if (this.viewportBorder > 0) {
  92946. globalViewport.x += this.viewportBorder;
  92947. globalViewport.y += this.viewportBorder;
  92948. globalViewport.width -= this.viewportBorder * 2;
  92949. globalViewport.height -= this.viewportBorder * 2;
  92950. this._positionX -= this.viewportBorder;
  92951. this._positionY -= this.viewportBorder;
  92952. }
  92953. // Position
  92954. var centerX = globalViewport.x + globalViewport.width / 2;
  92955. var centerY = globalViewport.y + globalViewport.height / 2;
  92956. var distX = centerX - this._positionX;
  92957. var distY = centerY - this._positionY;
  92958. // Effects
  92959. engine.enableEffect(this._effect);
  92960. engine.setState(false);
  92961. engine.setDepthBuffer(false);
  92962. // VBOs
  92963. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  92964. // Flares
  92965. for (var index = 0; index < this.lensFlares.length; index++) {
  92966. var flare = this.lensFlares[index];
  92967. engine.setAlphaMode(flare.alphaMode);
  92968. var x = centerX - (distX * flare.position);
  92969. var y = centerY - (distY * flare.position);
  92970. var cw = flare.size;
  92971. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  92972. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  92973. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  92974. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  92975. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  92976. // Texture
  92977. this._effect.setTexture("textureSampler", flare.texture);
  92978. // Color
  92979. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  92980. // Draw order
  92981. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92982. }
  92983. engine.setDepthBuffer(true);
  92984. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  92985. return true;
  92986. };
  92987. /**
  92988. * Dispose and release the lens flare with its associated resources.
  92989. */
  92990. LensFlareSystem.prototype.dispose = function () {
  92991. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92992. if (vertexBuffer) {
  92993. vertexBuffer.dispose();
  92994. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92995. }
  92996. if (this._indexBuffer) {
  92997. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92998. this._indexBuffer = null;
  92999. }
  93000. while (this.lensFlares.length) {
  93001. this.lensFlares[0].dispose();
  93002. }
  93003. // Remove from scene
  93004. var index = this._scene.lensFlareSystems.indexOf(this);
  93005. this._scene.lensFlareSystems.splice(index, 1);
  93006. };
  93007. /**
  93008. * Parse a lens flare system from a JSON repressentation
  93009. * @param parsedLensFlareSystem Define the JSON to parse
  93010. * @param scene Define the scene the parsed system should be instantiated in
  93011. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  93012. * @returns the parsed system
  93013. */
  93014. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  93015. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  93016. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  93017. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  93018. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  93019. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  93020. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  93021. var parsedFlare = parsedLensFlareSystem.flares[index];
  93022. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  93023. }
  93024. return lensFlareSystem;
  93025. };
  93026. /**
  93027. * Serialize the current Lens Flare System into a JSON representation.
  93028. * @returns the serialized JSON
  93029. */
  93030. LensFlareSystem.prototype.serialize = function () {
  93031. var serializationObject = {};
  93032. serializationObject.id = this.id;
  93033. serializationObject.name = this.name;
  93034. serializationObject.emitterId = this.getEmitter().id;
  93035. serializationObject.borderLimit = this.borderLimit;
  93036. serializationObject.flares = [];
  93037. for (var index = 0; index < this.lensFlares.length; index++) {
  93038. var flare = this.lensFlares[index];
  93039. serializationObject.flares.push({
  93040. size: flare.size,
  93041. position: flare.position,
  93042. color: flare.color.asArray(),
  93043. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  93044. });
  93045. }
  93046. return serializationObject;
  93047. };
  93048. return LensFlareSystem;
  93049. }());
  93050. BABYLON.LensFlareSystem = LensFlareSystem;
  93051. })(BABYLON || (BABYLON = {}));
  93052. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  93053. var BABYLON;
  93054. (function (BABYLON) {
  93055. /**
  93056. * This is a holder class for the physics joint created by the physics plugin.
  93057. * It holds a set of functions to control the underlying joint.
  93058. */
  93059. var PhysicsJoint = /** @class */ (function () {
  93060. function PhysicsJoint(type, jointData) {
  93061. this.type = type;
  93062. this.jointData = jointData;
  93063. jointData.nativeParams = jointData.nativeParams || {};
  93064. }
  93065. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  93066. get: function () {
  93067. return this._physicsJoint;
  93068. },
  93069. set: function (newJoint) {
  93070. if (this._physicsJoint) {
  93071. //remove from the wolrd
  93072. }
  93073. this._physicsJoint = newJoint;
  93074. },
  93075. enumerable: true,
  93076. configurable: true
  93077. });
  93078. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  93079. set: function (physicsPlugin) {
  93080. this._physicsPlugin = physicsPlugin;
  93081. },
  93082. enumerable: true,
  93083. configurable: true
  93084. });
  93085. /**
  93086. * Execute a function that is physics-plugin specific.
  93087. * @param {Function} func the function that will be executed.
  93088. * It accepts two parameters: the physics world and the physics joint.
  93089. */
  93090. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  93091. func(this._physicsPlugin.world, this._physicsJoint);
  93092. };
  93093. //TODO check if the native joints are the same
  93094. //Joint Types
  93095. PhysicsJoint.DistanceJoint = 0;
  93096. PhysicsJoint.HingeJoint = 1;
  93097. PhysicsJoint.BallAndSocketJoint = 2;
  93098. PhysicsJoint.WheelJoint = 3;
  93099. PhysicsJoint.SliderJoint = 4;
  93100. //OIMO
  93101. PhysicsJoint.PrismaticJoint = 5;
  93102. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  93103. PhysicsJoint.UniversalJoint = 6;
  93104. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  93105. //Cannon
  93106. //Similar to a Ball-Joint. Different in params
  93107. PhysicsJoint.PointToPointJoint = 8;
  93108. //Cannon only at the moment
  93109. PhysicsJoint.SpringJoint = 9;
  93110. PhysicsJoint.LockJoint = 10;
  93111. return PhysicsJoint;
  93112. }());
  93113. BABYLON.PhysicsJoint = PhysicsJoint;
  93114. /**
  93115. * A class representing a physics distance joint.
  93116. */
  93117. var DistanceJoint = /** @class */ (function (_super) {
  93118. __extends(DistanceJoint, _super);
  93119. function DistanceJoint(jointData) {
  93120. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  93121. }
  93122. /**
  93123. * Update the predefined distance.
  93124. */
  93125. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  93126. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  93127. };
  93128. return DistanceJoint;
  93129. }(PhysicsJoint));
  93130. BABYLON.DistanceJoint = DistanceJoint;
  93131. var MotorEnabledJoint = /** @class */ (function (_super) {
  93132. __extends(MotorEnabledJoint, _super);
  93133. function MotorEnabledJoint(type, jointData) {
  93134. return _super.call(this, type, jointData) || this;
  93135. }
  93136. /**
  93137. * Set the motor values.
  93138. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93139. * @param {number} force the force to apply
  93140. * @param {number} maxForce max force for this motor.
  93141. */
  93142. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  93143. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  93144. };
  93145. /**
  93146. * Set the motor's limits.
  93147. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93148. */
  93149. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  93150. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  93151. };
  93152. return MotorEnabledJoint;
  93153. }(PhysicsJoint));
  93154. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  93155. /**
  93156. * This class represents a single hinge physics joint
  93157. */
  93158. var HingeJoint = /** @class */ (function (_super) {
  93159. __extends(HingeJoint, _super);
  93160. function HingeJoint(jointData) {
  93161. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  93162. }
  93163. /**
  93164. * Set the motor values.
  93165. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93166. * @param {number} force the force to apply
  93167. * @param {number} maxForce max force for this motor.
  93168. */
  93169. HingeJoint.prototype.setMotor = function (force, maxForce) {
  93170. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  93171. };
  93172. /**
  93173. * Set the motor's limits.
  93174. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93175. */
  93176. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  93177. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  93178. };
  93179. return HingeJoint;
  93180. }(MotorEnabledJoint));
  93181. BABYLON.HingeJoint = HingeJoint;
  93182. /**
  93183. * This class represents a dual hinge physics joint (same as wheel joint)
  93184. */
  93185. var Hinge2Joint = /** @class */ (function (_super) {
  93186. __extends(Hinge2Joint, _super);
  93187. function Hinge2Joint(jointData) {
  93188. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  93189. }
  93190. /**
  93191. * Set the motor values.
  93192. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93193. * @param {number} force the force to apply
  93194. * @param {number} maxForce max force for this motor.
  93195. * @param {motorIndex} the motor's index, 0 or 1.
  93196. */
  93197. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  93198. if (motorIndex === void 0) { motorIndex = 0; }
  93199. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  93200. };
  93201. /**
  93202. * Set the motor limits.
  93203. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93204. * @param {number} upperLimit the upper limit
  93205. * @param {number} lowerLimit lower limit
  93206. * @param {motorIndex} the motor's index, 0 or 1.
  93207. */
  93208. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  93209. if (motorIndex === void 0) { motorIndex = 0; }
  93210. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  93211. };
  93212. return Hinge2Joint;
  93213. }(MotorEnabledJoint));
  93214. BABYLON.Hinge2Joint = Hinge2Joint;
  93215. })(BABYLON || (BABYLON = {}));
  93216. //# sourceMappingURL=babylon.physicsJoint.js.map
  93217. var BABYLON;
  93218. (function (BABYLON) {
  93219. var PhysicsImpostor = /** @class */ (function () {
  93220. function PhysicsImpostor(object, type, _options, _scene) {
  93221. if (_options === void 0) { _options = { mass: 0 }; }
  93222. var _this = this;
  93223. this.object = object;
  93224. this.type = type;
  93225. this._options = _options;
  93226. this._scene = _scene;
  93227. this._bodyUpdateRequired = false;
  93228. this._onBeforePhysicsStepCallbacks = new Array();
  93229. this._onAfterPhysicsStepCallbacks = new Array();
  93230. this._onPhysicsCollideCallbacks = [];
  93231. this._deltaPosition = BABYLON.Vector3.Zero();
  93232. this._isDisposed = false;
  93233. //temp variables for parent rotation calculations
  93234. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  93235. this._tmpQuat = new BABYLON.Quaternion();
  93236. this._tmpQuat2 = new BABYLON.Quaternion();
  93237. /**
  93238. * this function is executed by the physics engine.
  93239. */
  93240. this.beforeStep = function () {
  93241. if (!_this._physicsEngine) {
  93242. return;
  93243. }
  93244. _this.object.translate(_this._deltaPosition, -1);
  93245. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  93246. _this.object.computeWorldMatrix(false);
  93247. if (_this.object.parent && _this.object.rotationQuaternion) {
  93248. _this.getParentsRotation();
  93249. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  93250. }
  93251. else {
  93252. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  93253. }
  93254. if (!_this._options.disableBidirectionalTransformation) {
  93255. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  93256. }
  93257. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  93258. func(_this);
  93259. });
  93260. };
  93261. /**
  93262. * this function is executed by the physics engine.
  93263. */
  93264. this.afterStep = function () {
  93265. if (!_this._physicsEngine) {
  93266. return;
  93267. }
  93268. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  93269. func(_this);
  93270. });
  93271. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  93272. // object has now its world rotation. needs to be converted to local.
  93273. if (_this.object.parent && _this.object.rotationQuaternion) {
  93274. _this.getParentsRotation();
  93275. _this._tmpQuat.conjugateInPlace();
  93276. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  93277. }
  93278. // take the position set and make it the absolute position of this object.
  93279. _this.object.setAbsolutePosition(_this.object.position);
  93280. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  93281. _this.object.translate(_this._deltaPosition, 1);
  93282. };
  93283. /**
  93284. * Legacy collision detection event support
  93285. */
  93286. this.onCollideEvent = null;
  93287. //event and body object due to cannon's event-based architecture.
  93288. this.onCollide = function (e) {
  93289. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  93290. return;
  93291. }
  93292. if (!_this._physicsEngine) {
  93293. return;
  93294. }
  93295. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  93296. if (otherImpostor) {
  93297. // Legacy collision detection event support
  93298. if (_this.onCollideEvent) {
  93299. _this.onCollideEvent(_this, otherImpostor);
  93300. }
  93301. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  93302. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  93303. }).forEach(function (obj) {
  93304. obj.callback(_this, otherImpostor);
  93305. });
  93306. }
  93307. };
  93308. //sanity check!
  93309. if (!this.object) {
  93310. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  93311. return;
  93312. }
  93313. //legacy support for old syntax.
  93314. if (!this._scene && object.getScene) {
  93315. this._scene = object.getScene();
  93316. }
  93317. if (!this._scene) {
  93318. return;
  93319. }
  93320. this._physicsEngine = this._scene.getPhysicsEngine();
  93321. if (!this._physicsEngine) {
  93322. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  93323. }
  93324. else {
  93325. //set the object's quaternion, if not set
  93326. if (!this.object.rotationQuaternion) {
  93327. if (this.object.rotation) {
  93328. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  93329. }
  93330. else {
  93331. this.object.rotationQuaternion = new BABYLON.Quaternion();
  93332. }
  93333. }
  93334. //default options params
  93335. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  93336. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  93337. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  93338. this._joints = [];
  93339. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  93340. if (!this.object.parent || this._options.ignoreParent) {
  93341. this._init();
  93342. }
  93343. else if (this.object.parent.physicsImpostor) {
  93344. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  93345. }
  93346. }
  93347. }
  93348. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  93349. get: function () {
  93350. return this._isDisposed;
  93351. },
  93352. enumerable: true,
  93353. configurable: true
  93354. });
  93355. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  93356. get: function () {
  93357. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  93358. },
  93359. set: function (value) {
  93360. this.setMass(value);
  93361. },
  93362. enumerable: true,
  93363. configurable: true
  93364. });
  93365. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  93366. get: function () {
  93367. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  93368. },
  93369. set: function (value) {
  93370. if (!this._physicsEngine) {
  93371. return;
  93372. }
  93373. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  93374. },
  93375. enumerable: true,
  93376. configurable: true
  93377. });
  93378. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  93379. get: function () {
  93380. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  93381. },
  93382. set: function (value) {
  93383. if (!this._physicsEngine) {
  93384. return;
  93385. }
  93386. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  93387. },
  93388. enumerable: true,
  93389. configurable: true
  93390. });
  93391. /**
  93392. * This function will completly initialize this impostor.
  93393. * It will create a new body - but only if this mesh has no parent.
  93394. * If it has, this impostor will not be used other than to define the impostor
  93395. * of the child mesh.
  93396. * @hidden
  93397. */
  93398. PhysicsImpostor.prototype._init = function () {
  93399. if (!this._physicsEngine) {
  93400. return;
  93401. }
  93402. this._physicsEngine.removeImpostor(this);
  93403. this.physicsBody = null;
  93404. this._parent = this._parent || this._getPhysicsParent();
  93405. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  93406. this._physicsEngine.addImpostor(this);
  93407. }
  93408. };
  93409. PhysicsImpostor.prototype._getPhysicsParent = function () {
  93410. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  93411. var parentMesh = this.object.parent;
  93412. return parentMesh.physicsImpostor;
  93413. }
  93414. return null;
  93415. };
  93416. /**
  93417. * Should a new body be generated.
  93418. */
  93419. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  93420. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  93421. };
  93422. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  93423. this.forceUpdate();
  93424. };
  93425. /**
  93426. * Force a regeneration of this or the parent's impostor's body.
  93427. * Use under cautious - This will remove all joints already implemented.
  93428. */
  93429. PhysicsImpostor.prototype.forceUpdate = function () {
  93430. this._init();
  93431. if (this.parent && !this._options.ignoreParent) {
  93432. this.parent.forceUpdate();
  93433. }
  93434. };
  93435. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  93436. /*public get mesh(): AbstractMesh {
  93437. return this._mesh;
  93438. }*/
  93439. /**
  93440. * Gets the body that holds this impostor. Either its own, or its parent.
  93441. */
  93442. get: function () {
  93443. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  93444. },
  93445. /**
  93446. * Set the physics body. Used mainly by the physics engine/plugin
  93447. */
  93448. set: function (physicsBody) {
  93449. if (this._physicsBody && this._physicsEngine) {
  93450. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  93451. }
  93452. this._physicsBody = physicsBody;
  93453. this.resetUpdateFlags();
  93454. },
  93455. enumerable: true,
  93456. configurable: true
  93457. });
  93458. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  93459. get: function () {
  93460. return !this._options.ignoreParent && this._parent ? this._parent : null;
  93461. },
  93462. set: function (value) {
  93463. this._parent = value;
  93464. },
  93465. enumerable: true,
  93466. configurable: true
  93467. });
  93468. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  93469. this._bodyUpdateRequired = false;
  93470. };
  93471. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  93472. if (this.object.getBoundingInfo) {
  93473. var q = this.object.rotationQuaternion;
  93474. //reset rotation
  93475. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  93476. //calculate the world matrix with no rotation
  93477. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  93478. var boundingInfo = this.object.getBoundingInfo();
  93479. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  93480. //bring back the rotation
  93481. this.object.rotationQuaternion = q;
  93482. //calculate the world matrix with the new rotation
  93483. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  93484. return size;
  93485. }
  93486. else {
  93487. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  93488. }
  93489. };
  93490. PhysicsImpostor.prototype.getObjectCenter = function () {
  93491. if (this.object.getBoundingInfo) {
  93492. var boundingInfo = this.object.getBoundingInfo();
  93493. return boundingInfo.boundingBox.centerWorld;
  93494. }
  93495. else {
  93496. return this.object.position;
  93497. }
  93498. };
  93499. /**
  93500. * Get a specific parametes from the options parameter.
  93501. */
  93502. PhysicsImpostor.prototype.getParam = function (paramName) {
  93503. return this._options[paramName];
  93504. };
  93505. /**
  93506. * Sets a specific parameter in the options given to the physics plugin
  93507. */
  93508. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  93509. this._options[paramName] = value;
  93510. this._bodyUpdateRequired = true;
  93511. };
  93512. /**
  93513. * Specifically change the body's mass option. Won't recreate the physics body object
  93514. */
  93515. PhysicsImpostor.prototype.setMass = function (mass) {
  93516. if (this.getParam("mass") !== mass) {
  93517. this.setParam("mass", mass);
  93518. }
  93519. if (this._physicsEngine) {
  93520. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  93521. }
  93522. };
  93523. PhysicsImpostor.prototype.getLinearVelocity = function () {
  93524. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  93525. };
  93526. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  93527. if (this._physicsEngine) {
  93528. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  93529. }
  93530. };
  93531. PhysicsImpostor.prototype.getAngularVelocity = function () {
  93532. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  93533. };
  93534. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  93535. if (this._physicsEngine) {
  93536. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  93537. }
  93538. };
  93539. /**
  93540. * Execute a function with the physics plugin native code.
  93541. * Provide a function the will have two variables - the world object and the physics body object.
  93542. */
  93543. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  93544. if (this._physicsEngine) {
  93545. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  93546. }
  93547. };
  93548. /**
  93549. * Register a function that will be executed before the physics world is stepping forward.
  93550. */
  93551. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  93552. this._onBeforePhysicsStepCallbacks.push(func);
  93553. };
  93554. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  93555. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  93556. if (index > -1) {
  93557. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  93558. }
  93559. else {
  93560. BABYLON.Tools.Warn("Function to remove was not found");
  93561. }
  93562. };
  93563. /**
  93564. * Register a function that will be executed after the physics step
  93565. */
  93566. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  93567. this._onAfterPhysicsStepCallbacks.push(func);
  93568. };
  93569. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  93570. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  93571. if (index > -1) {
  93572. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  93573. }
  93574. else {
  93575. BABYLON.Tools.Warn("Function to remove was not found");
  93576. }
  93577. };
  93578. /**
  93579. * register a function that will be executed when this impostor collides against a different body.
  93580. */
  93581. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  93582. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  93583. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  93584. };
  93585. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  93586. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  93587. var index = -1;
  93588. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  93589. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  93590. // chcek the arrays match
  93591. var sameList = cbDef.otherImpostors.every(function (impostor) {
  93592. return collidedAgainstList.indexOf(impostor) > -1;
  93593. });
  93594. if (sameList) {
  93595. index = idx;
  93596. }
  93597. return sameList;
  93598. }
  93599. return false;
  93600. });
  93601. if (found) {
  93602. this._onPhysicsCollideCallbacks.splice(index, 1);
  93603. }
  93604. else {
  93605. BABYLON.Tools.Warn("Function to remove was not found");
  93606. }
  93607. };
  93608. PhysicsImpostor.prototype.getParentsRotation = function () {
  93609. var parent = this.object.parent;
  93610. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  93611. while (parent) {
  93612. if (parent.rotationQuaternion) {
  93613. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  93614. }
  93615. else {
  93616. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  93617. }
  93618. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  93619. parent = parent.parent;
  93620. }
  93621. return this._tmpQuat;
  93622. };
  93623. /**
  93624. * Apply a force
  93625. */
  93626. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  93627. if (this._physicsEngine) {
  93628. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  93629. }
  93630. return this;
  93631. };
  93632. /**
  93633. * Apply an impulse
  93634. */
  93635. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  93636. if (this._physicsEngine) {
  93637. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  93638. }
  93639. return this;
  93640. };
  93641. /**
  93642. * A help function to create a joint.
  93643. */
  93644. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  93645. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  93646. this.addJoint(otherImpostor, joint);
  93647. return this;
  93648. };
  93649. /**
  93650. * Add a joint to this impostor with a different impostor.
  93651. */
  93652. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  93653. this._joints.push({
  93654. otherImpostor: otherImpostor,
  93655. joint: joint
  93656. });
  93657. if (this._physicsEngine) {
  93658. this._physicsEngine.addJoint(this, otherImpostor, joint);
  93659. }
  93660. return this;
  93661. };
  93662. /**
  93663. * Will keep this body still, in a sleep mode.
  93664. */
  93665. PhysicsImpostor.prototype.sleep = function () {
  93666. if (this._physicsEngine) {
  93667. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  93668. }
  93669. return this;
  93670. };
  93671. /**
  93672. * Wake the body up.
  93673. */
  93674. PhysicsImpostor.prototype.wakeUp = function () {
  93675. if (this._physicsEngine) {
  93676. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  93677. }
  93678. return this;
  93679. };
  93680. PhysicsImpostor.prototype.clone = function (newObject) {
  93681. if (!newObject)
  93682. return null;
  93683. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  93684. };
  93685. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  93686. var _this = this;
  93687. //no dispose if no physics engine is available.
  93688. if (!this._physicsEngine) {
  93689. return;
  93690. }
  93691. this._joints.forEach(function (j) {
  93692. if (_this._physicsEngine) {
  93693. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  93694. }
  93695. });
  93696. //dispose the physics body
  93697. this._physicsEngine.removeImpostor(this);
  93698. if (this.parent) {
  93699. this.parent.forceUpdate();
  93700. }
  93701. else {
  93702. /*this._object.getChildMeshes().forEach(function(mesh) {
  93703. if (mesh.physicsImpostor) {
  93704. if (disposeChildren) {
  93705. mesh.physicsImpostor.dispose();
  93706. mesh.physicsImpostor = null;
  93707. }
  93708. }
  93709. })*/
  93710. }
  93711. this._isDisposed = true;
  93712. };
  93713. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  93714. this._deltaPosition.copyFrom(position);
  93715. };
  93716. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  93717. if (!this._deltaRotation) {
  93718. this._deltaRotation = new BABYLON.Quaternion();
  93719. }
  93720. this._deltaRotation.copyFrom(rotation);
  93721. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  93722. };
  93723. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  93724. if (this._physicsEngine) {
  93725. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  93726. }
  93727. return this;
  93728. };
  93729. PhysicsImpostor.prototype.getRadius = function () {
  93730. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  93731. };
  93732. /**
  93733. * Sync a bone with this impostor
  93734. * @param bone The bone to sync to the impostor.
  93735. * @param boneMesh The mesh that the bone is influencing.
  93736. * @param jointPivot The pivot of the joint / bone in local space.
  93737. * @param distToJoint Optional distance from the impostor to the joint.
  93738. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  93739. */
  93740. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  93741. var tempVec = PhysicsImpostor._tmpVecs[0];
  93742. var mesh = this.object;
  93743. if (mesh.rotationQuaternion) {
  93744. if (adjustRotation) {
  93745. var tempQuat = PhysicsImpostor._tmpQuat;
  93746. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  93747. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  93748. }
  93749. else {
  93750. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  93751. }
  93752. }
  93753. tempVec.x = 0;
  93754. tempVec.y = 0;
  93755. tempVec.z = 0;
  93756. if (jointPivot) {
  93757. tempVec.x = jointPivot.x;
  93758. tempVec.y = jointPivot.y;
  93759. tempVec.z = jointPivot.z;
  93760. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  93761. if (distToJoint === undefined || distToJoint === null) {
  93762. distToJoint = jointPivot.length();
  93763. }
  93764. tempVec.x *= distToJoint;
  93765. tempVec.y *= distToJoint;
  93766. tempVec.z *= distToJoint;
  93767. }
  93768. if (bone.getParent()) {
  93769. tempVec.addInPlace(mesh.getAbsolutePosition());
  93770. bone.setAbsolutePosition(tempVec, boneMesh);
  93771. }
  93772. else {
  93773. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  93774. boneMesh.position.x -= tempVec.x;
  93775. boneMesh.position.y -= tempVec.y;
  93776. boneMesh.position.z -= tempVec.z;
  93777. }
  93778. };
  93779. /**
  93780. * Sync impostor to a bone
  93781. * @param bone The bone that the impostor will be synced to.
  93782. * @param boneMesh The mesh that the bone is influencing.
  93783. * @param jointPivot The pivot of the joint / bone in local space.
  93784. * @param distToJoint Optional distance from the impostor to the joint.
  93785. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  93786. * @param boneAxis Optional vector3 axis the bone is aligned with
  93787. */
  93788. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  93789. var mesh = this.object;
  93790. if (mesh.rotationQuaternion) {
  93791. if (adjustRotation) {
  93792. var tempQuat = PhysicsImpostor._tmpQuat;
  93793. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  93794. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  93795. }
  93796. else {
  93797. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  93798. }
  93799. }
  93800. var pos = PhysicsImpostor._tmpVecs[0];
  93801. var boneDir = PhysicsImpostor._tmpVecs[1];
  93802. if (!boneAxis) {
  93803. boneAxis = PhysicsImpostor._tmpVecs[2];
  93804. boneAxis.x = 0;
  93805. boneAxis.y = 1;
  93806. boneAxis.z = 0;
  93807. }
  93808. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  93809. bone.getAbsolutePositionToRef(boneMesh, pos);
  93810. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  93811. distToJoint = jointPivot.length();
  93812. }
  93813. if (distToJoint !== undefined && distToJoint !== null) {
  93814. pos.x += boneDir.x * distToJoint;
  93815. pos.y += boneDir.y * distToJoint;
  93816. pos.z += boneDir.z * distToJoint;
  93817. }
  93818. mesh.setAbsolutePosition(pos);
  93819. };
  93820. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  93821. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  93822. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  93823. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  93824. //Impostor types
  93825. PhysicsImpostor.NoImpostor = 0;
  93826. PhysicsImpostor.SphereImpostor = 1;
  93827. PhysicsImpostor.BoxImpostor = 2;
  93828. PhysicsImpostor.PlaneImpostor = 3;
  93829. PhysicsImpostor.MeshImpostor = 4;
  93830. PhysicsImpostor.CylinderImpostor = 7;
  93831. PhysicsImpostor.ParticleImpostor = 8;
  93832. PhysicsImpostor.HeightmapImpostor = 9;
  93833. return PhysicsImpostor;
  93834. }());
  93835. BABYLON.PhysicsImpostor = PhysicsImpostor;
  93836. })(BABYLON || (BABYLON = {}));
  93837. //# sourceMappingURL=babylon.physicsImpostor.js.map
  93838. var BABYLON;
  93839. (function (BABYLON) {
  93840. /**
  93841. * Class used to control physics engine
  93842. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  93843. */
  93844. var PhysicsEngine = /** @class */ (function () {
  93845. /**
  93846. * Creates a new Physics Engine
  93847. * @param gravity defines the gravity vector used by the simulation
  93848. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  93849. */
  93850. function PhysicsEngine(gravity, _physicsPlugin) {
  93851. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  93852. this._physicsPlugin = _physicsPlugin;
  93853. this._impostors = [];
  93854. this._joints = [];
  93855. if (!this._physicsPlugin.isSupported()) {
  93856. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  93857. + "Please make sure it is included.");
  93858. }
  93859. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  93860. this.setGravity(gravity);
  93861. this.setTimeStep();
  93862. }
  93863. /**
  93864. * Sets the gravity vector used by the simulation
  93865. * @param gravity defines the gravity vector to use
  93866. */
  93867. PhysicsEngine.prototype.setGravity = function (gravity) {
  93868. this.gravity = gravity;
  93869. this._physicsPlugin.setGravity(this.gravity);
  93870. };
  93871. /**
  93872. * Set the time step of the physics engine.
  93873. * Default is 1/60.
  93874. * To slow it down, enter 1/600 for example.
  93875. * To speed it up, 1/30
  93876. * @param newTimeStep defines the new timestep to apply to this world.
  93877. */
  93878. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  93879. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  93880. this._physicsPlugin.setTimeStep(newTimeStep);
  93881. };
  93882. /**
  93883. * Get the time step of the physics engine.
  93884. * @returns the current time step
  93885. */
  93886. PhysicsEngine.prototype.getTimeStep = function () {
  93887. return this._physicsPlugin.getTimeStep();
  93888. };
  93889. /**
  93890. * Release all resources
  93891. */
  93892. PhysicsEngine.prototype.dispose = function () {
  93893. this._impostors.forEach(function (impostor) {
  93894. impostor.dispose();
  93895. });
  93896. this._physicsPlugin.dispose();
  93897. };
  93898. /**
  93899. * Gets the name of the current physics plugin
  93900. * @returns the name of the plugin
  93901. */
  93902. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  93903. return this._physicsPlugin.name;
  93904. };
  93905. /**
  93906. * Adding a new impostor for the impostor tracking.
  93907. * This will be done by the impostor itself.
  93908. * @param impostor the impostor to add
  93909. */
  93910. PhysicsEngine.prototype.addImpostor = function (impostor) {
  93911. impostor.uniqueId = this._impostors.push(impostor);
  93912. //if no parent, generate the body
  93913. if (!impostor.parent) {
  93914. this._physicsPlugin.generatePhysicsBody(impostor);
  93915. }
  93916. };
  93917. /**
  93918. * Remove an impostor from the engine.
  93919. * This impostor and its mesh will not longer be updated by the physics engine.
  93920. * @param impostor the impostor to remove
  93921. */
  93922. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  93923. var index = this._impostors.indexOf(impostor);
  93924. if (index > -1) {
  93925. var removed = this._impostors.splice(index, 1);
  93926. //Is it needed?
  93927. if (removed.length) {
  93928. //this will also remove it from the world.
  93929. removed[0].physicsBody = null;
  93930. }
  93931. }
  93932. };
  93933. /**
  93934. * Add a joint to the physics engine
  93935. * @param mainImpostor defines the main impostor to which the joint is added.
  93936. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  93937. * @param joint defines the joint that will connect both impostors.
  93938. */
  93939. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  93940. var impostorJoint = {
  93941. mainImpostor: mainImpostor,
  93942. connectedImpostor: connectedImpostor,
  93943. joint: joint
  93944. };
  93945. joint.physicsPlugin = this._physicsPlugin;
  93946. this._joints.push(impostorJoint);
  93947. this._physicsPlugin.generateJoint(impostorJoint);
  93948. };
  93949. /**
  93950. * Removes a joint from the simulation
  93951. * @param mainImpostor defines the impostor used with the joint
  93952. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  93953. * @param joint defines the joint to remove
  93954. */
  93955. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  93956. var matchingJoints = this._joints.filter(function (impostorJoint) {
  93957. return (impostorJoint.connectedImpostor === connectedImpostor
  93958. && impostorJoint.joint === joint
  93959. && impostorJoint.mainImpostor === mainImpostor);
  93960. });
  93961. if (matchingJoints.length) {
  93962. this._physicsPlugin.removeJoint(matchingJoints[0]);
  93963. //TODO remove it from the list as well
  93964. }
  93965. };
  93966. /**
  93967. * Called by the scene. No need to call it.
  93968. * @param delta defines the timespam between frames
  93969. */
  93970. PhysicsEngine.prototype._step = function (delta) {
  93971. var _this = this;
  93972. //check if any mesh has no body / requires an update
  93973. this._impostors.forEach(function (impostor) {
  93974. if (impostor.isBodyInitRequired()) {
  93975. _this._physicsPlugin.generatePhysicsBody(impostor);
  93976. }
  93977. });
  93978. if (delta > 0.1) {
  93979. delta = 0.1;
  93980. }
  93981. else if (delta <= 0) {
  93982. delta = 1.0 / 60.0;
  93983. }
  93984. this._physicsPlugin.executeStep(delta, this._impostors);
  93985. };
  93986. /**
  93987. * Gets the current plugin used to run the simulation
  93988. * @returns current plugin
  93989. */
  93990. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  93991. return this._physicsPlugin;
  93992. };
  93993. /**
  93994. * Gets the list of physic impostors
  93995. * @returns an array of PhysicsImpostor
  93996. */
  93997. PhysicsEngine.prototype.getImpostors = function () {
  93998. return this._impostors;
  93999. };
  94000. /**
  94001. * Gets the impostor for a physics enabled object
  94002. * @param object defines the object impersonated by the impostor
  94003. * @returns the PhysicsImpostor or null if not found
  94004. */
  94005. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  94006. for (var i = 0; i < this._impostors.length; ++i) {
  94007. if (this._impostors[i].object === object) {
  94008. return this._impostors[i];
  94009. }
  94010. }
  94011. return null;
  94012. };
  94013. /**
  94014. * Gets the impostor for a physics body object
  94015. * @param body defines physics body used by the impostor
  94016. * @returns the PhysicsImpostor or null if not found
  94017. */
  94018. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  94019. for (var i = 0; i < this._impostors.length; ++i) {
  94020. if (this._impostors[i].physicsBody === body) {
  94021. return this._impostors[i];
  94022. }
  94023. }
  94024. return null;
  94025. };
  94026. /**
  94027. * Global value used to control the smallest number supported by the simulation
  94028. */
  94029. PhysicsEngine.Epsilon = 0.001;
  94030. return PhysicsEngine;
  94031. }());
  94032. BABYLON.PhysicsEngine = PhysicsEngine;
  94033. })(BABYLON || (BABYLON = {}));
  94034. //# sourceMappingURL=babylon.physicsEngine.js.map
  94035. var BABYLON;
  94036. (function (BABYLON) {
  94037. var PhysicsHelper = /** @class */ (function () {
  94038. function PhysicsHelper(scene) {
  94039. this._scene = scene;
  94040. this._physicsEngine = this._scene.getPhysicsEngine();
  94041. if (!this._physicsEngine) {
  94042. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  94043. }
  94044. }
  94045. /**
  94046. * @param {Vector3} origin the origin of the explosion
  94047. * @param {number} radius the explosion radius
  94048. * @param {number} strength the explosion strength
  94049. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  94050. */
  94051. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  94052. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94053. if (!this._physicsEngine) {
  94054. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  94055. return null;
  94056. }
  94057. var impostors = this._physicsEngine.getImpostors();
  94058. if (impostors.length === 0) {
  94059. return null;
  94060. }
  94061. var event = new PhysicsRadialExplosionEvent(this._scene);
  94062. impostors.forEach(function (impostor) {
  94063. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  94064. if (!impostorForceAndContactPoint) {
  94065. return;
  94066. }
  94067. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94068. });
  94069. event.dispose(false);
  94070. return event;
  94071. };
  94072. /**
  94073. * @param {Vector3} origin the origin of the explosion
  94074. * @param {number} radius the explosion radius
  94075. * @param {number} strength the explosion strength
  94076. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  94077. */
  94078. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  94079. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94080. if (!this._physicsEngine) {
  94081. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94082. return null;
  94083. }
  94084. var impostors = this._physicsEngine.getImpostors();
  94085. if (impostors.length === 0) {
  94086. return null;
  94087. }
  94088. var event = new PhysicsRadialExplosionEvent(this._scene);
  94089. impostors.forEach(function (impostor) {
  94090. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  94091. if (!impostorForceAndContactPoint) {
  94092. return;
  94093. }
  94094. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94095. });
  94096. event.dispose(false);
  94097. return event;
  94098. };
  94099. /**
  94100. * @param {Vector3} origin the origin of the explosion
  94101. * @param {number} radius the explosion radius
  94102. * @param {number} strength the explosion strength
  94103. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  94104. */
  94105. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  94106. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94107. if (!this._physicsEngine) {
  94108. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94109. return null;
  94110. }
  94111. var impostors = this._physicsEngine.getImpostors();
  94112. if (impostors.length === 0) {
  94113. return null;
  94114. }
  94115. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  94116. event.dispose(false);
  94117. return event;
  94118. };
  94119. /**
  94120. * @param {Vector3} origin the origin of the updraft
  94121. * @param {number} radius the radius of the updraft
  94122. * @param {number} strength the strength of the updraft
  94123. * @param {number} height the height of the updraft
  94124. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  94125. */
  94126. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  94127. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  94128. if (!this._physicsEngine) {
  94129. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94130. return null;
  94131. }
  94132. if (this._physicsEngine.getImpostors().length === 0) {
  94133. return null;
  94134. }
  94135. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  94136. event.dispose(false);
  94137. return event;
  94138. };
  94139. /**
  94140. * @param {Vector3} origin the of the vortex
  94141. * @param {number} radius the radius of the vortex
  94142. * @param {number} strength the strength of the vortex
  94143. * @param {number} height the height of the vortex
  94144. */
  94145. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  94146. if (!this._physicsEngine) {
  94147. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94148. return null;
  94149. }
  94150. if (this._physicsEngine.getImpostors().length === 0) {
  94151. return null;
  94152. }
  94153. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  94154. event.dispose(false);
  94155. return event;
  94156. };
  94157. return PhysicsHelper;
  94158. }());
  94159. BABYLON.PhysicsHelper = PhysicsHelper;
  94160. /***** Radial explosion *****/
  94161. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  94162. function PhysicsRadialExplosionEvent(scene) {
  94163. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  94164. this._rays = [];
  94165. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  94166. this._scene = scene;
  94167. }
  94168. /**
  94169. * Returns the data related to the radial explosion event (sphere & rays).
  94170. * @returns {PhysicsRadialExplosionEventData}
  94171. */
  94172. PhysicsRadialExplosionEvent.prototype.getData = function () {
  94173. this._dataFetched = true;
  94174. return {
  94175. sphere: this._sphere,
  94176. rays: this._rays,
  94177. };
  94178. };
  94179. /**
  94180. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  94181. * @param impostor
  94182. * @param {Vector3} origin the origin of the explosion
  94183. * @param {number} radius the explosion radius
  94184. * @param {number} strength the explosion strength
  94185. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  94186. * @returns {Nullable<PhysicsForceAndContactPoint>}
  94187. */
  94188. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  94189. if (impostor.mass === 0) {
  94190. return null;
  94191. }
  94192. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  94193. return null;
  94194. }
  94195. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  94196. return null;
  94197. }
  94198. var impostorObjectCenter = impostor.getObjectCenter();
  94199. var direction = impostorObjectCenter.subtract(origin);
  94200. var ray = new BABYLON.Ray(origin, direction, radius);
  94201. this._rays.push(ray);
  94202. var hit = ray.intersectsMesh(impostor.object);
  94203. var contactPoint = hit.pickedPoint;
  94204. if (!contactPoint) {
  94205. return null;
  94206. }
  94207. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  94208. if (distanceFromOrigin > radius) {
  94209. return null;
  94210. }
  94211. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  94212. ? strength
  94213. : strength * (1 - (distanceFromOrigin / radius));
  94214. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  94215. return { force: force, contactPoint: contactPoint };
  94216. };
  94217. /**
  94218. * Disposes the sphere.
  94219. * @param {bolean} force
  94220. */
  94221. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  94222. var _this = this;
  94223. if (force === void 0) { force = true; }
  94224. if (force) {
  94225. this._sphere.dispose();
  94226. }
  94227. else {
  94228. setTimeout(function () {
  94229. if (!_this._dataFetched) {
  94230. _this._sphere.dispose();
  94231. }
  94232. }, 0);
  94233. }
  94234. };
  94235. /*** Helpers ***/
  94236. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  94237. if (!this._sphere) {
  94238. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  94239. this._sphere.isVisible = false;
  94240. }
  94241. };
  94242. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  94243. var impostorObject = impostor.object;
  94244. this._prepareSphere();
  94245. this._sphere.position = origin;
  94246. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  94247. this._sphere._updateBoundingInfo();
  94248. this._sphere.computeWorldMatrix(true);
  94249. return this._sphere.intersectsMesh(impostorObject, true);
  94250. };
  94251. return PhysicsRadialExplosionEvent;
  94252. }());
  94253. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  94254. /***** Gravitational Field *****/
  94255. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  94256. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  94257. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94258. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  94259. this._physicsHelper = physicsHelper;
  94260. this._scene = scene;
  94261. this._origin = origin;
  94262. this._radius = radius;
  94263. this._strength = strength;
  94264. this._falloff = falloff;
  94265. this._tickCallback = this._tick.bind(this);
  94266. }
  94267. /**
  94268. * Returns the data related to the gravitational field event (sphere).
  94269. * @returns {PhysicsGravitationalFieldEventData}
  94270. */
  94271. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  94272. this._dataFetched = true;
  94273. return {
  94274. sphere: this._sphere,
  94275. };
  94276. };
  94277. /**
  94278. * Enables the gravitational field.
  94279. */
  94280. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  94281. this._tickCallback.call(this);
  94282. this._scene.registerBeforeRender(this._tickCallback);
  94283. };
  94284. /**
  94285. * Disables the gravitational field.
  94286. */
  94287. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  94288. this._scene.unregisterBeforeRender(this._tickCallback);
  94289. };
  94290. /**
  94291. * Disposes the sphere.
  94292. * @param {bolean} force
  94293. */
  94294. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  94295. var _this = this;
  94296. if (force === void 0) { force = true; }
  94297. if (force) {
  94298. this._sphere.dispose();
  94299. }
  94300. else {
  94301. setTimeout(function () {
  94302. if (!_this._dataFetched) {
  94303. _this._sphere.dispose();
  94304. }
  94305. }, 0);
  94306. }
  94307. };
  94308. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  94309. // Since the params won't change, we fetch the event only once
  94310. if (this._sphere) {
  94311. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  94312. }
  94313. else {
  94314. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  94315. if (radialExplosionEvent) {
  94316. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  94317. }
  94318. }
  94319. };
  94320. return PhysicsGravitationalFieldEvent;
  94321. }());
  94322. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  94323. /***** Updraft *****/
  94324. var PhysicsUpdraftEvent = /** @class */ (function () {
  94325. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  94326. this._scene = _scene;
  94327. this._origin = _origin;
  94328. this._radius = _radius;
  94329. this._strength = _strength;
  94330. this._height = _height;
  94331. this._updraftMode = _updraftMode;
  94332. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  94333. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  94334. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  94335. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  94336. this._physicsEngine = this._scene.getPhysicsEngine();
  94337. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  94338. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  94339. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  94340. this._originDirection = this._origin.subtract(this._originTop).normalize();
  94341. }
  94342. this._tickCallback = this._tick.bind(this);
  94343. }
  94344. /**
  94345. * Returns the data related to the updraft event (cylinder).
  94346. * @returns {PhysicsUpdraftEventData}
  94347. */
  94348. PhysicsUpdraftEvent.prototype.getData = function () {
  94349. this._dataFetched = true;
  94350. return {
  94351. cylinder: this._cylinder,
  94352. };
  94353. };
  94354. /**
  94355. * Enables the updraft.
  94356. */
  94357. PhysicsUpdraftEvent.prototype.enable = function () {
  94358. this._tickCallback.call(this);
  94359. this._scene.registerBeforeRender(this._tickCallback);
  94360. };
  94361. /**
  94362. * Disables the cortex.
  94363. */
  94364. PhysicsUpdraftEvent.prototype.disable = function () {
  94365. this._scene.unregisterBeforeRender(this._tickCallback);
  94366. };
  94367. /**
  94368. * Disposes the sphere.
  94369. * @param {bolean} force
  94370. */
  94371. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  94372. var _this = this;
  94373. if (force === void 0) { force = true; }
  94374. if (force) {
  94375. this._cylinder.dispose();
  94376. }
  94377. else {
  94378. setTimeout(function () {
  94379. if (!_this._dataFetched) {
  94380. _this._cylinder.dispose();
  94381. }
  94382. }, 0);
  94383. }
  94384. };
  94385. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  94386. if (impostor.mass === 0) {
  94387. return null;
  94388. }
  94389. if (!this._intersectsWithCylinder(impostor)) {
  94390. return null;
  94391. }
  94392. var impostorObjectCenter = impostor.getObjectCenter();
  94393. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  94394. var direction = this._originDirection;
  94395. }
  94396. else {
  94397. var direction = impostorObjectCenter.subtract(this._originTop);
  94398. }
  94399. var multiplier = this._strength * -1;
  94400. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  94401. return { force: force, contactPoint: impostorObjectCenter };
  94402. };
  94403. PhysicsUpdraftEvent.prototype._tick = function () {
  94404. var _this = this;
  94405. this._physicsEngine.getImpostors().forEach(function (impostor) {
  94406. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  94407. if (!impostorForceAndContactPoint) {
  94408. return;
  94409. }
  94410. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94411. });
  94412. };
  94413. /*** Helpers ***/
  94414. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  94415. if (!this._cylinder) {
  94416. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  94417. height: this._height,
  94418. diameter: this._radius * 2,
  94419. }, this._scene);
  94420. this._cylinder.isVisible = false;
  94421. }
  94422. };
  94423. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  94424. var impostorObject = impostor.object;
  94425. this._prepareCylinder();
  94426. this._cylinder.position = this._cylinderPosition;
  94427. return this._cylinder.intersectsMesh(impostorObject, true);
  94428. };
  94429. return PhysicsUpdraftEvent;
  94430. }());
  94431. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  94432. /***** Vortex *****/
  94433. var PhysicsVortexEvent = /** @class */ (function () {
  94434. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  94435. this._scene = _scene;
  94436. this._origin = _origin;
  94437. this._radius = _radius;
  94438. this._strength = _strength;
  94439. this._height = _height;
  94440. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  94441. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  94442. this._updraftMultiplier = 0.02;
  94443. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  94444. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  94445. this._physicsEngine = this._scene.getPhysicsEngine();
  94446. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  94447. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  94448. this._tickCallback = this._tick.bind(this);
  94449. }
  94450. /**
  94451. * Returns the data related to the vortex event (cylinder).
  94452. * @returns {PhysicsVortexEventData}
  94453. */
  94454. PhysicsVortexEvent.prototype.getData = function () {
  94455. this._dataFetched = true;
  94456. return {
  94457. cylinder: this._cylinder,
  94458. };
  94459. };
  94460. /**
  94461. * Enables the vortex.
  94462. */
  94463. PhysicsVortexEvent.prototype.enable = function () {
  94464. this._tickCallback.call(this);
  94465. this._scene.registerBeforeRender(this._tickCallback);
  94466. };
  94467. /**
  94468. * Disables the cortex.
  94469. */
  94470. PhysicsVortexEvent.prototype.disable = function () {
  94471. this._scene.unregisterBeforeRender(this._tickCallback);
  94472. };
  94473. /**
  94474. * Disposes the sphere.
  94475. * @param {bolean} force
  94476. */
  94477. PhysicsVortexEvent.prototype.dispose = function (force) {
  94478. var _this = this;
  94479. if (force === void 0) { force = true; }
  94480. if (force) {
  94481. this._cylinder.dispose();
  94482. }
  94483. else {
  94484. setTimeout(function () {
  94485. if (!_this._dataFetched) {
  94486. _this._cylinder.dispose();
  94487. }
  94488. }, 0);
  94489. }
  94490. };
  94491. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  94492. if (impostor.mass === 0) {
  94493. return null;
  94494. }
  94495. if (!this._intersectsWithCylinder(impostor)) {
  94496. return null;
  94497. }
  94498. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  94499. return null;
  94500. }
  94501. var impostorObjectCenter = impostor.getObjectCenter();
  94502. 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)
  94503. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  94504. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  94505. var hit = ray.intersectsMesh(impostor.object);
  94506. var contactPoint = hit.pickedPoint;
  94507. if (!contactPoint) {
  94508. return null;
  94509. }
  94510. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  94511. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  94512. var directionToOrigin = contactPoint.normalize();
  94513. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  94514. directionToOrigin = directionToOrigin.negate();
  94515. }
  94516. // TODO: find a more physically based solution
  94517. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  94518. var forceX = directionToOrigin.x * this._strength / 8;
  94519. var forceY = directionToOrigin.y * this._updraftMultiplier;
  94520. var forceZ = directionToOrigin.z * this._strength / 8;
  94521. }
  94522. else {
  94523. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  94524. var forceY = this._originTop.y * this._updraftMultiplier;
  94525. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  94526. }
  94527. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  94528. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  94529. return { force: force, contactPoint: impostorObjectCenter };
  94530. };
  94531. PhysicsVortexEvent.prototype._tick = function () {
  94532. var _this = this;
  94533. this._physicsEngine.getImpostors().forEach(function (impostor) {
  94534. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  94535. if (!impostorForceAndContactPoint) {
  94536. return;
  94537. }
  94538. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94539. });
  94540. };
  94541. /*** Helpers ***/
  94542. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  94543. if (!this._cylinder) {
  94544. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  94545. height: this._height,
  94546. diameter: this._radius * 2,
  94547. }, this._scene);
  94548. this._cylinder.isVisible = false;
  94549. }
  94550. };
  94551. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  94552. var impostorObject = impostor.object;
  94553. this._prepareCylinder();
  94554. this._cylinder.position = this._cylinderPosition;
  94555. return this._cylinder.intersectsMesh(impostorObject, true);
  94556. };
  94557. return PhysicsVortexEvent;
  94558. }());
  94559. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  94560. /***** Enums *****/
  94561. /**
  94562. * The strenght of the force in correspondence to the distance of the affected object
  94563. */
  94564. var PhysicsRadialImpulseFalloff;
  94565. (function (PhysicsRadialImpulseFalloff) {
  94566. /** Defines that impulse is constant in strength across it's whole radius */
  94567. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  94568. /** DEfines that impulse gets weaker if it's further from the origin */
  94569. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  94570. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  94571. /**
  94572. * The strenght of the force in correspondence to the distance of the affected object
  94573. */
  94574. var PhysicsUpdraftMode;
  94575. (function (PhysicsUpdraftMode) {
  94576. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  94577. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  94578. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  94579. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  94580. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  94581. })(BABYLON || (BABYLON = {}));
  94582. //# sourceMappingURL=babylon.physicsHelper.js.map
  94583. var BABYLON;
  94584. (function (BABYLON) {
  94585. /** @hidden */
  94586. var CannonJSPlugin = /** @class */ (function () {
  94587. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  94588. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  94589. if (iterations === void 0) { iterations = 10; }
  94590. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  94591. this.name = "CannonJSPlugin";
  94592. this._physicsMaterials = new Array();
  94593. this._fixedTimeStep = 1 / 60;
  94594. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  94595. this.BJSCANNON = CANNON;
  94596. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  94597. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  94598. this._tmpPosition = BABYLON.Vector3.Zero();
  94599. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  94600. this._tmpUnityRotation = new BABYLON.Quaternion();
  94601. if (!this.isSupported()) {
  94602. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  94603. return;
  94604. }
  94605. this._extendNamespace();
  94606. this.world = new this.BJSCANNON.World();
  94607. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  94608. this.world.solver.iterations = iterations;
  94609. }
  94610. CannonJSPlugin.prototype.setGravity = function (gravity) {
  94611. this.world.gravity.copy(gravity);
  94612. };
  94613. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  94614. this._fixedTimeStep = timeStep;
  94615. };
  94616. CannonJSPlugin.prototype.getTimeStep = function () {
  94617. return this._fixedTimeStep;
  94618. };
  94619. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  94620. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  94621. };
  94622. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  94623. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  94624. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  94625. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  94626. };
  94627. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  94628. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  94629. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  94630. impostor.physicsBody.applyForce(impulse, worldPoint);
  94631. };
  94632. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  94633. //parent-child relationship. Does this impostor has a parent impostor?
  94634. if (impostor.parent) {
  94635. if (impostor.physicsBody) {
  94636. this.removePhysicsBody(impostor);
  94637. //TODO is that needed?
  94638. impostor.forceUpdate();
  94639. }
  94640. return;
  94641. }
  94642. //should a new body be created for this impostor?
  94643. if (impostor.isBodyInitRequired()) {
  94644. var shape = this._createShape(impostor);
  94645. //unregister events, if body is being changed
  94646. var oldBody = impostor.physicsBody;
  94647. if (oldBody) {
  94648. this.removePhysicsBody(impostor);
  94649. }
  94650. //create the body and material
  94651. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  94652. var bodyCreationObject = {
  94653. mass: impostor.getParam("mass"),
  94654. material: material
  94655. };
  94656. // A simple extend, in case native options were used.
  94657. var nativeOptions = impostor.getParam("nativeOptions");
  94658. for (var key in nativeOptions) {
  94659. if (nativeOptions.hasOwnProperty(key)) {
  94660. bodyCreationObject[key] = nativeOptions[key];
  94661. }
  94662. }
  94663. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  94664. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  94665. this.world.addEventListener("preStep", impostor.beforeStep);
  94666. this.world.addEventListener("postStep", impostor.afterStep);
  94667. impostor.physicsBody.addShape(shape);
  94668. this.world.add(impostor.physicsBody);
  94669. //try to keep the body moving in the right direction by taking old properties.
  94670. //Should be tested!
  94671. if (oldBody) {
  94672. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  94673. impostor.physicsBody[param].copy(oldBody[param]);
  94674. });
  94675. }
  94676. this._processChildMeshes(impostor);
  94677. }
  94678. //now update the body's transformation
  94679. this._updatePhysicsBodyTransformation(impostor);
  94680. };
  94681. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  94682. var _this = this;
  94683. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  94684. var currentRotation = mainImpostor.object.rotationQuaternion;
  94685. if (meshChildren.length) {
  94686. var processMesh = function (localPosition, mesh) {
  94687. if (!currentRotation || !mesh.rotationQuaternion) {
  94688. return;
  94689. }
  94690. var childImpostor = mesh.getPhysicsImpostor();
  94691. if (childImpostor) {
  94692. var parent = childImpostor.parent;
  94693. if (parent !== mainImpostor) {
  94694. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  94695. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  94696. if (childImpostor.physicsBody) {
  94697. _this.removePhysicsBody(childImpostor);
  94698. childImpostor.physicsBody = null;
  94699. }
  94700. childImpostor.parent = mainImpostor;
  94701. childImpostor.resetUpdateFlags();
  94702. 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));
  94703. //Add the mass of the children.
  94704. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  94705. }
  94706. }
  94707. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  94708. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  94709. };
  94710. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  94711. }
  94712. };
  94713. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  94714. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  94715. this.world.removeEventListener("preStep", impostor.beforeStep);
  94716. this.world.removeEventListener("postStep", impostor.afterStep);
  94717. this.world.remove(impostor.physicsBody);
  94718. };
  94719. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  94720. var mainBody = impostorJoint.mainImpostor.physicsBody;
  94721. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  94722. if (!mainBody || !connectedBody) {
  94723. return;
  94724. }
  94725. var constraint;
  94726. var jointData = impostorJoint.joint.jointData;
  94727. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  94728. var constraintData = {
  94729. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  94730. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  94731. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  94732. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  94733. maxForce: jointData.nativeParams.maxForce,
  94734. collideConnected: !!jointData.collision
  94735. };
  94736. switch (impostorJoint.joint.type) {
  94737. case BABYLON.PhysicsJoint.HingeJoint:
  94738. case BABYLON.PhysicsJoint.Hinge2Joint:
  94739. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  94740. break;
  94741. case BABYLON.PhysicsJoint.DistanceJoint:
  94742. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  94743. break;
  94744. case BABYLON.PhysicsJoint.SpringJoint:
  94745. var springData = jointData;
  94746. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  94747. restLength: springData.length,
  94748. stiffness: springData.stiffness,
  94749. damping: springData.damping,
  94750. localAnchorA: constraintData.pivotA,
  94751. localAnchorB: constraintData.pivotB
  94752. });
  94753. break;
  94754. case BABYLON.PhysicsJoint.LockJoint:
  94755. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  94756. break;
  94757. case BABYLON.PhysicsJoint.PointToPointJoint:
  94758. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  94759. default:
  94760. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  94761. break;
  94762. }
  94763. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  94764. constraint.collideConnected = !!jointData.collision;
  94765. impostorJoint.joint.physicsJoint = constraint;
  94766. //don't add spring as constraint, as it is not one.
  94767. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  94768. this.world.addConstraint(constraint);
  94769. }
  94770. else {
  94771. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  94772. constraint.applyForce();
  94773. };
  94774. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  94775. }
  94776. };
  94777. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  94778. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  94779. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  94780. }
  94781. else {
  94782. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  94783. }
  94784. };
  94785. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  94786. var index;
  94787. var mat;
  94788. for (index = 0; index < this._physicsMaterials.length; index++) {
  94789. mat = this._physicsMaterials[index];
  94790. if (mat.friction === friction && mat.restitution === restitution) {
  94791. return mat;
  94792. }
  94793. }
  94794. var currentMat = new this.BJSCANNON.Material(name);
  94795. currentMat.friction = friction;
  94796. currentMat.restitution = restitution;
  94797. this._physicsMaterials.push(currentMat);
  94798. return currentMat;
  94799. };
  94800. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  94801. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  94802. };
  94803. CannonJSPlugin.prototype._createShape = function (impostor) {
  94804. var object = impostor.object;
  94805. var returnValue;
  94806. var extendSize = impostor.getObjectExtendSize();
  94807. switch (impostor.type) {
  94808. case BABYLON.PhysicsImpostor.SphereImpostor:
  94809. var radiusX = extendSize.x;
  94810. var radiusY = extendSize.y;
  94811. var radiusZ = extendSize.z;
  94812. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  94813. break;
  94814. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  94815. case BABYLON.PhysicsImpostor.CylinderImpostor:
  94816. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  94817. break;
  94818. case BABYLON.PhysicsImpostor.BoxImpostor:
  94819. var box = extendSize.scale(0.5);
  94820. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  94821. break;
  94822. case BABYLON.PhysicsImpostor.PlaneImpostor:
  94823. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  94824. returnValue = new this.BJSCANNON.Plane();
  94825. break;
  94826. case BABYLON.PhysicsImpostor.MeshImpostor:
  94827. // should transform the vertex data to world coordinates!!
  94828. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  94829. var rawFaces = object.getIndices ? object.getIndices() : [];
  94830. if (!rawVerts)
  94831. return;
  94832. // get only scale! so the object could transform correctly.
  94833. var oldPosition = object.position.clone();
  94834. var oldRotation = object.rotation && object.rotation.clone();
  94835. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  94836. object.position.copyFromFloats(0, 0, 0);
  94837. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  94838. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  94839. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  94840. var transform = object.computeWorldMatrix(true);
  94841. // convert rawVerts to object space
  94842. var temp = new Array();
  94843. var index;
  94844. for (index = 0; index < rawVerts.length; index += 3) {
  94845. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  94846. }
  94847. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  94848. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  94849. //now set back the transformation!
  94850. object.position.copyFrom(oldPosition);
  94851. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  94852. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  94853. break;
  94854. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  94855. var oldPosition2 = object.position.clone();
  94856. var oldRotation2 = object.rotation && object.rotation.clone();
  94857. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  94858. object.position.copyFromFloats(0, 0, 0);
  94859. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  94860. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  94861. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  94862. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  94863. returnValue = this._createHeightmap(object);
  94864. object.position.copyFrom(oldPosition2);
  94865. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  94866. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  94867. object.computeWorldMatrix(true);
  94868. break;
  94869. case BABYLON.PhysicsImpostor.ParticleImpostor:
  94870. returnValue = new this.BJSCANNON.Particle();
  94871. break;
  94872. }
  94873. return returnValue;
  94874. };
  94875. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  94876. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  94877. var transform = object.computeWorldMatrix(true);
  94878. // convert rawVerts to object space
  94879. var temp = new Array();
  94880. var index;
  94881. for (index = 0; index < pos.length; index += 3) {
  94882. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  94883. }
  94884. pos = temp;
  94885. var matrix = new Array();
  94886. //For now pointDepth will not be used and will be automatically calculated.
  94887. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  94888. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  94889. var boundingInfo = object.getBoundingInfo();
  94890. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  94891. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  94892. var elementSize = dim * 2 / arraySize;
  94893. for (var i = 0; i < pos.length; i = i + 3) {
  94894. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  94895. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  94896. var y = -pos[i + 2] + minY;
  94897. if (!matrix[x]) {
  94898. matrix[x] = [];
  94899. }
  94900. if (!matrix[x][z]) {
  94901. matrix[x][z] = y;
  94902. }
  94903. matrix[x][z] = Math.max(y, matrix[x][z]);
  94904. }
  94905. for (var x = 0; x <= arraySize; ++x) {
  94906. if (!matrix[x]) {
  94907. var loc = 1;
  94908. while (!matrix[(x + loc) % arraySize]) {
  94909. loc++;
  94910. }
  94911. matrix[x] = matrix[(x + loc) % arraySize].slice();
  94912. //console.log("missing x", x);
  94913. }
  94914. for (var z = 0; z <= arraySize; ++z) {
  94915. if (!matrix[x][z]) {
  94916. var loc = 1;
  94917. var newValue;
  94918. while (newValue === undefined) {
  94919. newValue = matrix[x][(z + loc++) % arraySize];
  94920. }
  94921. matrix[x][z] = newValue;
  94922. }
  94923. }
  94924. }
  94925. var shape = new this.BJSCANNON.Heightfield(matrix, {
  94926. elementSize: elementSize
  94927. });
  94928. //For future reference, needed for body transformation
  94929. shape.minY = minY;
  94930. return shape;
  94931. };
  94932. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  94933. var object = impostor.object;
  94934. //make sure it is updated...
  94935. object.computeWorldMatrix && object.computeWorldMatrix(true);
  94936. // The delta between the mesh position and the mesh bounding box center
  94937. var bInfo = object.getBoundingInfo();
  94938. if (!bInfo)
  94939. return;
  94940. var center = impostor.getObjectCenter();
  94941. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  94942. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  94943. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  94944. this._tmpPosition.copyFrom(center);
  94945. var quaternion = object.rotationQuaternion;
  94946. if (!quaternion) {
  94947. return;
  94948. }
  94949. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  94950. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  94951. //-90 DEG in X, precalculated
  94952. quaternion = quaternion.multiply(this._minus90X);
  94953. //Invert! (Precalculated, 90 deg in X)
  94954. //No need to clone. this will never change.
  94955. impostor.setDeltaRotation(this._plus90X);
  94956. }
  94957. //If it is a heightfield, if should be centered.
  94958. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  94959. var mesh = object;
  94960. var boundingInfo = mesh.getBoundingInfo();
  94961. //calculate the correct body position:
  94962. var rotationQuaternion = mesh.rotationQuaternion;
  94963. mesh.rotationQuaternion = this._tmpUnityRotation;
  94964. mesh.computeWorldMatrix(true);
  94965. //get original center with no rotation
  94966. var c = center.clone();
  94967. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  94968. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  94969. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  94970. mesh.setPreTransformMatrix(p);
  94971. mesh.computeWorldMatrix(true);
  94972. //calculate the translation
  94973. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  94974. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  94975. //add it inverted to the delta
  94976. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  94977. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  94978. //rotation is back
  94979. mesh.rotationQuaternion = rotationQuaternion;
  94980. mesh.setPreTransformMatrix(oldPivot);
  94981. mesh.computeWorldMatrix(true);
  94982. }
  94983. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  94984. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  94985. //this._tmpPosition.copyFrom(object.position);
  94986. }
  94987. impostor.setDeltaPosition(this._tmpDeltaPosition);
  94988. //Now update the impostor object
  94989. impostor.physicsBody.position.copy(this._tmpPosition);
  94990. impostor.physicsBody.quaternion.copy(quaternion);
  94991. };
  94992. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  94993. impostor.object.position.copyFrom(impostor.physicsBody.position);
  94994. if (impostor.object.rotationQuaternion) {
  94995. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  94996. }
  94997. };
  94998. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  94999. impostor.physicsBody.position.copy(newPosition);
  95000. impostor.physicsBody.quaternion.copy(newRotation);
  95001. };
  95002. CannonJSPlugin.prototype.isSupported = function () {
  95003. return this.BJSCANNON !== undefined;
  95004. };
  95005. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  95006. impostor.physicsBody.velocity.copy(velocity);
  95007. };
  95008. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  95009. impostor.physicsBody.angularVelocity.copy(velocity);
  95010. };
  95011. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  95012. var v = impostor.physicsBody.velocity;
  95013. if (!v) {
  95014. return null;
  95015. }
  95016. return new BABYLON.Vector3(v.x, v.y, v.z);
  95017. };
  95018. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  95019. var v = impostor.physicsBody.angularVelocity;
  95020. if (!v) {
  95021. return null;
  95022. }
  95023. return new BABYLON.Vector3(v.x, v.y, v.z);
  95024. };
  95025. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  95026. impostor.physicsBody.mass = mass;
  95027. impostor.physicsBody.updateMassProperties();
  95028. };
  95029. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  95030. return impostor.physicsBody.mass;
  95031. };
  95032. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  95033. return impostor.physicsBody.material.friction;
  95034. };
  95035. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  95036. impostor.physicsBody.material.friction = friction;
  95037. };
  95038. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  95039. return impostor.physicsBody.material.restitution;
  95040. };
  95041. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  95042. impostor.physicsBody.material.restitution = restitution;
  95043. };
  95044. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  95045. impostor.physicsBody.sleep();
  95046. };
  95047. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  95048. impostor.physicsBody.wakeUp();
  95049. };
  95050. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  95051. joint.physicsJoint.distance = maxDistance;
  95052. };
  95053. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  95054. // if (!motorIndex) {
  95055. // joint.physicsJoint.enableMotor();
  95056. // }
  95057. // }
  95058. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  95059. // if (!motorIndex) {
  95060. // joint.physicsJoint.disableMotor();
  95061. // }
  95062. // }
  95063. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  95064. if (!motorIndex) {
  95065. joint.physicsJoint.enableMotor();
  95066. joint.physicsJoint.setMotorSpeed(speed);
  95067. if (maxForce) {
  95068. this.setLimit(joint, maxForce);
  95069. }
  95070. }
  95071. };
  95072. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  95073. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  95074. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  95075. };
  95076. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  95077. var body = impostor.physicsBody;
  95078. mesh.position.x = body.position.x;
  95079. mesh.position.y = body.position.y;
  95080. mesh.position.z = body.position.z;
  95081. if (mesh.rotationQuaternion) {
  95082. mesh.rotationQuaternion.x = body.quaternion.x;
  95083. mesh.rotationQuaternion.y = body.quaternion.y;
  95084. mesh.rotationQuaternion.z = body.quaternion.z;
  95085. mesh.rotationQuaternion.w = body.quaternion.w;
  95086. }
  95087. };
  95088. CannonJSPlugin.prototype.getRadius = function (impostor) {
  95089. var shape = impostor.physicsBody.shapes[0];
  95090. return shape.boundingSphereRadius;
  95091. };
  95092. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  95093. var shape = impostor.physicsBody.shapes[0];
  95094. result.x = shape.halfExtents.x * 2;
  95095. result.y = shape.halfExtents.y * 2;
  95096. result.z = shape.halfExtents.z * 2;
  95097. };
  95098. CannonJSPlugin.prototype.dispose = function () {
  95099. };
  95100. CannonJSPlugin.prototype._extendNamespace = function () {
  95101. //this will force cannon to execute at least one step when using interpolation
  95102. var step_tmp1 = new this.BJSCANNON.Vec3();
  95103. var Engine = this.BJSCANNON;
  95104. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  95105. maxSubSteps = maxSubSteps || 10;
  95106. timeSinceLastCalled = timeSinceLastCalled || 0;
  95107. if (timeSinceLastCalled === 0) {
  95108. this.internalStep(dt);
  95109. this.time += dt;
  95110. }
  95111. else {
  95112. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  95113. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  95114. var t0 = performance.now();
  95115. for (var i = 0; i !== internalSteps; i++) {
  95116. this.internalStep(dt);
  95117. if (performance.now() - t0 > dt * 1000) {
  95118. break;
  95119. }
  95120. }
  95121. this.time += timeSinceLastCalled;
  95122. var h = this.time % dt;
  95123. var h_div_dt = h / dt;
  95124. var interpvelo = step_tmp1;
  95125. var bodies = this.bodies;
  95126. for (var j = 0; j !== bodies.length; j++) {
  95127. var b = bodies[j];
  95128. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  95129. b.position.vsub(b.previousPosition, interpvelo);
  95130. interpvelo.scale(h_div_dt, interpvelo);
  95131. b.position.vadd(interpvelo, b.interpolatedPosition);
  95132. }
  95133. else {
  95134. b.interpolatedPosition.copy(b.position);
  95135. b.interpolatedQuaternion.copy(b.quaternion);
  95136. }
  95137. }
  95138. }
  95139. };
  95140. };
  95141. return CannonJSPlugin;
  95142. }());
  95143. BABYLON.CannonJSPlugin = CannonJSPlugin;
  95144. })(BABYLON || (BABYLON = {}));
  95145. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  95146. var BABYLON;
  95147. (function (BABYLON) {
  95148. /** @hidden */
  95149. var OimoJSPlugin = /** @class */ (function () {
  95150. function OimoJSPlugin(iterations) {
  95151. this.name = "OimoJSPlugin";
  95152. this._tmpImpostorsArray = [];
  95153. this._tmpPositionVector = BABYLON.Vector3.Zero();
  95154. this.BJSOIMO = OIMO;
  95155. this.world = new this.BJSOIMO.World({
  95156. iterations: iterations
  95157. });
  95158. this.world.clear();
  95159. }
  95160. OimoJSPlugin.prototype.setGravity = function (gravity) {
  95161. this.world.gravity.copy(gravity);
  95162. };
  95163. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  95164. this.world.timeStep = timeStep;
  95165. };
  95166. OimoJSPlugin.prototype.getTimeStep = function () {
  95167. return this.world.timeStep;
  95168. };
  95169. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  95170. var _this = this;
  95171. impostors.forEach(function (impostor) {
  95172. impostor.beforeStep();
  95173. });
  95174. this.world.step();
  95175. impostors.forEach(function (impostor) {
  95176. impostor.afterStep();
  95177. //update the ordered impostors array
  95178. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  95179. });
  95180. //check for collisions
  95181. var contact = this.world.contacts;
  95182. while (contact !== null) {
  95183. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  95184. contact = contact.next;
  95185. continue;
  95186. }
  95187. //is this body colliding with any other? get the impostor
  95188. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  95189. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  95190. if (!mainImpostor || !collidingImpostor) {
  95191. contact = contact.next;
  95192. continue;
  95193. }
  95194. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  95195. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  95196. contact = contact.next;
  95197. }
  95198. };
  95199. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  95200. var mass = impostor.physicsBody.mass;
  95201. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  95202. };
  95203. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  95204. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  95205. this.applyImpulse(impostor, force, contactPoint);
  95206. };
  95207. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  95208. var _this = this;
  95209. //parent-child relationship. Does this impostor has a parent impostor?
  95210. if (impostor.parent) {
  95211. if (impostor.physicsBody) {
  95212. this.removePhysicsBody(impostor);
  95213. //TODO is that needed?
  95214. impostor.forceUpdate();
  95215. }
  95216. return;
  95217. }
  95218. if (impostor.isBodyInitRequired()) {
  95219. var bodyConfig = {
  95220. name: impostor.uniqueId,
  95221. //Oimo must have mass, also for static objects.
  95222. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  95223. size: [],
  95224. type: [],
  95225. pos: [],
  95226. posShape: [],
  95227. rot: [],
  95228. rotShape: [],
  95229. move: impostor.getParam("mass") !== 0,
  95230. density: impostor.getParam("mass"),
  95231. friction: impostor.getParam("friction"),
  95232. restitution: impostor.getParam("restitution"),
  95233. //Supporting older versions of Oimo
  95234. world: this.world
  95235. };
  95236. var impostors = [impostor];
  95237. var addToArray = function (parent) {
  95238. if (!parent.getChildMeshes)
  95239. return;
  95240. parent.getChildMeshes().forEach(function (m) {
  95241. if (m.physicsImpostor) {
  95242. impostors.push(m.physicsImpostor);
  95243. //m.physicsImpostor._init();
  95244. }
  95245. });
  95246. };
  95247. addToArray(impostor.object);
  95248. var checkWithEpsilon_1 = function (value) {
  95249. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  95250. };
  95251. var globalQuaternion_1 = new BABYLON.Quaternion();
  95252. impostors.forEach(function (i) {
  95253. if (!i.object.rotationQuaternion) {
  95254. return;
  95255. }
  95256. //get the correct bounding box
  95257. var oldQuaternion = i.object.rotationQuaternion;
  95258. globalQuaternion_1 = oldQuaternion.clone();
  95259. var rot = oldQuaternion.toEulerAngles();
  95260. var extendSize = i.getObjectExtendSize();
  95261. var radToDeg = 57.295779513082320876;
  95262. if (i === impostor) {
  95263. var center = impostor.getObjectCenter();
  95264. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  95265. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  95266. //Can also use Array.prototype.push.apply
  95267. bodyConfig.pos.push(center.x);
  95268. bodyConfig.pos.push(center.y);
  95269. bodyConfig.pos.push(center.z);
  95270. bodyConfig.posShape.push(0, 0, 0);
  95271. //tmp solution
  95272. bodyConfig.rot.push(0);
  95273. bodyConfig.rot.push(0);
  95274. bodyConfig.rot.push(0);
  95275. bodyConfig.rotShape.push(0, 0, 0);
  95276. }
  95277. else {
  95278. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  95279. bodyConfig.posShape.push(localPosition.x);
  95280. bodyConfig.posShape.push(localPosition.y);
  95281. bodyConfig.posShape.push(localPosition.z);
  95282. bodyConfig.pos.push(0, 0, 0);
  95283. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  95284. bodyConfig.rot.push(0);
  95285. bodyConfig.rot.push(0);
  95286. bodyConfig.rot.push(0);
  95287. bodyConfig.rotShape.push(rot.x * radToDeg);
  95288. bodyConfig.rotShape.push(rot.y * radToDeg);
  95289. bodyConfig.rotShape.push(rot.z * radToDeg);
  95290. }
  95291. // register mesh
  95292. switch (i.type) {
  95293. case BABYLON.PhysicsImpostor.ParticleImpostor:
  95294. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  95295. case BABYLON.PhysicsImpostor.SphereImpostor:
  95296. var radiusX = extendSize.x;
  95297. var radiusY = extendSize.y;
  95298. var radiusZ = extendSize.z;
  95299. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  95300. bodyConfig.type.push('sphere');
  95301. //due to the way oimo works with compounds, add 3 times
  95302. bodyConfig.size.push(size);
  95303. bodyConfig.size.push(size);
  95304. bodyConfig.size.push(size);
  95305. break;
  95306. case BABYLON.PhysicsImpostor.CylinderImpostor:
  95307. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  95308. var sizeY = checkWithEpsilon_1(extendSize.y);
  95309. bodyConfig.type.push('cylinder');
  95310. bodyConfig.size.push(sizeX);
  95311. bodyConfig.size.push(sizeY);
  95312. //due to the way oimo works with compounds, add one more value.
  95313. bodyConfig.size.push(sizeY);
  95314. break;
  95315. case BABYLON.PhysicsImpostor.PlaneImpostor:
  95316. case BABYLON.PhysicsImpostor.BoxImpostor:
  95317. default:
  95318. var sizeX = checkWithEpsilon_1(extendSize.x);
  95319. var sizeY = checkWithEpsilon_1(extendSize.y);
  95320. var sizeZ = checkWithEpsilon_1(extendSize.z);
  95321. bodyConfig.type.push('box');
  95322. //if (i === impostor) {
  95323. bodyConfig.size.push(sizeX);
  95324. bodyConfig.size.push(sizeY);
  95325. bodyConfig.size.push(sizeZ);
  95326. //} else {
  95327. // bodyConfig.size.push(0,0,0);
  95328. //}
  95329. break;
  95330. }
  95331. //actually not needed, but hey...
  95332. i.object.rotationQuaternion = oldQuaternion;
  95333. });
  95334. impostor.physicsBody = this.world.add(bodyConfig);
  95335. // set the quaternion, ignoring the previously defined (euler) rotation
  95336. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  95337. // update with delta 0, so the body will reveive the new rotation.
  95338. impostor.physicsBody.updatePosition(0);
  95339. }
  95340. else {
  95341. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  95342. }
  95343. impostor.setDeltaPosition(this._tmpPositionVector);
  95344. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  95345. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  95346. };
  95347. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  95348. //impostor.physicsBody.dispose();
  95349. //Same as : (older oimo versions)
  95350. this.world.removeRigidBody(impostor.physicsBody);
  95351. };
  95352. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  95353. var mainBody = impostorJoint.mainImpostor.physicsBody;
  95354. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  95355. if (!mainBody || !connectedBody) {
  95356. return;
  95357. }
  95358. var jointData = impostorJoint.joint.jointData;
  95359. var options = jointData.nativeParams || {};
  95360. var type;
  95361. var nativeJointData = {
  95362. body1: mainBody,
  95363. body2: connectedBody,
  95364. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  95365. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  95366. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  95367. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  95368. min: options.min,
  95369. max: options.max,
  95370. collision: options.collision || jointData.collision,
  95371. spring: options.spring,
  95372. //supporting older version of Oimo
  95373. world: this.world
  95374. };
  95375. switch (impostorJoint.joint.type) {
  95376. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  95377. type = "jointBall";
  95378. break;
  95379. case BABYLON.PhysicsJoint.SpringJoint:
  95380. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  95381. var springData = jointData;
  95382. nativeJointData.min = springData.length || nativeJointData.min;
  95383. //Max should also be set, just make sure it is at least min
  95384. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  95385. case BABYLON.PhysicsJoint.DistanceJoint:
  95386. type = "jointDistance";
  95387. nativeJointData.max = jointData.maxDistance;
  95388. break;
  95389. case BABYLON.PhysicsJoint.PrismaticJoint:
  95390. type = "jointPrisme";
  95391. break;
  95392. case BABYLON.PhysicsJoint.SliderJoint:
  95393. type = "jointSlide";
  95394. break;
  95395. case BABYLON.PhysicsJoint.WheelJoint:
  95396. type = "jointWheel";
  95397. break;
  95398. case BABYLON.PhysicsJoint.HingeJoint:
  95399. default:
  95400. type = "jointHinge";
  95401. break;
  95402. }
  95403. nativeJointData.type = type;
  95404. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  95405. };
  95406. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  95407. //Bug in Oimo prevents us from disposing a joint in the playground
  95408. //joint.joint.physicsJoint.dispose();
  95409. //So we will bruteforce it!
  95410. try {
  95411. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  95412. }
  95413. catch (e) {
  95414. BABYLON.Tools.Warn(e);
  95415. }
  95416. };
  95417. OimoJSPlugin.prototype.isSupported = function () {
  95418. return this.BJSOIMO !== undefined;
  95419. };
  95420. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  95421. if (!impostor.physicsBody.sleeping) {
  95422. //TODO check that
  95423. /*if (impostor.physicsBody.shapes.next) {
  95424. var parentShape = this._getLastShape(impostor.physicsBody);
  95425. impostor.object.position.copyFrom(parentShape.position);
  95426. console.log(parentShape.position);
  95427. } else {*/
  95428. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  95429. //}
  95430. if (impostor.object.rotationQuaternion) {
  95431. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  95432. }
  95433. }
  95434. };
  95435. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  95436. var body = impostor.physicsBody;
  95437. body.position.copy(newPosition);
  95438. body.orientation.copy(newRotation);
  95439. body.syncShapes();
  95440. body.awake();
  95441. };
  95442. /*private _getLastShape(body: any): any {
  95443. var lastShape = body.shapes;
  95444. while (lastShape.next) {
  95445. lastShape = lastShape.next;
  95446. }
  95447. return lastShape;
  95448. }*/
  95449. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  95450. impostor.physicsBody.linearVelocity.copy(velocity);
  95451. };
  95452. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  95453. impostor.physicsBody.angularVelocity.copy(velocity);
  95454. };
  95455. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  95456. var v = impostor.physicsBody.linearVelocity;
  95457. if (!v) {
  95458. return null;
  95459. }
  95460. return new BABYLON.Vector3(v.x, v.y, v.z);
  95461. };
  95462. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  95463. var v = impostor.physicsBody.angularVelocity;
  95464. if (!v) {
  95465. return null;
  95466. }
  95467. return new BABYLON.Vector3(v.x, v.y, v.z);
  95468. };
  95469. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  95470. var staticBody = mass === 0;
  95471. //this will actually set the body's density and not its mass.
  95472. //But this is how oimo treats the mass variable.
  95473. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  95474. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  95475. };
  95476. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  95477. return impostor.physicsBody.shapes.density;
  95478. };
  95479. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  95480. return impostor.physicsBody.shapes.friction;
  95481. };
  95482. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  95483. impostor.physicsBody.shapes.friction = friction;
  95484. };
  95485. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  95486. return impostor.physicsBody.shapes.restitution;
  95487. };
  95488. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  95489. impostor.physicsBody.shapes.restitution = restitution;
  95490. };
  95491. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  95492. impostor.physicsBody.sleep();
  95493. };
  95494. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  95495. impostor.physicsBody.awake();
  95496. };
  95497. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  95498. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  95499. if (minDistance !== void 0) {
  95500. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  95501. }
  95502. };
  95503. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  95504. //TODO separate rotational and transational motors.
  95505. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  95506. if (motor) {
  95507. motor.setMotor(speed, maxForce);
  95508. }
  95509. };
  95510. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  95511. //TODO separate rotational and transational motors.
  95512. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  95513. if (motor) {
  95514. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  95515. }
  95516. };
  95517. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  95518. var body = impostor.physicsBody;
  95519. mesh.position.x = body.position.x;
  95520. mesh.position.y = body.position.y;
  95521. mesh.position.z = body.position.z;
  95522. if (mesh.rotationQuaternion) {
  95523. mesh.rotationQuaternion.x = body.orientation.x;
  95524. mesh.rotationQuaternion.y = body.orientation.y;
  95525. mesh.rotationQuaternion.z = body.orientation.z;
  95526. mesh.rotationQuaternion.w = body.orientation.s;
  95527. }
  95528. };
  95529. OimoJSPlugin.prototype.getRadius = function (impostor) {
  95530. return impostor.physicsBody.shapes.radius;
  95531. };
  95532. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  95533. var shape = impostor.physicsBody.shapes;
  95534. result.x = shape.halfWidth * 2;
  95535. result.y = shape.halfHeight * 2;
  95536. result.z = shape.halfDepth * 2;
  95537. };
  95538. OimoJSPlugin.prototype.dispose = function () {
  95539. this.world.clear();
  95540. };
  95541. return OimoJSPlugin;
  95542. }());
  95543. BABYLON.OimoJSPlugin = OimoJSPlugin;
  95544. })(BABYLON || (BABYLON = {}));
  95545. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  95546. var BABYLON;
  95547. (function (BABYLON) {
  95548. /**
  95549. * Gets the current physics engine
  95550. * @returns a IPhysicsEngine or null if none attached
  95551. */
  95552. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  95553. return this._physicsEngine;
  95554. };
  95555. /**
  95556. * Enables physics to the current scene
  95557. * @param gravity defines the scene's gravity for the physics engine
  95558. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  95559. * @return a boolean indicating if the physics engine was initialized
  95560. */
  95561. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  95562. if (gravity === void 0) { gravity = null; }
  95563. if (this._physicsEngine) {
  95564. return true;
  95565. }
  95566. // Register the component to the scene
  95567. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  95568. if (!component) {
  95569. component = new PhysicsEngineSceneComponent(this);
  95570. this._addComponent(component);
  95571. }
  95572. try {
  95573. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  95574. return true;
  95575. }
  95576. catch (e) {
  95577. BABYLON.Tools.Error(e.message);
  95578. return false;
  95579. }
  95580. };
  95581. /**
  95582. * Disables and disposes the physics engine associated with the scene
  95583. */
  95584. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  95585. if (!this._physicsEngine) {
  95586. return;
  95587. }
  95588. this._physicsEngine.dispose();
  95589. this._physicsEngine = null;
  95590. };
  95591. /**
  95592. * Gets a boolean indicating if there is an active physics engine
  95593. * @returns a boolean indicating if there is an active physics engine
  95594. */
  95595. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  95596. return this._physicsEngine !== undefined;
  95597. };
  95598. /**
  95599. * Deletes a physics compound impostor
  95600. * @param compound defines the compound to delete
  95601. */
  95602. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  95603. var mesh = compound.parts[0].mesh;
  95604. if (mesh.physicsImpostor) {
  95605. mesh.physicsImpostor.dispose( /*true*/);
  95606. mesh.physicsImpostor = null;
  95607. }
  95608. };
  95609. /** @hidden */
  95610. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  95611. if (this._physicsEngine) {
  95612. this.onBeforePhysicsObservable.notifyObservers(this);
  95613. this._physicsEngine._step(step / 1000);
  95614. this.onAfterPhysicsObservable.notifyObservers(this);
  95615. }
  95616. };
  95617. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  95618. get: function () {
  95619. return this._physicsImpostor;
  95620. },
  95621. set: function (value) {
  95622. var _this = this;
  95623. if (this._physicsImpostor === value) {
  95624. return;
  95625. }
  95626. if (this._disposePhysicsObserver) {
  95627. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  95628. }
  95629. this._physicsImpostor = value;
  95630. if (value) {
  95631. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  95632. // Physics
  95633. if (_this.physicsImpostor) {
  95634. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  95635. _this.physicsImpostor = null;
  95636. }
  95637. });
  95638. }
  95639. },
  95640. enumerable: true,
  95641. configurable: true
  95642. });
  95643. /**
  95644. * Gets the current physics impostor
  95645. * @see http://doc.babylonjs.com/features/physics_engine
  95646. * @returns a physics impostor or null
  95647. */
  95648. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  95649. return this.physicsImpostor;
  95650. };
  95651. /**
  95652. * Apply a physic impulse to the mesh
  95653. * @param force defines the force to apply
  95654. * @param contactPoint defines where to apply the force
  95655. * @returns the current mesh
  95656. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  95657. */
  95658. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  95659. if (!this.physicsImpostor) {
  95660. return this;
  95661. }
  95662. this.physicsImpostor.applyImpulse(force, contactPoint);
  95663. return this;
  95664. };
  95665. /**
  95666. * Creates a physic joint between two meshes
  95667. * @param otherMesh defines the other mesh to use
  95668. * @param pivot1 defines the pivot to use on this mesh
  95669. * @param pivot2 defines the pivot to use on the other mesh
  95670. * @param options defines additional options (can be plugin dependent)
  95671. * @returns the current mesh
  95672. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  95673. */
  95674. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  95675. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  95676. return this;
  95677. }
  95678. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  95679. mainPivot: pivot1,
  95680. connectedPivot: pivot2,
  95681. nativeParams: options
  95682. });
  95683. return this;
  95684. };
  95685. /**
  95686. * Defines the physics engine scene component responsible to manage a physics engine
  95687. */
  95688. var PhysicsEngineSceneComponent = /** @class */ (function () {
  95689. /**
  95690. * Creates a new instance of the component for the given scene
  95691. * @param scene Defines the scene to register the component in
  95692. */
  95693. function PhysicsEngineSceneComponent(scene) {
  95694. var _this = this;
  95695. /**
  95696. * The component name helpful to identify the component in the list of scene components.
  95697. */
  95698. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  95699. this.scene = scene;
  95700. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  95701. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  95702. // Replace the function used to get the deterministic frame time
  95703. this.scene.getDeterministicFrameTime = function () {
  95704. if (_this.scene._physicsEngine) {
  95705. return _this.scene._physicsEngine.getTimeStep() * 1000;
  95706. }
  95707. return 1000.0 / 60.0;
  95708. };
  95709. }
  95710. /**
  95711. * Registers the component in a given scene
  95712. */
  95713. PhysicsEngineSceneComponent.prototype.register = function () {
  95714. };
  95715. /**
  95716. * Rebuilds the elements related to this component in case of
  95717. * context lost for instance.
  95718. */
  95719. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  95720. // Nothing to do for this component
  95721. };
  95722. /**
  95723. * Disposes the component and the associated ressources
  95724. */
  95725. PhysicsEngineSceneComponent.prototype.dispose = function () {
  95726. this.scene.onBeforePhysicsObservable.clear();
  95727. this.scene.onAfterPhysicsObservable.clear();
  95728. if (this.scene._physicsEngine) {
  95729. this.scene.disablePhysicsEngine();
  95730. }
  95731. };
  95732. return PhysicsEngineSceneComponent;
  95733. }());
  95734. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  95735. })(BABYLON || (BABYLON = {}));
  95736. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  95737. var BABYLON;
  95738. (function (BABYLON) {
  95739. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  95740. // All values and structures referenced from:
  95741. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  95742. var DDS_MAGIC = 0x20534444;
  95743. var
  95744. //DDSD_CAPS = 0x1,
  95745. //DDSD_HEIGHT = 0x2,
  95746. //DDSD_WIDTH = 0x4,
  95747. //DDSD_PITCH = 0x8,
  95748. //DDSD_PIXELFORMAT = 0x1000,
  95749. DDSD_MIPMAPCOUNT = 0x20000;
  95750. //DDSD_LINEARSIZE = 0x80000,
  95751. //DDSD_DEPTH = 0x800000;
  95752. // var DDSCAPS_COMPLEX = 0x8,
  95753. // DDSCAPS_MIPMAP = 0x400000,
  95754. // DDSCAPS_TEXTURE = 0x1000;
  95755. var DDSCAPS2_CUBEMAP = 0x200;
  95756. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  95757. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  95758. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  95759. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  95760. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  95761. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  95762. // DDSCAPS2_VOLUME = 0x200000;
  95763. var
  95764. //DDPF_ALPHAPIXELS = 0x1,
  95765. //DDPF_ALPHA = 0x2,
  95766. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  95767. //DDPF_YUV = 0x200,
  95768. DDPF_LUMINANCE = 0x20000;
  95769. function FourCCToInt32(value) {
  95770. return value.charCodeAt(0) +
  95771. (value.charCodeAt(1) << 8) +
  95772. (value.charCodeAt(2) << 16) +
  95773. (value.charCodeAt(3) << 24);
  95774. }
  95775. function Int32ToFourCC(value) {
  95776. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  95777. }
  95778. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  95779. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  95780. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  95781. var FOURCC_DX10 = FourCCToInt32("DX10");
  95782. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  95783. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  95784. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  95785. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  95786. var headerLengthInt = 31; // The header length in 32 bit ints
  95787. // Offsets into the header array
  95788. var off_magic = 0;
  95789. var off_size = 1;
  95790. var off_flags = 2;
  95791. var off_height = 3;
  95792. var off_width = 4;
  95793. var off_mipmapCount = 7;
  95794. var off_pfFlags = 20;
  95795. var off_pfFourCC = 21;
  95796. var off_RGBbpp = 22;
  95797. var off_RMask = 23;
  95798. var off_GMask = 24;
  95799. var off_BMask = 25;
  95800. var off_AMask = 26;
  95801. // var off_caps1 = 27;
  95802. var off_caps2 = 28;
  95803. // var off_caps3 = 29;
  95804. // var off_caps4 = 30;
  95805. var off_dxgiFormat = 32;
  95806. ;
  95807. /**
  95808. * Class used to provide DDS decompression tools
  95809. */
  95810. var DDSTools = /** @class */ (function () {
  95811. function DDSTools() {
  95812. }
  95813. /**
  95814. * Gets DDS information from an array buffer
  95815. * @param arrayBuffer defines the array buffer to read data from
  95816. * @returns the DDS information
  95817. */
  95818. DDSTools.GetDDSInfo = function (arrayBuffer) {
  95819. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  95820. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  95821. var mipmapCount = 1;
  95822. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  95823. mipmapCount = Math.max(1, header[off_mipmapCount]);
  95824. }
  95825. var fourCC = header[off_pfFourCC];
  95826. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  95827. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95828. switch (fourCC) {
  95829. case FOURCC_D3DFMT_R16G16B16A16F:
  95830. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95831. break;
  95832. case FOURCC_D3DFMT_R32G32B32A32F:
  95833. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95834. break;
  95835. case FOURCC_DX10:
  95836. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  95837. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95838. break;
  95839. }
  95840. }
  95841. return {
  95842. width: header[off_width],
  95843. height: header[off_height],
  95844. mipmapCount: mipmapCount,
  95845. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  95846. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  95847. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  95848. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  95849. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  95850. dxgiFormat: dxgiFormat,
  95851. textureType: textureType
  95852. };
  95853. };
  95854. DDSTools._ToHalfFloat = function (value) {
  95855. if (!DDSTools._FloatView) {
  95856. DDSTools._FloatView = new Float32Array(1);
  95857. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  95858. }
  95859. DDSTools._FloatView[0] = value;
  95860. var x = DDSTools._Int32View[0];
  95861. var bits = (x >> 16) & 0x8000; /* Get the sign */
  95862. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  95863. var e = (x >> 23) & 0xff; /* Using int is faster here */
  95864. /* If zero, or denormal, or exponent underflows too much for a denormal
  95865. * half, return signed zero. */
  95866. if (e < 103) {
  95867. return bits;
  95868. }
  95869. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  95870. if (e > 142) {
  95871. bits |= 0x7c00;
  95872. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  95873. * not Inf, so make sure we set one mantissa bit too. */
  95874. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  95875. return bits;
  95876. }
  95877. /* If exponent underflows but not too much, return a denormal */
  95878. if (e < 113) {
  95879. m |= 0x0800;
  95880. /* Extra rounding may overflow and set mantissa to 0 and exponent
  95881. * to 1, which is OK. */
  95882. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  95883. return bits;
  95884. }
  95885. bits |= ((e - 112) << 10) | (m >> 1);
  95886. bits += m & 1;
  95887. return bits;
  95888. };
  95889. DDSTools._FromHalfFloat = function (value) {
  95890. var s = (value & 0x8000) >> 15;
  95891. var e = (value & 0x7C00) >> 10;
  95892. var f = value & 0x03FF;
  95893. if (e === 0) {
  95894. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  95895. }
  95896. else if (e == 0x1F) {
  95897. return f ? NaN : ((s ? -1 : 1) * Infinity);
  95898. }
  95899. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  95900. };
  95901. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95902. var destArray = new Float32Array(dataLength);
  95903. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95904. var index = 0;
  95905. for (var y = 0; y < height; y++) {
  95906. for (var x = 0; x < width; x++) {
  95907. var srcPos = (x + y * width) * 4;
  95908. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  95909. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  95910. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  95911. if (DDSTools.StoreLODInAlphaChannel) {
  95912. destArray[index + 3] = lod;
  95913. }
  95914. else {
  95915. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  95916. }
  95917. index += 4;
  95918. }
  95919. }
  95920. return destArray;
  95921. };
  95922. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95923. if (DDSTools.StoreLODInAlphaChannel) {
  95924. var destArray = new Uint16Array(dataLength);
  95925. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95926. var index = 0;
  95927. for (var y = 0; y < height; y++) {
  95928. for (var x = 0; x < width; x++) {
  95929. var srcPos = (x + y * width) * 4;
  95930. destArray[index] = srcData[srcPos];
  95931. destArray[index + 1] = srcData[srcPos + 1];
  95932. destArray[index + 2] = srcData[srcPos + 2];
  95933. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  95934. index += 4;
  95935. }
  95936. }
  95937. return destArray;
  95938. }
  95939. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  95940. };
  95941. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95942. if (DDSTools.StoreLODInAlphaChannel) {
  95943. var destArray = new Float32Array(dataLength);
  95944. var srcData = new Float32Array(arrayBuffer, dataOffset);
  95945. var index = 0;
  95946. for (var y = 0; y < height; y++) {
  95947. for (var x = 0; x < width; x++) {
  95948. var srcPos = (x + y * width) * 4;
  95949. destArray[index] = srcData[srcPos];
  95950. destArray[index + 1] = srcData[srcPos + 1];
  95951. destArray[index + 2] = srcData[srcPos + 2];
  95952. destArray[index + 3] = lod;
  95953. index += 4;
  95954. }
  95955. }
  95956. return destArray;
  95957. }
  95958. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  95959. };
  95960. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95961. var destArray = new Uint8Array(dataLength);
  95962. var srcData = new Float32Array(arrayBuffer, dataOffset);
  95963. var index = 0;
  95964. for (var y = 0; y < height; y++) {
  95965. for (var x = 0; x < width; x++) {
  95966. var srcPos = (x + y * width) * 4;
  95967. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  95968. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  95969. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  95970. if (DDSTools.StoreLODInAlphaChannel) {
  95971. destArray[index + 3] = lod;
  95972. }
  95973. else {
  95974. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  95975. }
  95976. index += 4;
  95977. }
  95978. }
  95979. return destArray;
  95980. };
  95981. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95982. var destArray = new Uint8Array(dataLength);
  95983. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95984. var index = 0;
  95985. for (var y = 0; y < height; y++) {
  95986. for (var x = 0; x < width; x++) {
  95987. var srcPos = (x + y * width) * 4;
  95988. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  95989. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  95990. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  95991. if (DDSTools.StoreLODInAlphaChannel) {
  95992. destArray[index + 3] = lod;
  95993. }
  95994. else {
  95995. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  95996. }
  95997. index += 4;
  95998. }
  95999. }
  96000. return destArray;
  96001. };
  96002. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  96003. var byteArray = new Uint8Array(dataLength);
  96004. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  96005. var index = 0;
  96006. for (var y = 0; y < height; y++) {
  96007. for (var x = 0; x < width; x++) {
  96008. var srcPos = (x + y * width) * 4;
  96009. byteArray[index] = srcData[srcPos + rOffset];
  96010. byteArray[index + 1] = srcData[srcPos + gOffset];
  96011. byteArray[index + 2] = srcData[srcPos + bOffset];
  96012. byteArray[index + 3] = srcData[srcPos + aOffset];
  96013. index += 4;
  96014. }
  96015. }
  96016. return byteArray;
  96017. };
  96018. DDSTools._ExtractLongWordOrder = function (value) {
  96019. if (value === 0 || value === 255 || value === -16777216) {
  96020. return 0;
  96021. }
  96022. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  96023. };
  96024. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  96025. var byteArray = new Uint8Array(dataLength);
  96026. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  96027. var index = 0;
  96028. for (var y = 0; y < height; y++) {
  96029. for (var x = 0; x < width; x++) {
  96030. var srcPos = (x + y * width) * 3;
  96031. byteArray[index] = srcData[srcPos + rOffset];
  96032. byteArray[index + 1] = srcData[srcPos + gOffset];
  96033. byteArray[index + 2] = srcData[srcPos + bOffset];
  96034. index += 3;
  96035. }
  96036. }
  96037. return byteArray;
  96038. };
  96039. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  96040. var byteArray = new Uint8Array(dataLength);
  96041. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  96042. var index = 0;
  96043. for (var y = 0; y < height; y++) {
  96044. for (var x = 0; x < width; x++) {
  96045. var srcPos = (x + y * width);
  96046. byteArray[index] = srcData[srcPos];
  96047. index++;
  96048. }
  96049. }
  96050. return byteArray;
  96051. };
  96052. /**
  96053. * Uploads DDS Levels to a Babylon Texture
  96054. * @hidden
  96055. */
  96056. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  96057. if (lodIndex === void 0) { lodIndex = -1; }
  96058. var sphericalPolynomialFaces = null;
  96059. if (info.sphericalPolynomial) {
  96060. sphericalPolynomialFaces = new Array();
  96061. }
  96062. var ext = engine.getCaps().s3tc;
  96063. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  96064. var fourCC, width, height, dataLength = 0, dataOffset;
  96065. var byteArray, mipmapCount, mip;
  96066. var internalCompressedFormat = 0;
  96067. var blockBytes = 1;
  96068. if (header[off_magic] !== DDS_MAGIC) {
  96069. BABYLON.Tools.Error("Invalid magic number in DDS header");
  96070. return;
  96071. }
  96072. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  96073. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  96074. return;
  96075. }
  96076. if (info.isCompressed && !ext) {
  96077. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  96078. return;
  96079. }
  96080. var bpp = header[off_RGBbpp];
  96081. dataOffset = header[off_size] + 4;
  96082. var computeFormats = false;
  96083. if (info.isFourCC) {
  96084. fourCC = header[off_pfFourCC];
  96085. switch (fourCC) {
  96086. case FOURCC_DXT1:
  96087. blockBytes = 8;
  96088. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  96089. break;
  96090. case FOURCC_DXT3:
  96091. blockBytes = 16;
  96092. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  96093. break;
  96094. case FOURCC_DXT5:
  96095. blockBytes = 16;
  96096. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  96097. break;
  96098. case FOURCC_D3DFMT_R16G16B16A16F:
  96099. computeFormats = true;
  96100. break;
  96101. case FOURCC_D3DFMT_R32G32B32A32F:
  96102. computeFormats = true;
  96103. break;
  96104. case FOURCC_DX10:
  96105. // There is an additionnal header so dataOffset need to be changed
  96106. dataOffset += 5 * 4; // 5 uints
  96107. var supported = false;
  96108. switch (info.dxgiFormat) {
  96109. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  96110. computeFormats = true;
  96111. supported = true;
  96112. break;
  96113. case DXGI_FORMAT_B8G8R8X8_UNORM:
  96114. info.isRGB = true;
  96115. info.isFourCC = false;
  96116. bpp = 32;
  96117. supported = true;
  96118. break;
  96119. }
  96120. if (supported) {
  96121. break;
  96122. }
  96123. default:
  96124. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  96125. return;
  96126. }
  96127. }
  96128. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  96129. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  96130. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  96131. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  96132. if (computeFormats) {
  96133. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  96134. }
  96135. mipmapCount = 1;
  96136. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  96137. mipmapCount = Math.max(1, header[off_mipmapCount]);
  96138. }
  96139. for (var face = 0; face < faces; face++) {
  96140. width = header[off_width];
  96141. height = header[off_height];
  96142. for (mip = 0; mip < mipmapCount; ++mip) {
  96143. if (lodIndex === -1 || lodIndex === mip) {
  96144. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  96145. var i = (lodIndex === -1) ? mip : 0;
  96146. if (!info.isCompressed && info.isFourCC) {
  96147. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  96148. dataLength = width * height * 4;
  96149. var floatArray = null;
  96150. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  96151. if (bpp === 128) {
  96152. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96153. if (sphericalPolynomialFaces && i == 0) {
  96154. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  96155. }
  96156. }
  96157. else if (bpp === 64) {
  96158. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96159. if (sphericalPolynomialFaces && i == 0) {
  96160. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  96161. }
  96162. }
  96163. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96164. }
  96165. else {
  96166. if (bpp === 128) {
  96167. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  96168. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96169. if (sphericalPolynomialFaces && i == 0) {
  96170. sphericalPolynomialFaces.push(floatArray);
  96171. }
  96172. }
  96173. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  96174. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  96175. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96176. if (sphericalPolynomialFaces && i == 0) {
  96177. sphericalPolynomialFaces.push(floatArray);
  96178. }
  96179. }
  96180. else { // 64
  96181. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96182. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96183. if (sphericalPolynomialFaces && i == 0) {
  96184. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  96185. }
  96186. }
  96187. }
  96188. if (floatArray) {
  96189. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  96190. }
  96191. }
  96192. else if (info.isRGB) {
  96193. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96194. if (bpp === 24) {
  96195. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  96196. dataLength = width * height * 3;
  96197. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  96198. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  96199. }
  96200. else { // 32
  96201. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  96202. dataLength = width * height * 4;
  96203. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  96204. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  96205. }
  96206. }
  96207. else if (info.isLuminance) {
  96208. var unpackAlignment = engine._getUnpackAlignement();
  96209. var unpaddedRowSize = width;
  96210. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  96211. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  96212. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  96213. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  96214. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96215. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  96216. }
  96217. else {
  96218. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  96219. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  96220. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96221. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  96222. }
  96223. }
  96224. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  96225. width *= 0.5;
  96226. height *= 0.5;
  96227. width = Math.max(1.0, width);
  96228. height = Math.max(1.0, height);
  96229. }
  96230. if (currentFace !== undefined) {
  96231. // Loading a single face
  96232. break;
  96233. }
  96234. }
  96235. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  96236. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  96237. size: header[off_width],
  96238. right: sphericalPolynomialFaces[0],
  96239. left: sphericalPolynomialFaces[1],
  96240. up: sphericalPolynomialFaces[2],
  96241. down: sphericalPolynomialFaces[3],
  96242. front: sphericalPolynomialFaces[4],
  96243. back: sphericalPolynomialFaces[5],
  96244. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  96245. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  96246. gammaSpace: false,
  96247. });
  96248. }
  96249. else {
  96250. info.sphericalPolynomial = undefined;
  96251. }
  96252. };
  96253. /**
  96254. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  96255. */
  96256. DDSTools.StoreLODInAlphaChannel = false;
  96257. return DDSTools;
  96258. }());
  96259. BABYLON.DDSTools = DDSTools;
  96260. })(BABYLON || (BABYLON = {}));
  96261. //# sourceMappingURL=babylon.dds.js.map
  96262. var BABYLON;
  96263. (function (BABYLON) {
  96264. /**
  96265. * Implementation of the DDS Texture Loader.
  96266. */
  96267. var DDSTextureLoader = /** @class */ (function () {
  96268. function DDSTextureLoader() {
  96269. /**
  96270. * Defines wether the loader supports cascade loading the different faces.
  96271. */
  96272. this.supportCascades = true;
  96273. }
  96274. /**
  96275. * This returns if the loader support the current file information.
  96276. * @param extension defines the file extension of the file being loaded
  96277. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96278. * @param fallback defines the fallback internal texture if any
  96279. * @param isBase64 defines whether the texture is encoded as a base64
  96280. * @param isBuffer defines whether the texture data are stored as a buffer
  96281. * @returns true if the loader can load the specified file
  96282. */
  96283. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96284. return extension.indexOf(".dds") === 0;
  96285. };
  96286. /**
  96287. * Transform the url before loading if required.
  96288. * @param rootUrl the url of the texture
  96289. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96290. * @returns the transformed texture
  96291. */
  96292. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96293. return rootUrl;
  96294. };
  96295. /**
  96296. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96297. * @param rootUrl the url of the texture
  96298. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96299. * @returns the fallback texture
  96300. */
  96301. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96302. return null;
  96303. };
  96304. /**
  96305. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96306. * @param data contains the texture data
  96307. * @param texture defines the BabylonJS internal texture
  96308. * @param createPolynomials will be true if polynomials have been requested
  96309. * @param onLoad defines the callback to trigger once the texture is ready
  96310. * @param onError defines the callback to trigger in case of error
  96311. */
  96312. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  96313. var engine = texture.getEngine();
  96314. var info;
  96315. var loadMipmap = false;
  96316. if (Array.isArray(imgs)) {
  96317. for (var index = 0; index < imgs.length; index++) {
  96318. var data_1 = imgs[index];
  96319. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  96320. texture.width = info.width;
  96321. texture.height = info.height;
  96322. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  96323. engine._unpackFlipY(info.isCompressed);
  96324. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  96325. if (!info.isFourCC && info.mipmapCount === 1) {
  96326. engine.generateMipMapsForCubemap(texture);
  96327. }
  96328. }
  96329. }
  96330. else {
  96331. var data = imgs;
  96332. info = BABYLON.DDSTools.GetDDSInfo(data);
  96333. texture.width = info.width;
  96334. texture.height = info.height;
  96335. if (createPolynomials) {
  96336. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  96337. }
  96338. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  96339. engine._unpackFlipY(info.isCompressed);
  96340. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  96341. if (!info.isFourCC && info.mipmapCount === 1) {
  96342. engine.generateMipMapsForCubemap(texture);
  96343. }
  96344. }
  96345. engine._setCubeMapTextureParams(loadMipmap);
  96346. texture.isReady = true;
  96347. if (onLoad) {
  96348. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  96349. }
  96350. };
  96351. /**
  96352. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96353. * @param data contains the texture data
  96354. * @param texture defines the BabylonJS internal texture
  96355. * @param callback defines the method to call once ready to upload
  96356. */
  96357. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  96358. var info = BABYLON.DDSTools.GetDDSInfo(data);
  96359. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  96360. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  96361. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  96362. });
  96363. };
  96364. return DDSTextureLoader;
  96365. }());
  96366. // Register the loader.
  96367. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  96368. })(BABYLON || (BABYLON = {}));
  96369. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  96370. var BABYLON;
  96371. (function (BABYLON) {
  96372. /**
  96373. * Based on jsTGALoader - Javascript loader for TGA file
  96374. * By Vincent Thibault
  96375. * @see http://blog.robrowser.com/javascript-tga-loader.html
  96376. */
  96377. var TGATools = /** @class */ (function () {
  96378. function TGATools() {
  96379. }
  96380. /**
  96381. * Gets the header of a TGA file
  96382. * @param data defines the TGA data
  96383. * @returns the header
  96384. */
  96385. TGATools.GetTGAHeader = function (data) {
  96386. var offset = 0;
  96387. var header = {
  96388. id_length: data[offset++],
  96389. colormap_type: data[offset++],
  96390. image_type: data[offset++],
  96391. colormap_index: data[offset++] | data[offset++] << 8,
  96392. colormap_length: data[offset++] | data[offset++] << 8,
  96393. colormap_size: data[offset++],
  96394. origin: [
  96395. data[offset++] | data[offset++] << 8,
  96396. data[offset++] | data[offset++] << 8
  96397. ],
  96398. width: data[offset++] | data[offset++] << 8,
  96399. height: data[offset++] | data[offset++] << 8,
  96400. pixel_size: data[offset++],
  96401. flags: data[offset++]
  96402. };
  96403. return header;
  96404. };
  96405. /**
  96406. * Uploads TGA content to a Babylon Texture
  96407. * @hidden
  96408. */
  96409. TGATools.UploadContent = function (texture, data) {
  96410. // Not enough data to contain header ?
  96411. if (data.length < 19) {
  96412. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  96413. return;
  96414. }
  96415. // Read Header
  96416. var offset = 18;
  96417. var header = TGATools.GetTGAHeader(data);
  96418. // Assume it's a valid Targa file.
  96419. if (header.id_length + offset > data.length) {
  96420. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  96421. return;
  96422. }
  96423. // Skip not needed data
  96424. offset += header.id_length;
  96425. var use_rle = false;
  96426. var use_pal = false;
  96427. var use_grey = false;
  96428. // Get some informations.
  96429. switch (header.image_type) {
  96430. case TGATools._TYPE_RLE_INDEXED:
  96431. use_rle = true;
  96432. case TGATools._TYPE_INDEXED:
  96433. use_pal = true;
  96434. break;
  96435. case TGATools._TYPE_RLE_RGB:
  96436. use_rle = true;
  96437. case TGATools._TYPE_RGB:
  96438. // use_rgb = true;
  96439. break;
  96440. case TGATools._TYPE_RLE_GREY:
  96441. use_rle = true;
  96442. case TGATools._TYPE_GREY:
  96443. use_grey = true;
  96444. break;
  96445. }
  96446. var pixel_data;
  96447. // var numAlphaBits = header.flags & 0xf;
  96448. var pixel_size = header.pixel_size >> 3;
  96449. var pixel_total = header.width * header.height * pixel_size;
  96450. // Read palettes
  96451. var palettes;
  96452. if (use_pal) {
  96453. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  96454. }
  96455. // Read LRE
  96456. if (use_rle) {
  96457. pixel_data = new Uint8Array(pixel_total);
  96458. var c, count, i;
  96459. var localOffset = 0;
  96460. var pixels = new Uint8Array(pixel_size);
  96461. while (offset < pixel_total && localOffset < pixel_total) {
  96462. c = data[offset++];
  96463. count = (c & 0x7f) + 1;
  96464. // RLE pixels
  96465. if (c & 0x80) {
  96466. // Bind pixel tmp array
  96467. for (i = 0; i < pixel_size; ++i) {
  96468. pixels[i] = data[offset++];
  96469. }
  96470. // Copy pixel array
  96471. for (i = 0; i < count; ++i) {
  96472. pixel_data.set(pixels, localOffset + i * pixel_size);
  96473. }
  96474. localOffset += pixel_size * count;
  96475. }
  96476. // Raw pixels
  96477. else {
  96478. count *= pixel_size;
  96479. for (i = 0; i < count; ++i) {
  96480. pixel_data[localOffset + i] = data[offset++];
  96481. }
  96482. localOffset += count;
  96483. }
  96484. }
  96485. }
  96486. // RAW Pixels
  96487. else {
  96488. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  96489. }
  96490. // Load to texture
  96491. var x_start, y_start, x_step, y_step, y_end, x_end;
  96492. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  96493. default:
  96494. case TGATools._ORIGIN_UL:
  96495. x_start = 0;
  96496. x_step = 1;
  96497. x_end = header.width;
  96498. y_start = 0;
  96499. y_step = 1;
  96500. y_end = header.height;
  96501. break;
  96502. case TGATools._ORIGIN_BL:
  96503. x_start = 0;
  96504. x_step = 1;
  96505. x_end = header.width;
  96506. y_start = header.height - 1;
  96507. y_step = -1;
  96508. y_end = -1;
  96509. break;
  96510. case TGATools._ORIGIN_UR:
  96511. x_start = header.width - 1;
  96512. x_step = -1;
  96513. x_end = -1;
  96514. y_start = 0;
  96515. y_step = 1;
  96516. y_end = header.height;
  96517. break;
  96518. case TGATools._ORIGIN_BR:
  96519. x_start = header.width - 1;
  96520. x_step = -1;
  96521. x_end = -1;
  96522. y_start = header.height - 1;
  96523. y_step = -1;
  96524. y_end = -1;
  96525. break;
  96526. }
  96527. // Load the specify method
  96528. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  96529. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  96530. var engine = texture.getEngine();
  96531. engine._uploadDataToTextureDirectly(texture, imageData);
  96532. };
  96533. /** @hidden */
  96534. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96535. var image = pixel_data, colormap = palettes;
  96536. var width = header.width, height = header.height;
  96537. var color, i = 0, x, y;
  96538. var imageData = new Uint8Array(width * height * 4);
  96539. for (y = y_start; y !== y_end; y += y_step) {
  96540. for (x = x_start; x !== x_end; x += x_step, i++) {
  96541. color = image[i];
  96542. imageData[(x + width * y) * 4 + 3] = 255;
  96543. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  96544. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  96545. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  96546. }
  96547. }
  96548. return imageData;
  96549. };
  96550. /** @hidden */
  96551. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96552. var image = pixel_data;
  96553. var width = header.width, height = header.height;
  96554. var color, i = 0, x, y;
  96555. var imageData = new Uint8Array(width * height * 4);
  96556. for (y = y_start; y !== y_end; y += y_step) {
  96557. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  96558. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  96559. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  96560. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  96561. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  96562. imageData[(x + width * y) * 4 + 0] = r;
  96563. imageData[(x + width * y) * 4 + 1] = g;
  96564. imageData[(x + width * y) * 4 + 2] = b;
  96565. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  96566. }
  96567. }
  96568. return imageData;
  96569. };
  96570. /** @hidden */
  96571. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96572. var image = pixel_data;
  96573. var width = header.width, height = header.height;
  96574. var i = 0, x, y;
  96575. var imageData = new Uint8Array(width * height * 4);
  96576. for (y = y_start; y !== y_end; y += y_step) {
  96577. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  96578. imageData[(x + width * y) * 4 + 3] = 255;
  96579. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  96580. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  96581. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  96582. }
  96583. }
  96584. return imageData;
  96585. };
  96586. /** @hidden */
  96587. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96588. var image = pixel_data;
  96589. var width = header.width, height = header.height;
  96590. var i = 0, x, y;
  96591. var imageData = new Uint8Array(width * height * 4);
  96592. for (y = y_start; y !== y_end; y += y_step) {
  96593. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  96594. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  96595. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  96596. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  96597. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  96598. }
  96599. }
  96600. return imageData;
  96601. };
  96602. /** @hidden */
  96603. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96604. var image = pixel_data;
  96605. var width = header.width, height = header.height;
  96606. var color, i = 0, x, y;
  96607. var imageData = new Uint8Array(width * height * 4);
  96608. for (y = y_start; y !== y_end; y += y_step) {
  96609. for (x = x_start; x !== x_end; x += x_step, i++) {
  96610. color = image[i];
  96611. imageData[(x + width * y) * 4 + 0] = color;
  96612. imageData[(x + width * y) * 4 + 1] = color;
  96613. imageData[(x + width * y) * 4 + 2] = color;
  96614. imageData[(x + width * y) * 4 + 3] = 255;
  96615. }
  96616. }
  96617. return imageData;
  96618. };
  96619. /** @hidden */
  96620. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96621. var image = pixel_data;
  96622. var width = header.width, height = header.height;
  96623. var i = 0, x, y;
  96624. var imageData = new Uint8Array(width * height * 4);
  96625. for (y = y_start; y !== y_end; y += y_step) {
  96626. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  96627. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  96628. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  96629. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  96630. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  96631. }
  96632. }
  96633. return imageData;
  96634. };
  96635. //private static _TYPE_NO_DATA = 0;
  96636. TGATools._TYPE_INDEXED = 1;
  96637. TGATools._TYPE_RGB = 2;
  96638. TGATools._TYPE_GREY = 3;
  96639. TGATools._TYPE_RLE_INDEXED = 9;
  96640. TGATools._TYPE_RLE_RGB = 10;
  96641. TGATools._TYPE_RLE_GREY = 11;
  96642. TGATools._ORIGIN_MASK = 0x30;
  96643. TGATools._ORIGIN_SHIFT = 0x04;
  96644. TGATools._ORIGIN_BL = 0x00;
  96645. TGATools._ORIGIN_BR = 0x01;
  96646. TGATools._ORIGIN_UL = 0x02;
  96647. TGATools._ORIGIN_UR = 0x03;
  96648. return TGATools;
  96649. }());
  96650. BABYLON.TGATools = TGATools;
  96651. })(BABYLON || (BABYLON = {}));
  96652. //# sourceMappingURL=babylon.tga.js.map
  96653. var BABYLON;
  96654. (function (BABYLON) {
  96655. /**
  96656. * Implementation of the TGA Texture Loader.
  96657. */
  96658. var TGATextureLoader = /** @class */ (function () {
  96659. function TGATextureLoader() {
  96660. /**
  96661. * Defines wether the loader supports cascade loading the different faces.
  96662. */
  96663. this.supportCascades = false;
  96664. }
  96665. /**
  96666. * This returns if the loader support the current file information.
  96667. * @param extension defines the file extension of the file being loaded
  96668. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96669. * @param fallback defines the fallback internal texture if any
  96670. * @param isBase64 defines whether the texture is encoded as a base64
  96671. * @param isBuffer defines whether the texture data are stored as a buffer
  96672. * @returns true if the loader can load the specified file
  96673. */
  96674. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96675. return extension.indexOf(".tga") === 0;
  96676. };
  96677. /**
  96678. * Transform the url before loading if required.
  96679. * @param rootUrl the url of the texture
  96680. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96681. * @returns the transformed texture
  96682. */
  96683. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96684. return rootUrl;
  96685. };
  96686. /**
  96687. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96688. * @param rootUrl the url of the texture
  96689. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96690. * @returns the fallback texture
  96691. */
  96692. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96693. return null;
  96694. };
  96695. /**
  96696. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96697. * @param data contains the texture data
  96698. * @param texture defines the BabylonJS internal texture
  96699. * @param createPolynomials will be true if polynomials have been requested
  96700. * @param onLoad defines the callback to trigger once the texture is ready
  96701. * @param onError defines the callback to trigger in case of error
  96702. */
  96703. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  96704. throw ".env not supported in Cube.";
  96705. };
  96706. /**
  96707. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96708. * @param data contains the texture data
  96709. * @param texture defines the BabylonJS internal texture
  96710. * @param callback defines the method to call once ready to upload
  96711. */
  96712. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  96713. var uintData = new Uint8Array(data);
  96714. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  96715. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  96716. BABYLON.TGATools.UploadContent(texture, uintData);
  96717. });
  96718. };
  96719. return TGATextureLoader;
  96720. }());
  96721. // Register the loader.
  96722. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  96723. })(BABYLON || (BABYLON = {}));
  96724. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  96725. var BABYLON;
  96726. (function (BABYLON) {
  96727. /**
  96728. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  96729. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  96730. */
  96731. var KhronosTextureContainer = /** @class */ (function () {
  96732. /**
  96733. * Creates a new KhronosTextureContainer
  96734. * @param arrayBuffer contents of the KTX container file
  96735. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  96736. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  96737. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  96738. */
  96739. function KhronosTextureContainer(
  96740. /** contents of the KTX container file */
  96741. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  96742. this.arrayBuffer = arrayBuffer;
  96743. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  96744. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  96745. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  96746. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  96747. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  96748. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  96749. BABYLON.Tools.Error("texture missing KTX identifier");
  96750. return;
  96751. }
  96752. // load the reset of the header in native 32 bit int
  96753. var header = new Int32Array(this.arrayBuffer, 12, 13);
  96754. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  96755. var oppositeEndianess = header[0] === 0x01020304;
  96756. // read all the header elements in order they exist in the file, without modification (sans endainness)
  96757. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  96758. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  96759. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  96760. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  96761. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  96762. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  96763. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  96764. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  96765. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  96766. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  96767. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  96768. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  96769. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  96770. if (this.glType !== 0) {
  96771. BABYLON.Tools.Error("only compressed formats currently supported");
  96772. return;
  96773. }
  96774. else {
  96775. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  96776. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  96777. }
  96778. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  96779. BABYLON.Tools.Error("only 2D textures currently supported");
  96780. return;
  96781. }
  96782. if (this.numberOfArrayElements !== 0) {
  96783. BABYLON.Tools.Error("texture arrays not currently supported");
  96784. return;
  96785. }
  96786. if (this.numberOfFaces !== facesExpected) {
  96787. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  96788. return;
  96789. }
  96790. // we now have a completely validated file, so could use existence of loadType as success
  96791. // would need to make this more elaborate & adjust checks above to support more than one load type
  96792. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  96793. }
  96794. //
  96795. /**
  96796. * Revert the endianness of a value.
  96797. * Not as fast hardware based, but will probably never need to use
  96798. * @param val defines the value to convert
  96799. * @returns the new value
  96800. */
  96801. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  96802. return ((val & 0xFF) << 24)
  96803. | ((val & 0xFF00) << 8)
  96804. | ((val >> 8) & 0xFF00)
  96805. | ((val >> 24) & 0xFF);
  96806. };
  96807. /**
  96808. * Uploads KTX content to a Babylon Texture.
  96809. * It is assumed that the texture has already been created & is currently bound
  96810. * @hidden
  96811. */
  96812. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  96813. switch (this.loadType) {
  96814. case KhronosTextureContainer.COMPRESSED_2D:
  96815. this._upload2DCompressedLevels(texture, loadMipmaps);
  96816. break;
  96817. case KhronosTextureContainer.TEX_2D:
  96818. case KhronosTextureContainer.COMPRESSED_3D:
  96819. case KhronosTextureContainer.TEX_3D:
  96820. }
  96821. };
  96822. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  96823. // initialize width & height for level 1
  96824. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  96825. var width = this.pixelWidth;
  96826. var height = this.pixelHeight;
  96827. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  96828. for (var level = 0; level < mipmapCount; level++) {
  96829. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  96830. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  96831. for (var face = 0; face < this.numberOfFaces; face++) {
  96832. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  96833. var engine = texture.getEngine();
  96834. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  96835. dataOffset += imageSize; // add size of the image for the next face/mipmap
  96836. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  96837. }
  96838. width = Math.max(1.0, width * 0.5);
  96839. height = Math.max(1.0, height * 0.5);
  96840. }
  96841. };
  96842. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  96843. // load types
  96844. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  96845. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  96846. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  96847. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  96848. return KhronosTextureContainer;
  96849. }());
  96850. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  96851. })(BABYLON || (BABYLON = {}));
  96852. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  96853. var BABYLON;
  96854. (function (BABYLON) {
  96855. /**
  96856. * Implementation of the KTX Texture Loader.
  96857. */
  96858. var KTXTextureLoader = /** @class */ (function () {
  96859. function KTXTextureLoader() {
  96860. /**
  96861. * Defines wether the loader supports cascade loading the different faces.
  96862. */
  96863. this.supportCascades = false;
  96864. }
  96865. /**
  96866. * This returns if the loader support the current file information.
  96867. * @param extension defines the file extension of the file being loaded
  96868. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96869. * @param fallback defines the fallback internal texture if any
  96870. * @param isBase64 defines whether the texture is encoded as a base64
  96871. * @param isBuffer defines whether the texture data are stored as a buffer
  96872. * @returns true if the loader can load the specified file
  96873. */
  96874. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96875. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  96876. return true;
  96877. }
  96878. return false;
  96879. };
  96880. /**
  96881. * Transform the url before loading if required.
  96882. * @param rootUrl the url of the texture
  96883. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96884. * @returns the transformed texture
  96885. */
  96886. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96887. var lastDot = rootUrl.lastIndexOf('.');
  96888. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  96889. };
  96890. /**
  96891. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96892. * @param rootUrl the url of the texture
  96893. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96894. * @returns the fallback texture
  96895. */
  96896. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96897. // remove the format appended to the rootUrl in the original createCubeTexture call.
  96898. var exp = new RegExp("" + textureFormatInUse + "$");
  96899. return rootUrl.replace(exp, "");
  96900. };
  96901. /**
  96902. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96903. * @param data contains the texture data
  96904. * @param texture defines the BabylonJS internal texture
  96905. * @param createPolynomials will be true if polynomials have been requested
  96906. * @param onLoad defines the callback to trigger once the texture is ready
  96907. * @param onError defines the callback to trigger in case of error
  96908. */
  96909. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  96910. if (Array.isArray(data)) {
  96911. return;
  96912. }
  96913. var engine = texture.getEngine();
  96914. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  96915. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  96916. engine._unpackFlipY(true);
  96917. ktx.uploadLevels(texture, texture.generateMipMaps);
  96918. texture.width = ktx.pixelWidth;
  96919. texture.height = ktx.pixelHeight;
  96920. engine._setCubeMapTextureParams(loadMipmap);
  96921. texture.isReady = true;
  96922. };
  96923. /**
  96924. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96925. * @param data contains the texture data
  96926. * @param texture defines the BabylonJS internal texture
  96927. * @param callback defines the method to call once ready to upload
  96928. */
  96929. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  96930. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  96931. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  96932. ktx.uploadLevels(texture, texture.generateMipMaps);
  96933. });
  96934. };
  96935. return KTXTextureLoader;
  96936. }());
  96937. // Register the loader.
  96938. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  96939. })(BABYLON || (BABYLON = {}));
  96940. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  96941. var BABYLON;
  96942. (function (BABYLON) {
  96943. /**
  96944. * Sets of helpers addressing the serialization and deserialization of environment texture
  96945. * stored in a BabylonJS env file.
  96946. * Those files are usually stored as .env files.
  96947. */
  96948. var EnvironmentTextureTools = /** @class */ (function () {
  96949. function EnvironmentTextureTools() {
  96950. }
  96951. /**
  96952. * Gets the environment info from an env file.
  96953. * @param data The array buffer containing the .env bytes.
  96954. * @returns the environment file info (the json header) if successfully parsed.
  96955. */
  96956. EnvironmentTextureTools.GetEnvInfo = function (data) {
  96957. var dataView = new DataView(data);
  96958. var pos = 0;
  96959. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  96960. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  96961. BABYLON.Tools.Error('Not a babylon environment map');
  96962. return null;
  96963. }
  96964. }
  96965. // Read json manifest - collect characters up to null terminator
  96966. var manifestString = '';
  96967. var charCode = 0x00;
  96968. while ((charCode = dataView.getUint8(pos++))) {
  96969. manifestString += String.fromCharCode(charCode);
  96970. }
  96971. var manifest = JSON.parse(manifestString);
  96972. if (manifest.specular) {
  96973. // Extend the header with the position of the payload.
  96974. manifest.specular.specularDataPosition = pos;
  96975. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  96976. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  96977. }
  96978. return manifest;
  96979. };
  96980. /**
  96981. * Creates an environment texture from a loaded cube texture.
  96982. * @param texture defines the cube texture to convert in env file
  96983. * @return a promise containing the environment data if succesfull.
  96984. */
  96985. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  96986. var _this = this;
  96987. var internalTexture = texture.getInternalTexture();
  96988. if (!internalTexture) {
  96989. return Promise.reject("The cube texture is invalid.");
  96990. }
  96991. if (!texture._prefiltered) {
  96992. return Promise.reject("The cube texture is invalid (not prefiltered).");
  96993. }
  96994. var engine = internalTexture.getEngine();
  96995. if (engine && engine.premultipliedAlpha) {
  96996. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  96997. }
  96998. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  96999. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  97000. }
  97001. var canvas = engine.getRenderingCanvas();
  97002. if (!canvas) {
  97003. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  97004. }
  97005. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97006. if (!engine.getCaps().textureFloatRender) {
  97007. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97008. if (!engine.getCaps().textureHalfFloatRender) {
  97009. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  97010. }
  97011. }
  97012. var cubeWidth = internalTexture.width;
  97013. var hostingScene = new BABYLON.Scene(engine);
  97014. var specularTextures = {};
  97015. var promises = [];
  97016. // Read and collect all mipmaps data from the cube.
  97017. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  97018. mipmapsCount = Math.round(mipmapsCount);
  97019. var _loop_1 = function (i) {
  97020. var faceWidth = Math.pow(2, mipmapsCount - i);
  97021. var _loop_2 = function (face) {
  97022. var data = texture.readPixels(face, i);
  97023. // Creates a temp texture with the face data.
  97024. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  97025. // And rgbdEncode them.
  97026. var promise = new Promise(function (resolve, reject) {
  97027. 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);
  97028. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  97029. rgbdPostProcess.onApply = function (effect) {
  97030. effect._bindTexture("textureSampler", tempTexture);
  97031. };
  97032. // As the process needs to happen on the main canvas, keep track of the current size
  97033. var currentW = engine.getRenderWidth();
  97034. var currentH = engine.getRenderHeight();
  97035. // Set the desired size for the texture
  97036. engine.setSize(faceWidth, faceWidth);
  97037. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  97038. // Reading datas from WebGL
  97039. BABYLON.Tools.ToBlob(canvas, function (blob) {
  97040. var fileReader = new FileReader();
  97041. fileReader.onload = function (event) {
  97042. var arrayBuffer = event.target.result;
  97043. specularTextures[i * 6 + face] = arrayBuffer;
  97044. resolve();
  97045. };
  97046. fileReader.readAsArrayBuffer(blob);
  97047. });
  97048. // Reapply the previous canvas size
  97049. engine.setSize(currentW, currentH);
  97050. });
  97051. });
  97052. promises.push(promise);
  97053. };
  97054. // All faces of the cube.
  97055. for (var face = 0; face < 6; face++) {
  97056. _loop_2(face);
  97057. }
  97058. };
  97059. for (var i = 0; i <= mipmapsCount; i++) {
  97060. _loop_1(i);
  97061. }
  97062. // Once all the textures haves been collected as RGBD stored in PNGs
  97063. return Promise.all(promises).then(function () {
  97064. // We can delete the hosting scene keeping track of all the creation objects
  97065. hostingScene.dispose();
  97066. // Creates the json header for the env texture
  97067. var info = {
  97068. version: 1,
  97069. width: cubeWidth,
  97070. irradiance: _this._CreateEnvTextureIrradiance(texture),
  97071. specular: {
  97072. mipmaps: [],
  97073. lodGenerationScale: texture.lodGenerationScale
  97074. }
  97075. };
  97076. // Sets the specular image data information
  97077. var position = 0;
  97078. for (var i = 0; i <= mipmapsCount; i++) {
  97079. for (var face = 0; face < 6; face++) {
  97080. var byteLength = specularTextures[i * 6 + face].byteLength;
  97081. info.specular.mipmaps.push({
  97082. length: byteLength,
  97083. position: position
  97084. });
  97085. position += byteLength;
  97086. }
  97087. }
  97088. // Encode the JSON as an array buffer
  97089. var infoString = JSON.stringify(info);
  97090. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  97091. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  97092. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  97093. infoView[i] = infoString.charCodeAt(i);
  97094. }
  97095. // Ends up with a null terminator for easier parsing
  97096. infoView[infoString.length] = 0x00;
  97097. // Computes the final required size and creates the storage
  97098. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  97099. var finalBuffer = new ArrayBuffer(totalSize);
  97100. var finalBufferView = new Uint8Array(finalBuffer);
  97101. var dataView = new DataView(finalBuffer);
  97102. // Copy the magic bytes identifying the file in
  97103. var pos = 0;
  97104. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  97105. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  97106. }
  97107. // Add the json info
  97108. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  97109. pos += infoBuffer.byteLength;
  97110. // Finally inserts the texture data
  97111. for (var i = 0; i <= mipmapsCount; i++) {
  97112. for (var face = 0; face < 6; face++) {
  97113. var dataBuffer = specularTextures[i * 6 + face];
  97114. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  97115. pos += dataBuffer.byteLength;
  97116. }
  97117. }
  97118. // Voila
  97119. return finalBuffer;
  97120. });
  97121. };
  97122. /**
  97123. * Creates a JSON representation of the spherical data.
  97124. * @param texture defines the texture containing the polynomials
  97125. * @return the JSON representation of the spherical info
  97126. */
  97127. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  97128. var polynmials = texture.sphericalPolynomial;
  97129. if (polynmials == null) {
  97130. return null;
  97131. }
  97132. return {
  97133. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  97134. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  97135. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  97136. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  97137. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  97138. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  97139. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  97140. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  97141. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  97142. };
  97143. };
  97144. /**
  97145. * Uploads the texture info contained in the env file to the GPU.
  97146. * @param texture defines the internal texture to upload to
  97147. * @param arrayBuffer defines the buffer cotaining the data to load
  97148. * @param info defines the texture info retrieved through the GetEnvInfo method
  97149. * @returns a promise
  97150. */
  97151. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  97152. if (info.version !== 1) {
  97153. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  97154. }
  97155. var specularInfo = info.specular;
  97156. if (!specularInfo) {
  97157. // Nothing else parsed so far
  97158. return Promise.resolve();
  97159. }
  97160. // Double checks the enclosed info
  97161. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  97162. mipmapsCount = Math.round(mipmapsCount) + 1;
  97163. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  97164. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  97165. }
  97166. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  97167. var imageData = new Array(mipmapsCount);
  97168. for (var i = 0; i < mipmapsCount; i++) {
  97169. imageData[i] = new Array(6);
  97170. for (var face = 0; face < 6; face++) {
  97171. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  97172. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  97173. }
  97174. }
  97175. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  97176. };
  97177. /**
  97178. * Uploads the levels of image data to the GPU.
  97179. * @param texture defines the internal texture to upload to
  97180. * @param imageData defines the array buffer views of image data [mipmap][face]
  97181. * @returns a promise
  97182. */
  97183. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  97184. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  97185. throw new Error("Texture size must be a power of two");
  97186. }
  97187. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  97188. // Gets everything ready.
  97189. var engine = texture.getEngine();
  97190. var expandTexture = false;
  97191. var generateNonLODTextures = false;
  97192. var rgbdPostProcess = null;
  97193. var cubeRtt = null;
  97194. var lodTextures = null;
  97195. var caps = engine.getCaps();
  97196. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97197. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97198. texture.generateMipMaps = true;
  97199. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  97200. // Add extra process if texture lod is not supported
  97201. if (!caps.textureLOD) {
  97202. expandTexture = false;
  97203. generateNonLODTextures = true;
  97204. lodTextures = {};
  97205. }
  97206. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  97207. else if (engine.webGLVersion < 2) {
  97208. expandTexture = false;
  97209. }
  97210. // If half float available we can uncompress the texture
  97211. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  97212. expandTexture = true;
  97213. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97214. }
  97215. // If full float available we can uncompress the texture
  97216. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  97217. expandTexture = true;
  97218. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97219. }
  97220. // Expand the texture if possible
  97221. if (expandTexture) {
  97222. // Simply run through the decode PP
  97223. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  97224. texture._isRGBD = false;
  97225. texture.invertY = false;
  97226. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  97227. generateDepthBuffer: false,
  97228. generateMipMaps: true,
  97229. generateStencilBuffer: false,
  97230. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  97231. type: texture.type,
  97232. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  97233. });
  97234. }
  97235. else {
  97236. texture._isRGBD = true;
  97237. texture.invertY = true;
  97238. // In case of missing support, applies the same patch than DDS files.
  97239. if (generateNonLODTextures) {
  97240. var mipSlices = 3;
  97241. var scale = texture._lodGenerationScale;
  97242. var offset = texture._lodGenerationOffset;
  97243. for (var i = 0; i < mipSlices; i++) {
  97244. //compute LOD from even spacing in smoothness (matching shader calculation)
  97245. var smoothness = i / (mipSlices - 1);
  97246. var roughness = 1 - smoothness;
  97247. var minLODIndex = offset; // roughness = 0
  97248. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  97249. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  97250. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  97251. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  97252. glTextureFromLod.isCube = true;
  97253. glTextureFromLod.invertY = true;
  97254. glTextureFromLod.generateMipMaps = false;
  97255. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  97256. // Wrap in a base texture for easy binding.
  97257. var lodTexture = new BABYLON.BaseTexture(null);
  97258. lodTexture.isCube = true;
  97259. lodTexture._texture = glTextureFromLod;
  97260. lodTextures[mipmapIndex] = lodTexture;
  97261. switch (i) {
  97262. case 0:
  97263. texture._lodTextureLow = lodTexture;
  97264. break;
  97265. case 1:
  97266. texture._lodTextureMid = lodTexture;
  97267. break;
  97268. case 2:
  97269. texture._lodTextureHigh = lodTexture;
  97270. break;
  97271. }
  97272. }
  97273. }
  97274. }
  97275. var promises = [];
  97276. var _loop_3 = function (i) {
  97277. var _loop_4 = function (face) {
  97278. // Constructs an image element from image data
  97279. var bytes = imageData[i][face];
  97280. var blob = new Blob([bytes], { type: 'image/png' });
  97281. var url = URL.createObjectURL(blob);
  97282. var image = new Image();
  97283. image.src = url;
  97284. // Enqueue promise to upload to the texture.
  97285. var promise = new Promise(function (resolve, reject) {
  97286. image.onload = function () {
  97287. if (expandTexture) {
  97288. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  97289. reject(message);
  97290. }, image);
  97291. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  97292. // Uncompress the data to a RTT
  97293. rgbdPostProcess.onApply = function (effect) {
  97294. effect._bindTexture("textureSampler", tempTexture_1);
  97295. effect.setFloat2("scale", 1, 1);
  97296. };
  97297. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  97298. // Cleanup
  97299. engine.restoreDefaultFramebuffer();
  97300. tempTexture_1.dispose();
  97301. window.URL.revokeObjectURL(url);
  97302. resolve();
  97303. });
  97304. }
  97305. else {
  97306. engine._uploadImageToTexture(texture, image, face, i);
  97307. // Upload the face to the non lod texture support
  97308. if (generateNonLODTextures) {
  97309. var lodTexture = lodTextures[i];
  97310. if (lodTexture) {
  97311. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  97312. }
  97313. }
  97314. resolve();
  97315. }
  97316. };
  97317. image.onerror = function (error) {
  97318. reject(error);
  97319. };
  97320. });
  97321. promises.push(promise);
  97322. };
  97323. // All faces
  97324. for (var face = 0; face < 6; face++) {
  97325. _loop_4(face);
  97326. }
  97327. };
  97328. // All mipmaps up to provided number of images
  97329. for (var i = 0; i < imageData.length; i++) {
  97330. _loop_3(i);
  97331. }
  97332. // Fill remaining mipmaps with black textures.
  97333. if (imageData.length < mipmapsCount) {
  97334. var data = void 0;
  97335. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  97336. var dataLength = size * size * 4;
  97337. switch (texture.type) {
  97338. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  97339. data = new Uint8Array(dataLength);
  97340. break;
  97341. }
  97342. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  97343. data = new Uint16Array(dataLength);
  97344. break;
  97345. }
  97346. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  97347. data = new Float32Array(dataLength);
  97348. break;
  97349. }
  97350. }
  97351. for (var i = imageData.length; i < mipmapsCount; i++) {
  97352. for (var face = 0; face < 6; face++) {
  97353. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  97354. }
  97355. }
  97356. }
  97357. // Once all done, finishes the cleanup and return
  97358. return Promise.all(promises).then(function () {
  97359. // Release temp RTT.
  97360. if (cubeRtt) {
  97361. engine._releaseFramebufferObjects(cubeRtt);
  97362. cubeRtt._swapAndDie(texture);
  97363. }
  97364. // Release temp Post Process.
  97365. if (rgbdPostProcess) {
  97366. rgbdPostProcess.dispose();
  97367. }
  97368. // Flag internal texture as ready in case they are in use.
  97369. if (generateNonLODTextures) {
  97370. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  97371. texture._lodTextureHigh._texture.isReady = true;
  97372. }
  97373. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  97374. texture._lodTextureMid._texture.isReady = true;
  97375. }
  97376. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  97377. texture._lodTextureLow._texture.isReady = true;
  97378. }
  97379. }
  97380. });
  97381. };
  97382. /**
  97383. * Uploads spherical polynomials information to the texture.
  97384. * @param texture defines the texture we are trying to upload the information to
  97385. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  97386. */
  97387. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  97388. if (info.version !== 1) {
  97389. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  97390. }
  97391. var irradianceInfo = info.irradiance;
  97392. if (!irradianceInfo) {
  97393. return;
  97394. }
  97395. var sp = new BABYLON.SphericalPolynomial();
  97396. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  97397. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  97398. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  97399. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  97400. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  97401. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  97402. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  97403. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  97404. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  97405. texture._sphericalPolynomial = sp;
  97406. };
  97407. /**
  97408. * Magic number identifying the env file.
  97409. */
  97410. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  97411. return EnvironmentTextureTools;
  97412. }());
  97413. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  97414. })(BABYLON || (BABYLON = {}));
  97415. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  97416. var BABYLON;
  97417. (function (BABYLON) {
  97418. /**
  97419. * Implementation of the ENV Texture Loader.
  97420. */
  97421. var ENVTextureLoader = /** @class */ (function () {
  97422. function ENVTextureLoader() {
  97423. /**
  97424. * Defines wether the loader supports cascade loading the different faces.
  97425. */
  97426. this.supportCascades = false;
  97427. }
  97428. /**
  97429. * This returns if the loader support the current file information.
  97430. * @param extension defines the file extension of the file being loaded
  97431. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97432. * @param fallback defines the fallback internal texture if any
  97433. * @param isBase64 defines whether the texture is encoded as a base64
  97434. * @param isBuffer defines whether the texture data are stored as a buffer
  97435. * @returns true if the loader can load the specified file
  97436. */
  97437. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  97438. return extension.indexOf(".env") === 0;
  97439. };
  97440. /**
  97441. * Transform the url before loading if required.
  97442. * @param rootUrl the url of the texture
  97443. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97444. * @returns the transformed texture
  97445. */
  97446. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  97447. return rootUrl;
  97448. };
  97449. /**
  97450. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  97451. * @param rootUrl the url of the texture
  97452. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97453. * @returns the fallback texture
  97454. */
  97455. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  97456. return null;
  97457. };
  97458. /**
  97459. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  97460. * @param data contains the texture data
  97461. * @param texture defines the BabylonJS internal texture
  97462. * @param createPolynomials will be true if polynomials have been requested
  97463. * @param onLoad defines the callback to trigger once the texture is ready
  97464. * @param onError defines the callback to trigger in case of error
  97465. */
  97466. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  97467. if (Array.isArray(data)) {
  97468. return;
  97469. }
  97470. data = data;
  97471. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  97472. if (info) {
  97473. texture.width = info.width;
  97474. texture.height = info.width;
  97475. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  97476. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  97477. texture.isReady = true;
  97478. if (onLoad) {
  97479. onLoad();
  97480. }
  97481. });
  97482. }
  97483. else if (onError) {
  97484. onError("Can not parse the environment file", null);
  97485. }
  97486. };
  97487. /**
  97488. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  97489. * @param data contains the texture data
  97490. * @param texture defines the BabylonJS internal texture
  97491. * @param callback defines the method to call once ready to upload
  97492. */
  97493. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  97494. throw ".env not supported in 2d.";
  97495. };
  97496. return ENVTextureLoader;
  97497. }());
  97498. // Register the loader.
  97499. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  97500. })(BABYLON || (BABYLON = {}));
  97501. //# sourceMappingURL=babylon.envTextureLoader.js.map
  97502. var BABYLON;
  97503. (function (BABYLON) {
  97504. /**
  97505. * Renders a layer on top of an existing scene
  97506. */
  97507. var UtilityLayerRenderer = /** @class */ (function () {
  97508. /**
  97509. * Instantiates a UtilityLayerRenderer
  97510. * @param originalScene the original scene that will be rendered on top of
  97511. */
  97512. function UtilityLayerRenderer(
  97513. /** the original scene that will be rendered on top of */
  97514. originalScene) {
  97515. var _this = this;
  97516. this.originalScene = originalScene;
  97517. this._pointerCaptures = {};
  97518. this._lastPointerEvents = {};
  97519. /**
  97520. * If the utility layer should automatically be rendered on top of existing scene
  97521. */
  97522. this.shouldRender = true;
  97523. /**
  97524. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  97525. */
  97526. this.onlyCheckPointerDownEvents = true;
  97527. /**
  97528. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  97529. */
  97530. this.processAllEvents = false;
  97531. /**
  97532. * Observable raised when the pointer move from the utility layer scene to the main scene
  97533. */
  97534. this.onPointerOutObservable = new BABYLON.Observable();
  97535. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  97536. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  97537. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  97538. this.utilityLayerScene._allowPostProcessClearColor = false;
  97539. originalScene.getEngine().scenes.pop();
  97540. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  97541. this.utilityLayerScene.detachControl();
  97542. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  97543. if (!_this.processAllEvents) {
  97544. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  97545. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  97546. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  97547. return;
  97548. }
  97549. }
  97550. var pointerEvent = (prePointerInfo.event);
  97551. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  97552. _this._pointerCaptures[pointerEvent.pointerId] = false;
  97553. return;
  97554. }
  97555. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  97556. if (!prePointerInfo.ray && utilityScenePick) {
  97557. prePointerInfo.ray = utilityScenePick.ray;
  97558. }
  97559. // always fire the prepointer oversvable
  97560. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  97561. // allow every non pointer down event to flow to the utility layer
  97562. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  97563. if (!prePointerInfo.skipOnPointerObservable) {
  97564. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  97565. }
  97566. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  97567. _this._pointerCaptures[pointerEvent.pointerId] = false;
  97568. }
  97569. return;
  97570. }
  97571. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  97572. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  97573. if (utilityScenePick && utilityScenePick.hit) {
  97574. if (!prePointerInfo.skipOnPointerObservable) {
  97575. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  97576. }
  97577. prePointerInfo.skipOnPointerObservable = true;
  97578. }
  97579. }
  97580. else {
  97581. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  97582. var pointerEvent_1 = (prePointerInfo.event);
  97583. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  97584. if (originalScenePick && utilityScenePick) {
  97585. // No pick in utility scene
  97586. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  97587. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  97588. // We touched an utility mesh present in the main scene
  97589. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  97590. prePointerInfo.skipOnPointerObservable = true;
  97591. }
  97592. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97593. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  97594. }
  97595. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  97596. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  97597. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  97598. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  97599. }
  97600. }
  97601. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  97602. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  97603. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  97604. // If a previous utility layer set this, do not unset this
  97605. if (!prePointerInfo.skipOnPointerObservable) {
  97606. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  97607. }
  97608. }
  97609. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  97610. // We have a pick in both scenes but main is closer than utility
  97611. // We touched an utility mesh present in the main scene
  97612. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  97613. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  97614. prePointerInfo.skipOnPointerObservable = true;
  97615. }
  97616. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  97617. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  97618. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  97619. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  97620. }
  97621. }
  97622. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  97623. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  97624. }
  97625. }
  97626. }
  97627. });
  97628. // Render directly on top of existing scene without clearing
  97629. this.utilityLayerScene.autoClear = false;
  97630. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  97631. if (_this.shouldRender) {
  97632. _this.render();
  97633. }
  97634. });
  97635. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  97636. _this.dispose();
  97637. });
  97638. this._updateCamera();
  97639. }
  97640. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  97641. /**
  97642. * 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)
  97643. */
  97644. get: function () {
  97645. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  97646. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  97647. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  97648. UtilityLayerRenderer._DefaultUtilityLayer = null;
  97649. });
  97650. }
  97651. return UtilityLayerRenderer._DefaultUtilityLayer;
  97652. },
  97653. enumerable: true,
  97654. configurable: true
  97655. });
  97656. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  97657. /**
  97658. * 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)
  97659. */
  97660. get: function () {
  97661. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  97662. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  97663. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  97664. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  97665. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  97666. });
  97667. }
  97668. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  97669. },
  97670. enumerable: true,
  97671. configurable: true
  97672. });
  97673. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  97674. if (!prePointerInfo.skipOnPointerObservable) {
  97675. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  97676. this._lastPointerEvents[pointerEvent.pointerId] = true;
  97677. }
  97678. };
  97679. /**
  97680. * Renders the utility layers scene on top of the original scene
  97681. */
  97682. UtilityLayerRenderer.prototype.render = function () {
  97683. this._updateCamera();
  97684. if (this.utilityLayerScene.activeCamera) {
  97685. // Set the camera's scene to utility layers scene
  97686. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  97687. var camera = this.utilityLayerScene.activeCamera;
  97688. camera._scene = this.utilityLayerScene;
  97689. if (camera.leftCamera) {
  97690. camera.leftCamera._scene = this.utilityLayerScene;
  97691. }
  97692. if (camera.rightCamera) {
  97693. camera.rightCamera._scene = this.utilityLayerScene;
  97694. }
  97695. this.utilityLayerScene.render(false);
  97696. // Reset camera's scene back to original
  97697. camera._scene = oldScene;
  97698. if (camera.leftCamera) {
  97699. camera.leftCamera._scene = oldScene;
  97700. }
  97701. if (camera.rightCamera) {
  97702. camera.rightCamera._scene = oldScene;
  97703. }
  97704. }
  97705. };
  97706. /**
  97707. * Disposes of the renderer
  97708. */
  97709. UtilityLayerRenderer.prototype.dispose = function () {
  97710. this.onPointerOutObservable.clear();
  97711. if (this._afterRenderObserver) {
  97712. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  97713. }
  97714. if (this._sceneDisposeObserver) {
  97715. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  97716. }
  97717. if (this._originalPointerObserver) {
  97718. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  97719. }
  97720. this.utilityLayerScene.dispose();
  97721. };
  97722. UtilityLayerRenderer.prototype._updateCamera = function () {
  97723. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  97724. };
  97725. UtilityLayerRenderer._DefaultUtilityLayer = null;
  97726. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  97727. return UtilityLayerRenderer;
  97728. }());
  97729. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  97730. })(BABYLON || (BABYLON = {}));
  97731. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  97732. //# sourceMappingURL=babylon.behavior.js.map
  97733. var BABYLON;
  97734. (function (BABYLON) {
  97735. /**
  97736. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  97737. */
  97738. var PointerDragBehavior = /** @class */ (function () {
  97739. /**
  97740. * Creates a pointer drag behavior that can be attached to a mesh
  97741. * @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)
  97742. */
  97743. function PointerDragBehavior(options) {
  97744. /**
  97745. * 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)
  97746. */
  97747. this.maxDragAngle = 0;
  97748. /**
  97749. * @hidden
  97750. */
  97751. this._useAlternatePickedPointAboveMaxDragAngle = false;
  97752. /**
  97753. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  97754. */
  97755. this.currentDraggingPointerID = -1;
  97756. /**
  97757. * If the behavior is currently in a dragging state
  97758. */
  97759. this.dragging = false;
  97760. /**
  97761. * 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)
  97762. */
  97763. this.dragDeltaRatio = 0.2;
  97764. /**
  97765. * If the drag plane orientation should be updated during the dragging (Default: true)
  97766. */
  97767. this.updateDragPlane = true;
  97768. // Debug mode will display drag planes to help visualize behavior
  97769. this._debugMode = false;
  97770. this._moving = false;
  97771. /**
  97772. * Fires each time the attached mesh is dragged with the pointer
  97773. * * delta between last drag position and current drag position in world space
  97774. * * dragDistance along the drag axis
  97775. * * dragPlaneNormal normal of the current drag plane used during the drag
  97776. * * dragPlanePoint in world space where the drag intersects the drag plane
  97777. */
  97778. this.onDragObservable = new BABYLON.Observable();
  97779. /**
  97780. * Fires each time a drag begins (eg. mouse down on mesh)
  97781. */
  97782. this.onDragStartObservable = new BABYLON.Observable();
  97783. /**
  97784. * Fires each time a drag ends (eg. mouse release after drag)
  97785. */
  97786. this.onDragEndObservable = new BABYLON.Observable();
  97787. /**
  97788. * If the attached mesh should be moved when dragged
  97789. */
  97790. this.moveAttached = true;
  97791. /**
  97792. * If the drag behavior will react to drag events (Default: true)
  97793. */
  97794. this.enabled = true;
  97795. /**
  97796. * If camera controls should be detached during the drag
  97797. */
  97798. this.detachCameraControls = true;
  97799. /**
  97800. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  97801. */
  97802. this.useObjectOrienationForDragging = true;
  97803. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  97804. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  97805. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  97806. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  97807. this._attachedElement = null;
  97808. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  97809. this._lastPointerRay = {};
  97810. this._dragDelta = new BABYLON.Vector3();
  97811. // Variables to avoid instantiation in the below method
  97812. this._pointA = new BABYLON.Vector3(0, 0, 0);
  97813. this._pointB = new BABYLON.Vector3(0, 0, 0);
  97814. this._pointC = new BABYLON.Vector3(0, 0, 0);
  97815. this._lineA = new BABYLON.Vector3(0, 0, 0);
  97816. this._lineB = new BABYLON.Vector3(0, 0, 0);
  97817. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  97818. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  97819. this._options = options ? options : {};
  97820. var optionCount = 0;
  97821. if (this._options.dragAxis) {
  97822. optionCount++;
  97823. }
  97824. if (this._options.dragPlaneNormal) {
  97825. optionCount++;
  97826. }
  97827. if (optionCount > 1) {
  97828. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  97829. }
  97830. }
  97831. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  97832. /**
  97833. * The name of the behavior
  97834. */
  97835. get: function () {
  97836. return "PointerDrag";
  97837. },
  97838. enumerable: true,
  97839. configurable: true
  97840. });
  97841. /**
  97842. * Initializes the behavior
  97843. */
  97844. PointerDragBehavior.prototype.init = function () { };
  97845. /**
  97846. * Attaches the drag behavior the passed in mesh
  97847. * @param ownerNode The mesh that will be dragged around once attached
  97848. */
  97849. PointerDragBehavior.prototype.attach = function (ownerNode) {
  97850. var _this = this;
  97851. this._scene = ownerNode.getScene();
  97852. this._attachedNode = ownerNode;
  97853. // Initialize drag plane to not interfere with existing scene
  97854. if (!PointerDragBehavior._planeScene) {
  97855. if (this._debugMode) {
  97856. PointerDragBehavior._planeScene = this._scene;
  97857. }
  97858. else {
  97859. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  97860. PointerDragBehavior._planeScene.detachControl();
  97861. this._scene.getEngine().scenes.pop();
  97862. this._scene.onDisposeObservable.addOnce(function () {
  97863. PointerDragBehavior._planeScene.dispose();
  97864. PointerDragBehavior._planeScene = null;
  97865. });
  97866. }
  97867. }
  97868. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  97869. // State of the drag
  97870. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  97871. var pickPredicate = function (m) {
  97872. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  97873. };
  97874. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  97875. if (!_this.enabled) {
  97876. return;
  97877. }
  97878. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  97879. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  97880. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  97881. }
  97882. }
  97883. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  97884. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  97885. _this.releaseDrag();
  97886. }
  97887. }
  97888. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  97889. var pointerId = pointerInfo.event.pointerId;
  97890. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  97891. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  97892. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  97893. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  97894. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  97895. }
  97896. _this.currentDraggingPointerID = pointerId;
  97897. }
  97898. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  97899. if (!_this._lastPointerRay[pointerId]) {
  97900. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  97901. }
  97902. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  97903. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  97904. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  97905. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  97906. _this._moveDrag(pointerInfo.pickInfo.ray);
  97907. }
  97908. }
  97909. }
  97910. });
  97911. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  97912. if (_this._moving && _this.moveAttached) {
  97913. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  97914. // Slowly move mesh to avoid jitter
  97915. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  97916. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  97917. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  97918. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  97919. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  97920. }
  97921. });
  97922. };
  97923. /**
  97924. * Force relase the drag action by code.
  97925. */
  97926. PointerDragBehavior.prototype.releaseDrag = function () {
  97927. this.dragging = false;
  97928. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  97929. this.currentDraggingPointerID = -1;
  97930. this._moving = false;
  97931. // Reattach camera controls
  97932. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  97933. this._scene.activeCamera.attachControl(this._attachedElement, true);
  97934. }
  97935. };
  97936. /**
  97937. * Simulates the start of a pointer drag event on the behavior
  97938. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  97939. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  97940. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  97941. */
  97942. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  97943. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  97944. this._startDrag(pointerId, fromRay, startPickedPoint);
  97945. var lastRay = this._lastPointerRay[pointerId];
  97946. if (pointerId === PointerDragBehavior._AnyMouseID) {
  97947. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  97948. }
  97949. if (lastRay) {
  97950. // if there was a last pointer ray drag the object there
  97951. this._moveDrag(lastRay);
  97952. }
  97953. };
  97954. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  97955. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  97956. return;
  97957. }
  97958. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  97959. // Create start ray from the camera to the object
  97960. if (fromRay) {
  97961. this._startDragRay.direction.copyFrom(fromRay.direction);
  97962. this._startDragRay.origin.copyFrom(fromRay.origin);
  97963. }
  97964. else {
  97965. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  97966. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  97967. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  97968. }
  97969. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  97970. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  97971. if (pickedPoint) {
  97972. this.dragging = true;
  97973. this.currentDraggingPointerID = pointerId;
  97974. this.lastDragPosition.copyFrom(pickedPoint);
  97975. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  97976. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  97977. // Detatch camera controls
  97978. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  97979. if (this._scene.activeCamera.inputs.attachedElement) {
  97980. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  97981. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  97982. }
  97983. else {
  97984. this._attachedElement = null;
  97985. }
  97986. }
  97987. }
  97988. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  97989. };
  97990. PointerDragBehavior.prototype._moveDrag = function (ray) {
  97991. this._moving = true;
  97992. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  97993. if (pickedPoint) {
  97994. if (this.updateDragPlane) {
  97995. this._updateDragPlanePosition(ray, pickedPoint);
  97996. }
  97997. var dragLength = 0;
  97998. // depending on the drag mode option drag accordingly
  97999. if (this._options.dragAxis) {
  98000. // Convert local drag axis to world
  98001. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  98002. // Project delta drag from the drag plane onto the drag axis
  98003. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  98004. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  98005. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  98006. }
  98007. else {
  98008. dragLength = this._dragDelta.length();
  98009. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  98010. }
  98011. this._targetPosition.addInPlace(this._dragDelta);
  98012. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  98013. this.lastDragPosition.copyFrom(pickedPoint);
  98014. }
  98015. };
  98016. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  98017. var _this = this;
  98018. if (!ray) {
  98019. return null;
  98020. }
  98021. // Calculate angle between plane normal and ray
  98022. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  98023. // Correct if ray is casted from oposite side
  98024. if (angle > Math.PI / 2) {
  98025. angle = Math.PI - angle;
  98026. }
  98027. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  98028. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  98029. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  98030. // Invert ray direction along the towards object axis
  98031. this._tmpVector.copyFrom(ray.direction);
  98032. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  98033. this._alternatePickedPoint.normalize();
  98034. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  98035. this._tmpVector.addInPlace(this._alternatePickedPoint);
  98036. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  98037. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  98038. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  98039. this._alternatePickedPoint.addInPlace(this._tmpVector);
  98040. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  98041. return this._alternatePickedPoint;
  98042. }
  98043. else {
  98044. return null;
  98045. }
  98046. }
  98047. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  98048. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  98049. return pickResult.pickedPoint;
  98050. }
  98051. else {
  98052. return null;
  98053. }
  98054. };
  98055. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  98056. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  98057. this._pointA.copyFrom(dragPlanePosition);
  98058. if (this._options.dragAxis) {
  98059. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  98060. // Calculate plane normal in direction of camera but perpendicular to drag axis
  98061. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  98062. ray.origin.subtractToRef(this._pointA, this._pointC);
  98063. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  98064. // Get perpendicular line from direction to camera and drag axis
  98065. this._pointB.subtractToRef(this._pointA, this._lineA);
  98066. this._pointC.subtractToRef(this._pointA, this._lineB);
  98067. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  98068. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  98069. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  98070. this._lookAt.normalize();
  98071. this._dragPlane.position.copyFrom(this._pointA);
  98072. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  98073. this._dragPlane.lookAt(this._lookAt);
  98074. }
  98075. else if (this._options.dragPlaneNormal) {
  98076. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  98077. this._dragPlane.position.copyFrom(this._pointA);
  98078. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  98079. this._dragPlane.lookAt(this._lookAt);
  98080. }
  98081. else {
  98082. this._dragPlane.position.copyFrom(this._pointA);
  98083. this._dragPlane.lookAt(ray.origin);
  98084. }
  98085. this._dragPlane.computeWorldMatrix(true);
  98086. };
  98087. /**
  98088. * Detaches the behavior from the mesh
  98089. */
  98090. PointerDragBehavior.prototype.detach = function () {
  98091. if (this._pointerObserver) {
  98092. this._scene.onPointerObservable.remove(this._pointerObserver);
  98093. }
  98094. if (this._beforeRenderObserver) {
  98095. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  98096. }
  98097. };
  98098. PointerDragBehavior._AnyMouseID = -2;
  98099. return PointerDragBehavior;
  98100. }());
  98101. BABYLON.PointerDragBehavior = PointerDragBehavior;
  98102. })(BABYLON || (BABYLON = {}));
  98103. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  98104. var BABYLON;
  98105. (function (BABYLON) {
  98106. /**
  98107. * A behavior that when attached to a mesh will allow the mesh to be scaled
  98108. */
  98109. var MultiPointerScaleBehavior = /** @class */ (function () {
  98110. /**
  98111. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  98112. */
  98113. function MultiPointerScaleBehavior() {
  98114. this._startDistance = 0;
  98115. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  98116. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  98117. this._sceneRenderObserver = null;
  98118. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  98119. this._dragBehaviorA.moveAttached = false;
  98120. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  98121. this._dragBehaviorB.moveAttached = false;
  98122. }
  98123. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  98124. /**
  98125. * The name of the behavior
  98126. */
  98127. get: function () {
  98128. return "MultiPointerScale";
  98129. },
  98130. enumerable: true,
  98131. configurable: true
  98132. });
  98133. /**
  98134. * Initializes the behavior
  98135. */
  98136. MultiPointerScaleBehavior.prototype.init = function () { };
  98137. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  98138. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  98139. };
  98140. /**
  98141. * Attaches the scale behavior the passed in mesh
  98142. * @param ownerNode The mesh that will be scaled around once attached
  98143. */
  98144. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  98145. var _this = this;
  98146. this._ownerNode = ownerNode;
  98147. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  98148. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  98149. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98150. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  98151. _this._dragBehaviorA.releaseDrag();
  98152. }
  98153. else {
  98154. _this._initialScale.copyFrom(ownerNode.scaling);
  98155. _this._startDistance = _this._getCurrentDistance();
  98156. }
  98157. }
  98158. });
  98159. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  98160. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98161. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  98162. _this._dragBehaviorB.releaseDrag();
  98163. }
  98164. else {
  98165. _this._initialScale.copyFrom(ownerNode.scaling);
  98166. _this._startDistance = _this._getCurrentDistance();
  98167. }
  98168. }
  98169. });
  98170. // Once both drag behaviors are active scale based on the distance between the two pointers
  98171. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  98172. behavior.onDragObservable.add(function () {
  98173. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98174. var ratio = _this._getCurrentDistance() / _this._startDistance;
  98175. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  98176. }
  98177. });
  98178. });
  98179. ownerNode.addBehavior(this._dragBehaviorA);
  98180. ownerNode.addBehavior(this._dragBehaviorB);
  98181. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  98182. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  98183. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98184. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  98185. if (change.length() > 0.01) {
  98186. ownerNode.scaling.addInPlace(change);
  98187. }
  98188. }
  98189. });
  98190. };
  98191. /**
  98192. * Detaches the behavior from the mesh
  98193. */
  98194. MultiPointerScaleBehavior.prototype.detach = function () {
  98195. var _this = this;
  98196. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  98197. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  98198. behavior.onDragStartObservable.clear();
  98199. behavior.onDragObservable.clear();
  98200. _this._ownerNode.removeBehavior(behavior);
  98201. });
  98202. };
  98203. return MultiPointerScaleBehavior;
  98204. }());
  98205. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  98206. })(BABYLON || (BABYLON = {}));
  98207. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  98208. var BABYLON;
  98209. (function (BABYLON) {
  98210. /**
  98211. * 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
  98212. */
  98213. var SixDofDragBehavior = /** @class */ (function () {
  98214. /**
  98215. * Instantiates 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
  98216. */
  98217. function SixDofDragBehavior() {
  98218. this._sceneRenderObserver = null;
  98219. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  98220. this._moving = false;
  98221. this._startingOrientation = new BABYLON.Quaternion();
  98222. /**
  98223. * 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)
  98224. */
  98225. this.zDragFactor = 3;
  98226. /**
  98227. * If the behavior is currently in a dragging state
  98228. */
  98229. this.dragging = false;
  98230. /**
  98231. * 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)
  98232. */
  98233. this.dragDeltaRatio = 0.2;
  98234. /**
  98235. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  98236. */
  98237. this.currentDraggingPointerID = -1;
  98238. /**
  98239. * If camera controls should be detached during the drag
  98240. */
  98241. this.detachCameraControls = true;
  98242. /**
  98243. * Fires each time a drag starts
  98244. */
  98245. this.onDragStartObservable = new BABYLON.Observable();
  98246. /**
  98247. * Fires each time a drag ends (eg. mouse release after drag)
  98248. */
  98249. this.onDragEndObservable = new BABYLON.Observable();
  98250. }
  98251. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  98252. /**
  98253. * The name of the behavior
  98254. */
  98255. get: function () {
  98256. return "SixDofDrag";
  98257. },
  98258. enumerable: true,
  98259. configurable: true
  98260. });
  98261. /**
  98262. * Initializes the behavior
  98263. */
  98264. SixDofDragBehavior.prototype.init = function () { };
  98265. /**
  98266. * Attaches the scale behavior the passed in mesh
  98267. * @param ownerNode The mesh that will be scaled around once attached
  98268. */
  98269. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  98270. var _this = this;
  98271. this._ownerNode = ownerNode;
  98272. this._scene = this._ownerNode.getScene();
  98273. if (!SixDofDragBehavior._virtualScene) {
  98274. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  98275. this._scene.getEngine().scenes.pop();
  98276. }
  98277. var pickedMesh = null;
  98278. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  98279. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  98280. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  98281. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  98282. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  98283. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  98284. var pickPredicate = function (m) {
  98285. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  98286. };
  98287. var attachedElement = null;
  98288. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  98289. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  98290. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  98291. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  98292. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  98293. }
  98294. pickedMesh = _this._ownerNode;
  98295. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  98296. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  98297. // Set position and orientation of the controller
  98298. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  98299. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  98300. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  98301. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  98302. pickedMesh.computeWorldMatrix();
  98303. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  98304. if (!pickedMesh.rotationQuaternion) {
  98305. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  98306. }
  98307. var oldParent = pickedMesh.parent;
  98308. pickedMesh.setParent(null);
  98309. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  98310. pickedMesh.setParent(oldParent);
  98311. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  98312. // Update state
  98313. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  98314. _this.dragging = true;
  98315. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  98316. // Detatch camera controls
  98317. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  98318. if (_this._scene.activeCamera.inputs.attachedElement) {
  98319. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  98320. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  98321. }
  98322. else {
  98323. attachedElement = null;
  98324. }
  98325. }
  98326. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  98327. _this.onDragStartObservable.notifyObservers({});
  98328. }
  98329. }
  98330. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  98331. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  98332. _this.dragging = false;
  98333. _this._moving = false;
  98334. _this.currentDraggingPointerID = -1;
  98335. pickedMesh = null;
  98336. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  98337. // Reattach camera controls
  98338. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  98339. _this._scene.activeCamera.attachControl(attachedElement, true);
  98340. }
  98341. _this.onDragEndObservable.notifyObservers({});
  98342. }
  98343. }
  98344. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  98345. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  98346. var zDragFactor = _this.zDragFactor;
  98347. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  98348. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  98349. zDragFactor = 0;
  98350. }
  98351. // Calculate controller drag distance in controller space
  98352. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  98353. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  98354. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  98355. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  98356. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  98357. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  98358. if (_this._virtualDragMesh.position.z < 0) {
  98359. _this._virtualDragMesh.position.z = 0;
  98360. }
  98361. // Update the controller position
  98362. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  98363. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  98364. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  98365. // Move the virtualObjectsPosition into the picked mesh's space if needed
  98366. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  98367. if (pickedMesh.parent) {
  98368. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  98369. }
  98370. if (!_this._moving) {
  98371. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  98372. }
  98373. _this._moving = true;
  98374. }
  98375. }
  98376. });
  98377. var tmpQuaternion = new BABYLON.Quaternion();
  98378. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  98379. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  98380. if (_this.dragging && _this._moving && pickedMesh) {
  98381. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  98382. // Slowly move mesh to avoid jitter
  98383. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  98384. // Get change in rotation
  98385. tmpQuaternion.copyFrom(_this._startingOrientation);
  98386. tmpQuaternion.x = -tmpQuaternion.x;
  98387. tmpQuaternion.y = -tmpQuaternion.y;
  98388. tmpQuaternion.z = -tmpQuaternion.z;
  98389. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  98390. // Convert change in rotation to only y axis rotation
  98391. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  98392. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  98393. // Slowly move mesh to avoid jitter
  98394. var oldParent = pickedMesh.parent;
  98395. pickedMesh.setParent(null);
  98396. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  98397. pickedMesh.setParent(oldParent);
  98398. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  98399. }
  98400. });
  98401. };
  98402. /**
  98403. * Detaches the behavior from the mesh
  98404. */
  98405. SixDofDragBehavior.prototype.detach = function () {
  98406. if (this._scene) {
  98407. this._scene.onPointerObservable.remove(this._pointerObserver);
  98408. }
  98409. if (this._ownerNode) {
  98410. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  98411. }
  98412. if (this._virtualOriginMesh) {
  98413. this._virtualOriginMesh.dispose();
  98414. }
  98415. if (this._virtualDragMesh) {
  98416. this._virtualDragMesh.dispose();
  98417. }
  98418. this.onDragEndObservable.clear();
  98419. this.onDragStartObservable.clear();
  98420. };
  98421. return SixDofDragBehavior;
  98422. }());
  98423. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  98424. })(BABYLON || (BABYLON = {}));
  98425. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  98426. var BABYLON;
  98427. (function (BABYLON) {
  98428. /**
  98429. * @hidden
  98430. */
  98431. var FaceDirectionInfo = /** @class */ (function () {
  98432. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  98433. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  98434. if (diff === void 0) { diff = 0; }
  98435. if (ignore === void 0) { ignore = false; }
  98436. this.direction = direction;
  98437. this.rotatedDirection = rotatedDirection;
  98438. this.diff = diff;
  98439. this.ignore = ignore;
  98440. }
  98441. return FaceDirectionInfo;
  98442. }());
  98443. /**
  98444. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  98445. */
  98446. var AttachToBoxBehavior = /** @class */ (function () {
  98447. /**
  98448. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  98449. * @param ui The transform node that should be attched to the mesh
  98450. */
  98451. function AttachToBoxBehavior(ui) {
  98452. this.ui = ui;
  98453. /**
  98454. * The name of the behavior
  98455. */
  98456. this.name = "AttachToBoxBehavior";
  98457. /**
  98458. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  98459. */
  98460. this.distanceAwayFromFace = 0.15;
  98461. /**
  98462. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  98463. */
  98464. this.distanceAwayFromBottomOfFace = 0.15;
  98465. 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))];
  98466. this._tmpMatrix = new BABYLON.Matrix();
  98467. this._tmpVector = new BABYLON.Vector3();
  98468. this._zeroVector = BABYLON.Vector3.Zero();
  98469. this._lookAtTmpMatrix = new BABYLON.Matrix();
  98470. /* Does nothing */
  98471. }
  98472. /**
  98473. * Initializes the behavior
  98474. */
  98475. AttachToBoxBehavior.prototype.init = function () {
  98476. /* Does nothing */
  98477. };
  98478. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  98479. var _this = this;
  98480. // Go over each face and calculate the angle between the face's normal and targetDirection
  98481. this._faceVectors.forEach(function (v) {
  98482. if (!_this._target.rotationQuaternion) {
  98483. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  98484. }
  98485. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  98486. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  98487. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  98488. });
  98489. // Return the face information of the one with the normal closeset to target direction
  98490. return this._faceVectors.reduce(function (min, p) {
  98491. if (min.ignore) {
  98492. return p;
  98493. }
  98494. else if (p.ignore) {
  98495. return min;
  98496. }
  98497. else {
  98498. return min.diff < p.diff ? min : p;
  98499. }
  98500. }, this._faceVectors[0]);
  98501. };
  98502. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  98503. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  98504. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  98505. this._lookAtTmpMatrix.invert();
  98506. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  98507. };
  98508. /**
  98509. * Attaches the AttachToBoxBehavior to the passed in mesh
  98510. * @param target The mesh that the specified node will be attached to
  98511. */
  98512. AttachToBoxBehavior.prototype.attach = function (target) {
  98513. var _this = this;
  98514. this._target = target;
  98515. this._scene = this._target.getScene();
  98516. // Every frame, update the app bars position
  98517. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  98518. if (!_this._scene.activeCamera) {
  98519. return;
  98520. }
  98521. // Find the face closest to the cameras position
  98522. var cameraPos = _this._scene.activeCamera.position;
  98523. if (_this._scene.activeCamera.devicePosition) {
  98524. cameraPos = _this._scene.activeCamera.devicePosition;
  98525. }
  98526. var facing = _this._closestFace(cameraPos.subtract(target.position));
  98527. if (_this._scene.activeCamera.leftCamera) {
  98528. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  98529. }
  98530. else {
  98531. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  98532. }
  98533. // Get camera up direction
  98534. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  98535. // Ignore faces to not select a parrelel face for the up vector of the UI
  98536. _this._faceVectors.forEach(function (v) {
  98537. if (facing.direction.x && v.direction.x) {
  98538. v.ignore = true;
  98539. }
  98540. if (facing.direction.y && v.direction.y) {
  98541. v.ignore = true;
  98542. }
  98543. if (facing.direction.z && v.direction.z) {
  98544. v.ignore = true;
  98545. }
  98546. });
  98547. var facingUp = _this._closestFace(_this._tmpVector);
  98548. // Unignore faces
  98549. _this._faceVectors.forEach(function (v) {
  98550. v.ignore = false;
  98551. });
  98552. // Position the app bar on that face
  98553. _this.ui.position.copyFrom(target.position);
  98554. if (facing.direction.x) {
  98555. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  98556. _this.ui.position.addInPlace(_this._tmpVector);
  98557. }
  98558. if (facing.direction.y) {
  98559. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  98560. _this.ui.position.addInPlace(_this._tmpVector);
  98561. }
  98562. if (facing.direction.z) {
  98563. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  98564. _this.ui.position.addInPlace(_this._tmpVector);
  98565. }
  98566. // Rotate to be oriented properly to the camera
  98567. if (!_this.ui.rotationQuaternion) {
  98568. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  98569. }
  98570. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  98571. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  98572. // Place ui the correct distance from the bottom of the mesh
  98573. if (facingUp.direction.x) {
  98574. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  98575. }
  98576. if (facingUp.direction.y) {
  98577. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  98578. }
  98579. if (facingUp.direction.z) {
  98580. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  98581. }
  98582. _this.ui.position.addInPlace(_this._tmpVector);
  98583. });
  98584. };
  98585. /**
  98586. * Detaches the behavior from the mesh
  98587. */
  98588. AttachToBoxBehavior.prototype.detach = function () {
  98589. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  98590. };
  98591. return AttachToBoxBehavior;
  98592. }());
  98593. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  98594. })(BABYLON || (BABYLON = {}));
  98595. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  98596. var BABYLON;
  98597. (function (BABYLON) {
  98598. /**
  98599. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  98600. */
  98601. var FadeInOutBehavior = /** @class */ (function () {
  98602. /**
  98603. * Instatiates the FadeInOutBehavior
  98604. */
  98605. function FadeInOutBehavior() {
  98606. var _this = this;
  98607. /**
  98608. * Time in milliseconds to delay before fading in (Default: 0)
  98609. */
  98610. this.delay = 0;
  98611. /**
  98612. * Time in milliseconds for the mesh to fade in (Default: 300)
  98613. */
  98614. this.fadeInTime = 300;
  98615. this._millisecondsPerFrame = 1000 / 60;
  98616. this._hovered = false;
  98617. this._hoverValue = 0;
  98618. this._ownerNode = null;
  98619. this._update = function () {
  98620. if (_this._ownerNode) {
  98621. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  98622. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  98623. if (_this._ownerNode.visibility > 1) {
  98624. _this._setAllVisibility(_this._ownerNode, 1);
  98625. _this._hoverValue = _this.fadeInTime + _this.delay;
  98626. return;
  98627. }
  98628. else if (_this._ownerNode.visibility < 0) {
  98629. _this._setAllVisibility(_this._ownerNode, 0);
  98630. if (_this._hoverValue < 0) {
  98631. _this._hoverValue = 0;
  98632. return;
  98633. }
  98634. }
  98635. setTimeout(_this._update, _this._millisecondsPerFrame);
  98636. }
  98637. };
  98638. }
  98639. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  98640. /**
  98641. * The name of the behavior
  98642. */
  98643. get: function () {
  98644. return "FadeInOut";
  98645. },
  98646. enumerable: true,
  98647. configurable: true
  98648. });
  98649. /**
  98650. * Initializes the behavior
  98651. */
  98652. FadeInOutBehavior.prototype.init = function () {
  98653. };
  98654. /**
  98655. * Attaches the fade behavior on the passed in mesh
  98656. * @param ownerNode The mesh that will be faded in/out once attached
  98657. */
  98658. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  98659. this._ownerNode = ownerNode;
  98660. this._setAllVisibility(this._ownerNode, 0);
  98661. };
  98662. /**
  98663. * Detaches the behavior from the mesh
  98664. */
  98665. FadeInOutBehavior.prototype.detach = function () {
  98666. this._ownerNode = null;
  98667. };
  98668. /**
  98669. * Triggers the mesh to begin fading in or out
  98670. * @param value if the object should fade in or out (true to fade in)
  98671. */
  98672. FadeInOutBehavior.prototype.fadeIn = function (value) {
  98673. this._hovered = value;
  98674. this._update();
  98675. };
  98676. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  98677. var _this = this;
  98678. mesh.visibility = value;
  98679. mesh.getChildMeshes().forEach(function (c) {
  98680. _this._setAllVisibility(c, value);
  98681. });
  98682. };
  98683. return FadeInOutBehavior;
  98684. }());
  98685. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  98686. })(BABYLON || (BABYLON = {}));
  98687. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  98688. var BABYLON;
  98689. (function (BABYLON) {
  98690. /**
  98691. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  98692. */
  98693. var Gizmo = /** @class */ (function () {
  98694. /**
  98695. * Creates a gizmo
  98696. * @param gizmoLayer The utility layer the gizmo will be added to
  98697. */
  98698. function Gizmo(
  98699. /** The utility layer the gizmo will be added to */
  98700. gizmoLayer) {
  98701. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98702. var _this = this;
  98703. this.gizmoLayer = gizmoLayer;
  98704. /**
  98705. * Ratio for the scale of the gizmo (Default: 1)
  98706. */
  98707. this.scaleRatio = 1;
  98708. this._tmpMatrix = new BABYLON.Matrix();
  98709. /**
  98710. * If a custom mesh has been set (Default: false)
  98711. */
  98712. this._customMeshSet = false;
  98713. /**
  98714. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  98715. */
  98716. this.updateGizmoRotationToMatchAttachedMesh = true;
  98717. /**
  98718. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  98719. */
  98720. this.updateGizmoPositionToMatchAttachedMesh = true;
  98721. /**
  98722. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  98723. */
  98724. this._updateScale = true;
  98725. this._interactionsEnabled = true;
  98726. this._tempVector = new BABYLON.Vector3();
  98727. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  98728. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  98729. _this._update();
  98730. });
  98731. this.attachedMesh = null;
  98732. }
  98733. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  98734. /**
  98735. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  98736. * * When set, interactions will be enabled
  98737. */
  98738. get: function () {
  98739. return this._attachedMesh;
  98740. },
  98741. set: function (value) {
  98742. this._attachedMesh = value;
  98743. this._rootMesh.setEnabled(value ? true : false);
  98744. this._attachedMeshChanged(value);
  98745. },
  98746. enumerable: true,
  98747. configurable: true
  98748. });
  98749. /**
  98750. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  98751. * @param mesh The mesh to replace the default mesh of the gizmo
  98752. */
  98753. Gizmo.prototype.setCustomMesh = function (mesh) {
  98754. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  98755. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  98756. }
  98757. this._rootMesh.getChildMeshes().forEach(function (c) {
  98758. c.dispose();
  98759. });
  98760. mesh.parent = this._rootMesh;
  98761. this._customMeshSet = true;
  98762. };
  98763. Gizmo.prototype._attachedMeshChanged = function (value) {
  98764. };
  98765. /**
  98766. * @hidden
  98767. * Updates the gizmo to match the attached mesh's position/rotation
  98768. */
  98769. Gizmo.prototype._update = function () {
  98770. if (this.attachedMesh) {
  98771. if (this.updateGizmoRotationToMatchAttachedMesh) {
  98772. if (!this._rootMesh.rotationQuaternion) {
  98773. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  98774. }
  98775. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  98776. this._tempVector.copyFrom(this.attachedMesh.scaling);
  98777. if (this.attachedMesh.scaling.x < 0) {
  98778. this.attachedMesh.scaling.x *= -1;
  98779. }
  98780. if (this.attachedMesh.scaling.y < 0) {
  98781. this.attachedMesh.scaling.y *= -1;
  98782. }
  98783. if (this.attachedMesh.scaling.z < 0) {
  98784. this.attachedMesh.scaling.z *= -1;
  98785. }
  98786. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  98787. this.attachedMesh.scaling.copyFrom(this._tempVector);
  98788. this.attachedMesh.computeWorldMatrix();
  98789. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  98790. }
  98791. else if (this._rootMesh.rotationQuaternion) {
  98792. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  98793. }
  98794. if (this.updateGizmoPositionToMatchAttachedMesh) {
  98795. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  98796. }
  98797. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  98798. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  98799. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  98800. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  98801. }
  98802. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  98803. var dist = this._tempVector.length() * this.scaleRatio;
  98804. this._rootMesh.scaling.set(dist, dist, dist);
  98805. }
  98806. }
  98807. };
  98808. /**
  98809. * Disposes of the gizmo
  98810. */
  98811. Gizmo.prototype.dispose = function () {
  98812. this._rootMesh.dispose();
  98813. if (this._beforeRenderObserver) {
  98814. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  98815. }
  98816. };
  98817. return Gizmo;
  98818. }());
  98819. BABYLON.Gizmo = Gizmo;
  98820. })(BABYLON || (BABYLON = {}));
  98821. //# sourceMappingURL=babylon.gizmo.js.map
  98822. var BABYLON;
  98823. (function (BABYLON) {
  98824. /**
  98825. * Single axis drag gizmo
  98826. */
  98827. var AxisDragGizmo = /** @class */ (function (_super) {
  98828. __extends(AxisDragGizmo, _super);
  98829. /**
  98830. * Creates an AxisDragGizmo
  98831. * @param gizmoLayer The utility layer the gizmo will be added to
  98832. * @param dragAxis The axis which the gizmo will be able to drag on
  98833. * @param color The color of the gizmo
  98834. */
  98835. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  98836. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98837. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98838. var _this = _super.call(this, gizmoLayer) || this;
  98839. _this._pointerObserver = null;
  98840. /**
  98841. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98842. */
  98843. _this.snapDistance = 0;
  98844. /**
  98845. * Event that fires each time the gizmo snaps to a new location.
  98846. * * snapDistance is the the change in distance
  98847. */
  98848. _this.onSnapObservable = new BABYLON.Observable();
  98849. // Create Material
  98850. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98851. coloredMaterial.disableLighting = true;
  98852. coloredMaterial.emissiveColor = color;
  98853. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98854. hoverMaterial.disableLighting = true;
  98855. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98856. // Build mesh on root node
  98857. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98858. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  98859. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  98860. arrowTail.color = coloredMaterial.emissiveColor;
  98861. arrow.addChild(arrowMesh);
  98862. arrow.addChild(arrowTail);
  98863. // Position arrow pointing in its drag axis
  98864. arrowMesh.scaling.scaleInPlace(0.05);
  98865. arrowMesh.material = coloredMaterial;
  98866. arrowMesh.rotation.x = Math.PI / 2;
  98867. arrowMesh.position.z += 0.3;
  98868. arrowTail.scaling.scaleInPlace(0.26);
  98869. arrowTail.rotation.x = Math.PI / 2;
  98870. arrowTail.material = coloredMaterial;
  98871. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  98872. arrow.scaling.scaleInPlace(1 / 3);
  98873. _this._rootMesh.addChild(arrow);
  98874. var currentSnapDragDistance = 0;
  98875. var tmpVector = new BABYLON.Vector3();
  98876. var tmpSnapEvent = { snapDistance: 0 };
  98877. // Add drag behavior to handle events when the gizmo is dragged
  98878. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  98879. _this.dragBehavior.moveAttached = false;
  98880. _this._rootMesh.addBehavior(_this.dragBehavior);
  98881. var localDelta = new BABYLON.Vector3();
  98882. var tmpMatrix = new BABYLON.Matrix();
  98883. _this.dragBehavior.onDragObservable.add(function (event) {
  98884. if (_this.attachedMesh) {
  98885. // Convert delta to local translation if it has a parent
  98886. if (_this.attachedMesh.parent) {
  98887. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  98888. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  98889. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  98890. }
  98891. else {
  98892. localDelta.copyFrom(event.delta);
  98893. }
  98894. // Snapping logic
  98895. if (_this.snapDistance == 0) {
  98896. _this.attachedMesh.position.addInPlace(localDelta);
  98897. }
  98898. else {
  98899. currentSnapDragDistance += event.dragDistance;
  98900. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  98901. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  98902. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  98903. localDelta.normalizeToRef(tmpVector);
  98904. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  98905. _this.attachedMesh.position.addInPlace(tmpVector);
  98906. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  98907. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  98908. }
  98909. }
  98910. }
  98911. });
  98912. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  98913. if (_this._customMeshSet) {
  98914. return;
  98915. }
  98916. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  98917. var material = isHovered ? hoverMaterial : coloredMaterial;
  98918. _this._rootMesh.getChildMeshes().forEach(function (m) {
  98919. m.material = material;
  98920. if (m.color) {
  98921. m.color = material.emissiveColor;
  98922. }
  98923. });
  98924. });
  98925. return _this;
  98926. }
  98927. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  98928. if (this.dragBehavior) {
  98929. this.dragBehavior.enabled = value ? true : false;
  98930. }
  98931. };
  98932. /**
  98933. * Disposes of the gizmo
  98934. */
  98935. AxisDragGizmo.prototype.dispose = function () {
  98936. this.onSnapObservable.clear();
  98937. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  98938. this.dragBehavior.detach();
  98939. _super.prototype.dispose.call(this);
  98940. };
  98941. return AxisDragGizmo;
  98942. }(BABYLON.Gizmo));
  98943. BABYLON.AxisDragGizmo = AxisDragGizmo;
  98944. })(BABYLON || (BABYLON = {}));
  98945. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  98946. var BABYLON;
  98947. (function (BABYLON) {
  98948. /**
  98949. * Single axis scale gizmo
  98950. */
  98951. var AxisScaleGizmo = /** @class */ (function (_super) {
  98952. __extends(AxisScaleGizmo, _super);
  98953. /**
  98954. * Creates an AxisScaleGizmo
  98955. * @param gizmoLayer The utility layer the gizmo will be added to
  98956. * @param dragAxis The axis which the gizmo will be able to scale on
  98957. * @param color The color of the gizmo
  98958. */
  98959. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  98960. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98961. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98962. var _this = _super.call(this, gizmoLayer) || this;
  98963. _this._pointerObserver = null;
  98964. /**
  98965. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98966. */
  98967. _this.snapDistance = 0;
  98968. /**
  98969. * Event that fires each time the gizmo snaps to a new location.
  98970. * * snapDistance is the the change in distance
  98971. */
  98972. _this.onSnapObservable = new BABYLON.Observable();
  98973. /**
  98974. * If the scaling operation should be done on all axis (default: false)
  98975. */
  98976. _this.uniformScaling = false;
  98977. // Create Material
  98978. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98979. _this._coloredMaterial.disableLighting = true;
  98980. _this._coloredMaterial.emissiveColor = color;
  98981. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98982. hoverMaterial.disableLighting = true;
  98983. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98984. // Build mesh on root node
  98985. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98986. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  98987. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  98988. arrowTail.color = _this._coloredMaterial.emissiveColor;
  98989. arrow.addChild(arrowMesh);
  98990. arrow.addChild(arrowTail);
  98991. // Position arrow pointing in its drag axis
  98992. arrowMesh.scaling.scaleInPlace(0.1);
  98993. arrowMesh.material = _this._coloredMaterial;
  98994. arrowMesh.rotation.x = Math.PI / 2;
  98995. arrowMesh.position.z += 0.3;
  98996. arrowTail.scaling.scaleInPlace(0.26);
  98997. arrowTail.rotation.x = Math.PI / 2;
  98998. arrowTail.material = _this._coloredMaterial;
  98999. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  99000. _this._rootMesh.addChild(arrow);
  99001. arrow.scaling.scaleInPlace(1 / 3);
  99002. // Add drag behavior to handle events when the gizmo is dragged
  99003. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  99004. _this.dragBehavior.moveAttached = false;
  99005. _this._rootMesh.addBehavior(_this.dragBehavior);
  99006. var currentSnapDragDistance = 0;
  99007. var tmpVector = new BABYLON.Vector3();
  99008. var tmpSnapEvent = { snapDistance: 0 };
  99009. _this.dragBehavior.onDragObservable.add(function (event) {
  99010. if (_this.attachedMesh) {
  99011. // Snapping logic
  99012. var snapped = false;
  99013. var dragSteps = 0;
  99014. if (_this.uniformScaling) {
  99015. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  99016. if (tmpVector.y < 0) {
  99017. tmpVector.scaleInPlace(-1);
  99018. }
  99019. }
  99020. else {
  99021. tmpVector.copyFrom(dragAxis);
  99022. }
  99023. if (_this.snapDistance == 0) {
  99024. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  99025. }
  99026. else {
  99027. currentSnapDragDistance += event.dragDistance;
  99028. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  99029. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  99030. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  99031. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  99032. snapped = true;
  99033. }
  99034. else {
  99035. tmpVector.scaleInPlace(0);
  99036. }
  99037. }
  99038. _this.attachedMesh.scaling.addInPlace(tmpVector);
  99039. if (snapped) {
  99040. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  99041. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  99042. }
  99043. }
  99044. });
  99045. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99046. if (_this._customMeshSet) {
  99047. return;
  99048. }
  99049. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  99050. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  99051. _this._rootMesh.getChildMeshes().forEach(function (m) {
  99052. m.material = material;
  99053. if (m.color) {
  99054. m.color = material.emissiveColor;
  99055. }
  99056. });
  99057. });
  99058. return _this;
  99059. }
  99060. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  99061. if (this.dragBehavior) {
  99062. this.dragBehavior.enabled = value ? true : false;
  99063. }
  99064. };
  99065. /**
  99066. * Disposes of the gizmo
  99067. */
  99068. AxisScaleGizmo.prototype.dispose = function () {
  99069. this.onSnapObservable.clear();
  99070. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  99071. this.dragBehavior.detach();
  99072. _super.prototype.dispose.call(this);
  99073. };
  99074. /**
  99075. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  99076. * @param mesh The mesh to replace the default mesh of the gizmo
  99077. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  99078. */
  99079. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  99080. var _this = this;
  99081. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  99082. _super.prototype.setCustomMesh.call(this, mesh);
  99083. if (useGizmoMaterial) {
  99084. this._rootMesh.getChildMeshes().forEach(function (m) {
  99085. m.material = _this._coloredMaterial;
  99086. if (m.color) {
  99087. m.color = _this._coloredMaterial.emissiveColor;
  99088. }
  99089. });
  99090. this._customMeshSet = false;
  99091. }
  99092. };
  99093. return AxisScaleGizmo;
  99094. }(BABYLON.Gizmo));
  99095. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  99096. })(BABYLON || (BABYLON = {}));
  99097. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  99098. var BABYLON;
  99099. (function (BABYLON) {
  99100. /**
  99101. * Single plane rotation gizmo
  99102. */
  99103. var PlaneRotationGizmo = /** @class */ (function (_super) {
  99104. __extends(PlaneRotationGizmo, _super);
  99105. /**
  99106. * Creates a PlaneRotationGizmo
  99107. * @param gizmoLayer The utility layer the gizmo will be added to
  99108. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  99109. * @param color The color of the gizmo
  99110. */
  99111. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  99112. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  99113. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99114. var _this = _super.call(this, gizmoLayer) || this;
  99115. _this._pointerObserver = null;
  99116. /**
  99117. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  99118. */
  99119. _this.snapDistance = 0;
  99120. /**
  99121. * Event that fires each time the gizmo snaps to a new location.
  99122. * * snapDistance is the the change in distance
  99123. */
  99124. _this.onSnapObservable = new BABYLON.Observable();
  99125. // Create Material
  99126. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99127. coloredMaterial.disableLighting = true;
  99128. coloredMaterial.emissiveColor = color;
  99129. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99130. hoverMaterial.disableLighting = true;
  99131. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  99132. // Build mesh on root node
  99133. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99134. // Create circle out of lines
  99135. var tessellation = 20;
  99136. var radius = 0.8;
  99137. var points = new Array();
  99138. for (var i = 0; i < tessellation; i++) {
  99139. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  99140. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  99141. }
  99142. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  99143. rotationMesh.color = coloredMaterial.emissiveColor;
  99144. // Position arrow pointing in its drag axis
  99145. rotationMesh.scaling.scaleInPlace(0.26);
  99146. rotationMesh.material = coloredMaterial;
  99147. rotationMesh.rotation.x = Math.PI / 2;
  99148. parentMesh.addChild(rotationMesh);
  99149. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  99150. _this._rootMesh.addChild(parentMesh);
  99151. parentMesh.scaling.scaleInPlace(1 / 3);
  99152. // Add drag behavior to handle events when the gizmo is dragged
  99153. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  99154. _this.dragBehavior.moveAttached = false;
  99155. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  99156. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  99157. _this._rootMesh.addBehavior(_this.dragBehavior);
  99158. var lastDragPosition = new BABYLON.Vector3();
  99159. _this.dragBehavior.onDragStartObservable.add(function (e) {
  99160. if (_this.attachedMesh) {
  99161. lastDragPosition.copyFrom(e.dragPlanePoint);
  99162. }
  99163. });
  99164. var rotationMatrix = new BABYLON.Matrix();
  99165. var planeNormalTowardsCamera = new BABYLON.Vector3();
  99166. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  99167. var tmpSnapEvent = { snapDistance: 0 };
  99168. var currentSnapDragDistance = 0;
  99169. var tmpMatrix = new BABYLON.Matrix();
  99170. var tmpVector = new BABYLON.Vector3();
  99171. var amountToRotate = new BABYLON.Quaternion();
  99172. _this.dragBehavior.onDragObservable.add(function (event) {
  99173. if (_this.attachedMesh) {
  99174. if (!_this.attachedMesh.rotationQuaternion) {
  99175. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  99176. }
  99177. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  99178. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  99179. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  99180. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  99181. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  99182. var angle = Math.atan2(cross.length(), dot);
  99183. planeNormalTowardsCamera.copyFrom(planeNormal);
  99184. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  99185. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  99186. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  99187. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  99188. }
  99189. // Flip up vector depending on which side the camera is on
  99190. if (gizmoLayer.utilityLayerScene.activeCamera) {
  99191. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  99192. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  99193. planeNormalTowardsCamera.scaleInPlace(-1);
  99194. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  99195. }
  99196. }
  99197. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  99198. if (halfCircleSide)
  99199. angle = -angle;
  99200. // Snapping logic
  99201. var snapped = false;
  99202. if (_this.snapDistance != 0) {
  99203. currentSnapDragDistance += angle;
  99204. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  99205. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  99206. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  99207. angle = _this.snapDistance * dragSteps;
  99208. snapped = true;
  99209. }
  99210. else {
  99211. angle = 0;
  99212. }
  99213. }
  99214. // If the mesh has a parent, convert needed world rotation to local rotation
  99215. tmpMatrix.reset();
  99216. if (_this.attachedMesh.parent) {
  99217. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  99218. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  99219. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  99220. }
  99221. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  99222. var quaternionCoefficient = Math.sin(angle / 2);
  99223. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  99224. // 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
  99225. if (tmpMatrix.determinant() > 0) {
  99226. amountToRotate.toEulerAnglesToRef(tmpVector);
  99227. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  99228. }
  99229. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  99230. // Rotate selected mesh quaternion over fixed axis
  99231. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  99232. }
  99233. else {
  99234. // Rotate selected mesh quaternion over rotated axis
  99235. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  99236. }
  99237. lastDragPosition.copyFrom(event.dragPlanePoint);
  99238. if (snapped) {
  99239. tmpSnapEvent.snapDistance = angle;
  99240. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  99241. }
  99242. }
  99243. });
  99244. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99245. if (_this._customMeshSet) {
  99246. return;
  99247. }
  99248. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  99249. var material = isHovered ? hoverMaterial : coloredMaterial;
  99250. _this._rootMesh.getChildMeshes().forEach(function (m) {
  99251. m.material = material;
  99252. if (m.color) {
  99253. m.color = material.emissiveColor;
  99254. }
  99255. });
  99256. });
  99257. return _this;
  99258. }
  99259. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  99260. if (this.dragBehavior) {
  99261. this.dragBehavior.enabled = value ? true : false;
  99262. }
  99263. };
  99264. /**
  99265. * Disposes of the gizmo
  99266. */
  99267. PlaneRotationGizmo.prototype.dispose = function () {
  99268. this.onSnapObservable.clear();
  99269. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  99270. this.dragBehavior.detach();
  99271. _super.prototype.dispose.call(this);
  99272. };
  99273. return PlaneRotationGizmo;
  99274. }(BABYLON.Gizmo));
  99275. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  99276. })(BABYLON || (BABYLON = {}));
  99277. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  99278. var BABYLON;
  99279. (function (BABYLON) {
  99280. /**
  99281. * Gizmo that enables dragging a mesh along 3 axis
  99282. */
  99283. var PositionGizmo = /** @class */ (function (_super) {
  99284. __extends(PositionGizmo, _super);
  99285. /**
  99286. * Creates a PositionGizmo
  99287. * @param gizmoLayer The utility layer the gizmo will be added to
  99288. */
  99289. function PositionGizmo(gizmoLayer) {
  99290. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99291. var _this = _super.call(this, gizmoLayer) || this;
  99292. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  99293. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  99294. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  99295. _this.attachedMesh = null;
  99296. return _this;
  99297. }
  99298. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  99299. set: function (mesh) {
  99300. if (this.xGizmo) {
  99301. this.xGizmo.attachedMesh = mesh;
  99302. this.yGizmo.attachedMesh = mesh;
  99303. this.zGizmo.attachedMesh = mesh;
  99304. }
  99305. },
  99306. enumerable: true,
  99307. configurable: true
  99308. });
  99309. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  99310. get: function () {
  99311. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  99312. },
  99313. set: function (value) {
  99314. if (this.xGizmo) {
  99315. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99316. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99317. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99318. }
  99319. },
  99320. enumerable: true,
  99321. configurable: true
  99322. });
  99323. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  99324. get: function () {
  99325. return this.xGizmo.snapDistance;
  99326. },
  99327. /**
  99328. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99329. */
  99330. set: function (value) {
  99331. if (this.xGizmo) {
  99332. this.xGizmo.snapDistance = value;
  99333. this.yGizmo.snapDistance = value;
  99334. this.zGizmo.snapDistance = value;
  99335. }
  99336. },
  99337. enumerable: true,
  99338. configurable: true
  99339. });
  99340. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  99341. get: function () {
  99342. return this.xGizmo.scaleRatio;
  99343. },
  99344. /**
  99345. * Ratio for the scale of the gizmo (Default: 1)
  99346. */
  99347. set: function (value) {
  99348. if (this.xGizmo) {
  99349. this.xGizmo.scaleRatio = value;
  99350. this.yGizmo.scaleRatio = value;
  99351. this.zGizmo.scaleRatio = value;
  99352. }
  99353. },
  99354. enumerable: true,
  99355. configurable: true
  99356. });
  99357. /**
  99358. * Disposes of the gizmo
  99359. */
  99360. PositionGizmo.prototype.dispose = function () {
  99361. this.xGizmo.dispose();
  99362. this.yGizmo.dispose();
  99363. this.zGizmo.dispose();
  99364. };
  99365. /**
  99366. * CustomMeshes are not supported by this gizmo
  99367. * @param mesh The mesh to replace the default mesh of the gizmo
  99368. */
  99369. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  99370. 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)");
  99371. };
  99372. return PositionGizmo;
  99373. }(BABYLON.Gizmo));
  99374. BABYLON.PositionGizmo = PositionGizmo;
  99375. })(BABYLON || (BABYLON = {}));
  99376. //# sourceMappingURL=babylon.positionGizmo.js.map
  99377. var BABYLON;
  99378. (function (BABYLON) {
  99379. /**
  99380. * Gizmo that enables rotating a mesh along 3 axis
  99381. */
  99382. var RotationGizmo = /** @class */ (function (_super) {
  99383. __extends(RotationGizmo, _super);
  99384. /**
  99385. * Creates a RotationGizmo
  99386. * @param gizmoLayer The utility layer the gizmo will be added to
  99387. */
  99388. function RotationGizmo(gizmoLayer) {
  99389. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99390. var _this = _super.call(this, gizmoLayer) || this;
  99391. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  99392. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  99393. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  99394. _this.attachedMesh = null;
  99395. return _this;
  99396. }
  99397. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  99398. set: function (mesh) {
  99399. if (this.xGizmo) {
  99400. this.xGizmo.attachedMesh = mesh;
  99401. this.yGizmo.attachedMesh = mesh;
  99402. this.zGizmo.attachedMesh = mesh;
  99403. }
  99404. },
  99405. enumerable: true,
  99406. configurable: true
  99407. });
  99408. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  99409. get: function () {
  99410. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  99411. },
  99412. set: function (value) {
  99413. if (this.xGizmo) {
  99414. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99415. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99416. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99417. }
  99418. },
  99419. enumerable: true,
  99420. configurable: true
  99421. });
  99422. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  99423. get: function () {
  99424. return this.xGizmo.snapDistance;
  99425. },
  99426. /**
  99427. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99428. */
  99429. set: function (value) {
  99430. if (this.xGizmo) {
  99431. this.xGizmo.snapDistance = value;
  99432. this.yGizmo.snapDistance = value;
  99433. this.zGizmo.snapDistance = value;
  99434. }
  99435. },
  99436. enumerable: true,
  99437. configurable: true
  99438. });
  99439. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  99440. get: function () {
  99441. return this.xGizmo.scaleRatio;
  99442. },
  99443. /**
  99444. * Ratio for the scale of the gizmo (Default: 1)
  99445. */
  99446. set: function (value) {
  99447. if (this.xGizmo) {
  99448. this.xGizmo.scaleRatio = value;
  99449. this.yGizmo.scaleRatio = value;
  99450. this.zGizmo.scaleRatio = value;
  99451. }
  99452. },
  99453. enumerable: true,
  99454. configurable: true
  99455. });
  99456. /**
  99457. * Disposes of the gizmo
  99458. */
  99459. RotationGizmo.prototype.dispose = function () {
  99460. this.xGizmo.dispose();
  99461. this.yGizmo.dispose();
  99462. this.zGizmo.dispose();
  99463. };
  99464. /**
  99465. * CustomMeshes are not supported by this gizmo
  99466. * @param mesh The mesh to replace the default mesh of the gizmo
  99467. */
  99468. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  99469. 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)");
  99470. };
  99471. return RotationGizmo;
  99472. }(BABYLON.Gizmo));
  99473. BABYLON.RotationGizmo = RotationGizmo;
  99474. })(BABYLON || (BABYLON = {}));
  99475. //# sourceMappingURL=babylon.rotationGizmo.js.map
  99476. var BABYLON;
  99477. (function (BABYLON) {
  99478. /**
  99479. * Gizmo that enables scaling a mesh along 3 axis
  99480. */
  99481. var ScaleGizmo = /** @class */ (function (_super) {
  99482. __extends(ScaleGizmo, _super);
  99483. /**
  99484. * Creates a ScaleGizmo
  99485. * @param gizmoLayer The utility layer the gizmo will be added to
  99486. */
  99487. function ScaleGizmo(gizmoLayer) {
  99488. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99489. var _this = _super.call(this, gizmoLayer) || this;
  99490. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  99491. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  99492. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  99493. // Create uniform scale gizmo
  99494. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  99495. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  99496. _this.uniformScaleGizmo.uniformScaling = true;
  99497. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  99498. octahedron.scaling.scaleInPlace(0.007);
  99499. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  99500. _this.attachedMesh = null;
  99501. return _this;
  99502. }
  99503. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  99504. set: function (mesh) {
  99505. if (this.xGizmo) {
  99506. this.xGizmo.attachedMesh = mesh;
  99507. this.yGizmo.attachedMesh = mesh;
  99508. this.zGizmo.attachedMesh = mesh;
  99509. this.uniformScaleGizmo.attachedMesh = mesh;
  99510. }
  99511. },
  99512. enumerable: true,
  99513. configurable: true
  99514. });
  99515. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  99516. get: function () {
  99517. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  99518. },
  99519. set: function (value) {
  99520. if (this.xGizmo) {
  99521. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99522. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99523. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99524. }
  99525. },
  99526. enumerable: true,
  99527. configurable: true
  99528. });
  99529. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  99530. get: function () {
  99531. return this.xGizmo.snapDistance;
  99532. },
  99533. /**
  99534. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99535. */
  99536. set: function (value) {
  99537. if (this.xGizmo) {
  99538. this.xGizmo.snapDistance = value;
  99539. this.yGizmo.snapDistance = value;
  99540. this.zGizmo.snapDistance = value;
  99541. this.uniformScaleGizmo.snapDistance = value;
  99542. }
  99543. },
  99544. enumerable: true,
  99545. configurable: true
  99546. });
  99547. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  99548. get: function () {
  99549. return this.xGizmo.scaleRatio;
  99550. },
  99551. /**
  99552. * Ratio for the scale of the gizmo (Default: 1)
  99553. */
  99554. set: function (value) {
  99555. if (this.xGizmo) {
  99556. this.xGizmo.scaleRatio = value;
  99557. this.yGizmo.scaleRatio = value;
  99558. this.zGizmo.scaleRatio = value;
  99559. this.uniformScaleGizmo.scaleRatio = value;
  99560. }
  99561. },
  99562. enumerable: true,
  99563. configurable: true
  99564. });
  99565. /**
  99566. * Disposes of the gizmo
  99567. */
  99568. ScaleGizmo.prototype.dispose = function () {
  99569. this.xGizmo.dispose();
  99570. this.yGizmo.dispose();
  99571. this.zGizmo.dispose();
  99572. this.uniformScaleGizmo.dispose();
  99573. };
  99574. return ScaleGizmo;
  99575. }(BABYLON.Gizmo));
  99576. BABYLON.ScaleGizmo = ScaleGizmo;
  99577. })(BABYLON || (BABYLON = {}));
  99578. //# sourceMappingURL=babylon.scaleGizmo.js.map
  99579. var BABYLON;
  99580. (function (BABYLON) {
  99581. /**
  99582. * Bounding box gizmo
  99583. */
  99584. var BoundingBoxGizmo = /** @class */ (function (_super) {
  99585. __extends(BoundingBoxGizmo, _super);
  99586. /**
  99587. * Creates an BoundingBoxGizmo
  99588. * @param gizmoLayer The utility layer the gizmo will be added to
  99589. * @param color The color of the gizmo
  99590. */
  99591. function BoundingBoxGizmo(color, gizmoLayer) {
  99592. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  99593. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  99594. var _this = _super.call(this, gizmoLayer) || this;
  99595. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  99596. _this._renderObserver = null;
  99597. _this._pointerObserver = null;
  99598. _this._scaleDragSpeed = 0.2;
  99599. _this._tmpQuaternion = new BABYLON.Quaternion();
  99600. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  99601. _this._tmpRotationMatrix = new BABYLON.Matrix();
  99602. /**
  99603. * 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)
  99604. */
  99605. _this.ignoreChildren = false;
  99606. /**
  99607. * 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)
  99608. */
  99609. _this.includeChildPredicate = null;
  99610. /**
  99611. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  99612. */
  99613. _this.rotationSphereSize = 0.1;
  99614. /**
  99615. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  99616. */
  99617. _this.scaleBoxSize = 0.1;
  99618. /**
  99619. * 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)
  99620. */
  99621. _this.fixedDragMeshScreenSize = false;
  99622. /**
  99623. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  99624. */
  99625. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  99626. /**
  99627. * Fired when a rotation sphere or scale box is dragged
  99628. */
  99629. _this.onDragStartObservable = new BABYLON.Observable();
  99630. /**
  99631. * Fired when a scale box is dragged
  99632. */
  99633. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  99634. /**
  99635. * Fired when a scale box drag is ended
  99636. */
  99637. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  99638. /**
  99639. * Fired when a rotation sphere is dragged
  99640. */
  99641. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  99642. /**
  99643. * Fired when a rotation sphere drag is ended
  99644. */
  99645. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  99646. /**
  99647. * 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)
  99648. */
  99649. _this.scalePivot = null;
  99650. _this._existingMeshScale = new BABYLON.Vector3();
  99651. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  99652. _this._updateScale = false;
  99653. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  99654. // Create Materials
  99655. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99656. coloredMaterial.disableLighting = true;
  99657. coloredMaterial.emissiveColor = color;
  99658. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99659. hoverColoredMaterial.disableLighting = true;
  99660. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  99661. // Build bounding box out of lines
  99662. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99663. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  99664. var lines = [];
  99665. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  99666. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  99667. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  99668. 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));
  99669. 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));
  99670. 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));
  99671. 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));
  99672. 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));
  99673. 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));
  99674. 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));
  99675. 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));
  99676. 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));
  99677. lines.forEach(function (l) {
  99678. l.color = color;
  99679. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  99680. l.isPickable = false;
  99681. _this._lineBoundingBox.addChild(l);
  99682. });
  99683. _this._rootMesh.addChild(_this._lineBoundingBox);
  99684. // Create rotation spheres
  99685. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99686. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  99687. var _loop_1 = function (i_1) {
  99688. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  99689. sphere.rotationQuaternion = new BABYLON.Quaternion();
  99690. sphere.material = coloredMaterial;
  99691. // Drag behavior
  99692. _dragBehavior = new BABYLON.PointerDragBehavior({});
  99693. _dragBehavior.moveAttached = false;
  99694. _dragBehavior.updateDragPlane = false;
  99695. sphere.addBehavior(_dragBehavior);
  99696. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  99697. var totalTurnAmountOfDrag = 0;
  99698. _dragBehavior.onDragStartObservable.add(function (event) {
  99699. startingTurnDirection.copyFrom(sphere.forward);
  99700. totalTurnAmountOfDrag = 0;
  99701. });
  99702. _dragBehavior.onDragObservable.add(function (event) {
  99703. _this.onRotationSphereDragObservable.notifyObservers({});
  99704. if (_this.attachedMesh) {
  99705. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  99706. var worldDragDirection = startingTurnDirection;
  99707. // Project the world right on to the drag plane
  99708. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  99709. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  99710. // project drag delta on to the resulting drag axis and rotate based on that
  99711. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  99712. // Make rotation relative to size of mesh.
  99713. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  99714. // Rotate based on axis
  99715. if (!_this.attachedMesh.rotationQuaternion) {
  99716. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  99717. }
  99718. if (!_this._anchorMesh.rotationQuaternion) {
  99719. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  99720. }
  99721. // Do not allow the object to turn more than a full circle
  99722. totalTurnAmountOfDrag += projectDist;
  99723. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  99724. if (i_1 >= 8) {
  99725. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  99726. }
  99727. else if (i_1 >= 4) {
  99728. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  99729. }
  99730. else {
  99731. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  99732. }
  99733. // Rotate around center of bounding box
  99734. _this._anchorMesh.addChild(_this.attachedMesh);
  99735. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  99736. _this._anchorMesh.removeChild(_this.attachedMesh);
  99737. }
  99738. _this.updateBoundingBox();
  99739. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  99740. }
  99741. });
  99742. // Selection/deselection
  99743. _dragBehavior.onDragStartObservable.add(function () {
  99744. _this.onDragStartObservable.notifyObservers({});
  99745. _this._selectNode(sphere);
  99746. });
  99747. _dragBehavior.onDragEndObservable.add(function () {
  99748. _this.onRotationSphereDragEndObservable.notifyObservers({});
  99749. _this._selectNode(null);
  99750. });
  99751. this_1._rotateSpheresParent.addChild(sphere);
  99752. };
  99753. var this_1 = this, _dragBehavior;
  99754. for (var i_1 = 0; i_1 < 12; i_1++) {
  99755. _loop_1(i_1);
  99756. }
  99757. _this._rootMesh.addChild(_this._rotateSpheresParent);
  99758. // Create scale cubes
  99759. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99760. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  99761. for (var i = 0; i < 2; i++) {
  99762. for (var j = 0; j < 2; j++) {
  99763. var _loop_2 = function () {
  99764. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  99765. box.material = coloredMaterial;
  99766. // Dragging logic
  99767. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  99768. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  99769. _dragBehavior.moveAttached = false;
  99770. box.addBehavior(_dragBehavior);
  99771. _dragBehavior.onDragObservable.add(function (event) {
  99772. _this.onScaleBoxDragObservable.notifyObservers({});
  99773. if (_this.attachedMesh) {
  99774. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  99775. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  99776. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  99777. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  99778. _this.updateBoundingBox();
  99779. if (_this.scalePivot) {
  99780. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  99781. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  99782. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  99783. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  99784. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  99785. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  99786. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  99787. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  99788. }
  99789. else {
  99790. // Scale from the position of the opposite corner
  99791. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  99792. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  99793. }
  99794. _this._anchorMesh.addChild(_this.attachedMesh);
  99795. _this._anchorMesh.scaling.addInPlace(deltaScale);
  99796. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  99797. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  99798. }
  99799. _this._anchorMesh.removeChild(_this.attachedMesh);
  99800. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  99801. }
  99802. });
  99803. // Selection/deselection
  99804. _dragBehavior.onDragStartObservable.add(function () {
  99805. _this.onDragStartObservable.notifyObservers({});
  99806. _this._selectNode(box);
  99807. });
  99808. _dragBehavior.onDragEndObservable.add(function () {
  99809. _this.onScaleBoxDragEndObservable.notifyObservers({});
  99810. _this._selectNode(null);
  99811. });
  99812. this_2._scaleBoxesParent.addChild(box);
  99813. };
  99814. var this_2 = this, _dragBehavior;
  99815. for (var k = 0; k < 2; k++) {
  99816. _loop_2();
  99817. }
  99818. }
  99819. }
  99820. _this._rootMesh.addChild(_this._scaleBoxesParent);
  99821. // Hover color change
  99822. var pointerIds = new Array();
  99823. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99824. if (!pointerIds[pointerInfo.event.pointerId]) {
  99825. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  99826. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  99827. pointerIds[pointerInfo.event.pointerId] = mesh;
  99828. mesh.material = hoverColoredMaterial;
  99829. }
  99830. });
  99831. }
  99832. else {
  99833. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  99834. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  99835. delete pointerIds[pointerInfo.event.pointerId];
  99836. }
  99837. }
  99838. });
  99839. // Update bounding box positions
  99840. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  99841. // Only update the bouding box if scaling has changed
  99842. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  99843. _this.updateBoundingBox();
  99844. }
  99845. });
  99846. _this.updateBoundingBox();
  99847. return _this;
  99848. }
  99849. /** @hidden */
  99850. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  99851. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  99852. // Save old pivot and set pivot to 0,0,0
  99853. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  99854. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  99855. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  99856. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  99857. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  99858. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  99859. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  99860. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  99861. }
  99862. }
  99863. BoundingBoxGizmo._PivotCached++;
  99864. };
  99865. /** @hidden */
  99866. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  99867. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  99868. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  99869. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  99870. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  99871. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  99872. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  99873. }
  99874. this._PivotCached--;
  99875. };
  99876. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  99877. if (value) {
  99878. // Reset anchor mesh to match attached mesh's scale
  99879. // This is needed to avoid invalid box/sphere position on first drag
  99880. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  99881. this._anchorMesh.addChild(value);
  99882. this._anchorMesh.removeChild(value);
  99883. BoundingBoxGizmo._RestorePivotPoint(value);
  99884. this.updateBoundingBox();
  99885. }
  99886. };
  99887. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  99888. this._rotateSpheresParent.getChildMeshes()
  99889. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  99890. m.isVisible = (!selectedMesh || m == selectedMesh);
  99891. });
  99892. };
  99893. /**
  99894. * Updates the bounding box information for the Gizmo
  99895. */
  99896. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  99897. if (this.attachedMesh) {
  99898. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  99899. this._update();
  99900. // Rotate based on axis
  99901. if (!this.attachedMesh.rotationQuaternion) {
  99902. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  99903. }
  99904. if (!this._anchorMesh.rotationQuaternion) {
  99905. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  99906. }
  99907. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  99908. // Store original position and reset mesh to origin before computing the bounding box
  99909. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  99910. this._tmpVector.copyFrom(this.attachedMesh.position);
  99911. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  99912. this.attachedMesh.position.set(0, 0, 0);
  99913. // Update bounding dimensions/positions
  99914. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  99915. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  99916. // Update gizmo to match bounding box scaling and rotation
  99917. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  99918. 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);
  99919. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  99920. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  99921. this._lineBoundingBox.computeWorldMatrix();
  99922. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  99923. // restore position/rotation values
  99924. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  99925. this.attachedMesh.position.copyFrom(this._tmpVector);
  99926. }
  99927. // Update rotation sphere locations
  99928. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  99929. for (var i = 0; i < 3; i++) {
  99930. for (var j = 0; j < 2; j++) {
  99931. for (var k = 0; k < 2; k++) {
  99932. var index = ((i * 4) + (j * 2)) + k;
  99933. if (i == 0) {
  99934. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  99935. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99936. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99937. }
  99938. if (i == 1) {
  99939. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  99940. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99941. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99942. }
  99943. if (i == 2) {
  99944. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  99945. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99946. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99947. }
  99948. if (this.fixedDragMeshScreenSize) {
  99949. this._rootMesh.computeWorldMatrix();
  99950. this._rotateSpheresParent.computeWorldMatrix();
  99951. rotateSpheres[index].computeWorldMatrix();
  99952. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  99953. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  99954. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  99955. }
  99956. else {
  99957. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  99958. }
  99959. }
  99960. }
  99961. }
  99962. // Update scale box locations
  99963. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  99964. for (var i = 0; i < 2; i++) {
  99965. for (var j = 0; j < 2; j++) {
  99966. for (var k = 0; k < 2; k++) {
  99967. var index = ((i * 4) + (j * 2)) + k;
  99968. if (scaleBoxes[index]) {
  99969. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  99970. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99971. if (this.fixedDragMeshScreenSize) {
  99972. this._rootMesh.computeWorldMatrix();
  99973. this._scaleBoxesParent.computeWorldMatrix();
  99974. scaleBoxes[index].computeWorldMatrix();
  99975. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  99976. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  99977. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  99978. }
  99979. else {
  99980. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  99981. }
  99982. }
  99983. }
  99984. }
  99985. }
  99986. if (this.attachedMesh) {
  99987. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  99988. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  99989. }
  99990. };
  99991. /**
  99992. * Enables rotation on the specified axis and disables rotation on the others
  99993. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  99994. */
  99995. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  99996. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  99997. if (i < 4) {
  99998. m.setEnabled(axis.indexOf("x") != -1);
  99999. }
  100000. else if (i < 8) {
  100001. m.setEnabled(axis.indexOf("y") != -1);
  100002. }
  100003. else {
  100004. m.setEnabled(axis.indexOf("z") != -1);
  100005. }
  100006. });
  100007. };
  100008. /**
  100009. * Disposes of the gizmo
  100010. */
  100011. BoundingBoxGizmo.prototype.dispose = function () {
  100012. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100013. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  100014. this._lineBoundingBox.dispose();
  100015. this._rotateSpheresParent.dispose();
  100016. this._scaleBoxesParent.dispose();
  100017. _super.prototype.dispose.call(this);
  100018. };
  100019. /**
  100020. * 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)
  100021. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  100022. * @returns the bounding box mesh with the passed in mesh as a child
  100023. */
  100024. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  100025. var makeNotPickable = function (root) {
  100026. root.isPickable = false;
  100027. root.getChildMeshes().forEach(function (c) {
  100028. makeNotPickable(c);
  100029. });
  100030. };
  100031. makeNotPickable(mesh);
  100032. // Reset position to get boudning box from origin with no rotation
  100033. if (!mesh.rotationQuaternion) {
  100034. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  100035. }
  100036. var oldPos = mesh.position.clone();
  100037. var oldRot = mesh.rotationQuaternion.clone();
  100038. mesh.rotationQuaternion.set(0, 0, 0, 1);
  100039. mesh.position.set(0, 0, 0);
  100040. // Update bounding dimensions/positions
  100041. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  100042. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  100043. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  100044. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  100045. // Restore original positions
  100046. mesh.addChild(box);
  100047. mesh.rotationQuaternion.copyFrom(oldRot);
  100048. mesh.position.copyFrom(oldPos);
  100049. // Reverse parenting
  100050. mesh.removeChild(box);
  100051. box.addChild(mesh);
  100052. box.visibility = 0;
  100053. return box;
  100054. };
  100055. /**
  100056. * CustomMeshes are not supported by this gizmo
  100057. * @param mesh The mesh to replace the default mesh of the gizmo
  100058. */
  100059. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  100060. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  100061. };
  100062. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  100063. // store/remove pivot point should only be applied during their outermost calls
  100064. BoundingBoxGizmo._PivotCached = 0;
  100065. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  100066. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  100067. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  100068. return BoundingBoxGizmo;
  100069. }(BABYLON.Gizmo));
  100070. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  100071. })(BABYLON || (BABYLON = {}));
  100072. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  100073. var BABYLON;
  100074. (function (BABYLON) {
  100075. /**
  100076. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  100077. */
  100078. var GizmoManager = /** @class */ (function () {
  100079. /**
  100080. * Instatiates a gizmo manager
  100081. * @param scene the scene to overlay the gizmos on top of
  100082. */
  100083. function GizmoManager(scene) {
  100084. var _this = this;
  100085. this.scene = scene;
  100086. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  100087. this._pointerObserver = null;
  100088. this._attachedMesh = null;
  100089. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  100090. /**
  100091. * When bounding box gizmo is enabled, this can be used to track drag/end events
  100092. */
  100093. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  100094. /**
  100095. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  100096. */
  100097. this.attachableMeshes = null;
  100098. /**
  100099. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  100100. */
  100101. this.usePointerToAttachGizmos = true;
  100102. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  100103. // Instatiate/dispose gizmos based on pointer actions
  100104. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  100105. if (!_this.usePointerToAttachGizmos) {
  100106. return;
  100107. }
  100108. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  100109. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  100110. var node = pointerInfo.pickInfo.pickedMesh;
  100111. if (_this.attachableMeshes == null) {
  100112. // Attach to the most parent node
  100113. while (node && node.parent != null) {
  100114. node = node.parent;
  100115. }
  100116. }
  100117. else {
  100118. // Attach to the parent node that is an attachableMesh
  100119. var found = false;
  100120. _this.attachableMeshes.forEach(function (mesh) {
  100121. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  100122. node = mesh;
  100123. found = true;
  100124. }
  100125. });
  100126. if (!found) {
  100127. node = null;
  100128. }
  100129. }
  100130. if (node instanceof BABYLON.AbstractMesh) {
  100131. _this.attachToMesh(node);
  100132. }
  100133. else {
  100134. _this.attachToMesh(null);
  100135. }
  100136. }
  100137. else {
  100138. _this.attachToMesh(null);
  100139. }
  100140. }
  100141. });
  100142. }
  100143. /**
  100144. * Attaches a set of gizmos to the specified mesh
  100145. * @param mesh The mesh the gizmo's should be attached to
  100146. */
  100147. GizmoManager.prototype.attachToMesh = function (mesh) {
  100148. if (this._attachedMesh) {
  100149. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  100150. }
  100151. this._attachedMesh = mesh;
  100152. for (var key in this.gizmos) {
  100153. var gizmo = (this.gizmos[key]);
  100154. if (gizmo && this._gizmosEnabled[key]) {
  100155. gizmo.attachedMesh = mesh;
  100156. }
  100157. }
  100158. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  100159. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  100160. }
  100161. };
  100162. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  100163. get: function () {
  100164. return this._gizmosEnabled.positionGizmo;
  100165. },
  100166. /**
  100167. * If the position gizmo is enabled
  100168. */
  100169. set: function (value) {
  100170. if (value) {
  100171. if (!this.gizmos.positionGizmo) {
  100172. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  100173. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  100174. }
  100175. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  100176. }
  100177. else if (this.gizmos.positionGizmo) {
  100178. this.gizmos.positionGizmo.attachedMesh = null;
  100179. }
  100180. this._gizmosEnabled.positionGizmo = value;
  100181. },
  100182. enumerable: true,
  100183. configurable: true
  100184. });
  100185. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  100186. get: function () {
  100187. return this._gizmosEnabled.rotationGizmo;
  100188. },
  100189. /**
  100190. * If the rotation gizmo is enabled
  100191. */
  100192. set: function (value) {
  100193. if (value) {
  100194. if (!this.gizmos.rotationGizmo) {
  100195. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  100196. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  100197. }
  100198. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  100199. }
  100200. else if (this.gizmos.rotationGizmo) {
  100201. this.gizmos.rotationGizmo.attachedMesh = null;
  100202. }
  100203. this._gizmosEnabled.rotationGizmo = value;
  100204. },
  100205. enumerable: true,
  100206. configurable: true
  100207. });
  100208. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  100209. get: function () {
  100210. return this._gizmosEnabled.scaleGizmo;
  100211. },
  100212. /**
  100213. * If the scale gizmo is enabled
  100214. */
  100215. set: function (value) {
  100216. if (value) {
  100217. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  100218. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  100219. }
  100220. else if (this.gizmos.scaleGizmo) {
  100221. this.gizmos.scaleGizmo.attachedMesh = null;
  100222. }
  100223. this._gizmosEnabled.scaleGizmo = value;
  100224. },
  100225. enumerable: true,
  100226. configurable: true
  100227. });
  100228. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  100229. get: function () {
  100230. return this._gizmosEnabled.boundingBoxGizmo;
  100231. },
  100232. /**
  100233. * If the boundingBox gizmo is enabled
  100234. */
  100235. set: function (value) {
  100236. if (value) {
  100237. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  100238. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  100239. if (this._attachedMesh) {
  100240. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  100241. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  100242. }
  100243. }
  100244. else if (this.gizmos.boundingBoxGizmo) {
  100245. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  100246. }
  100247. this._gizmosEnabled.boundingBoxGizmo = value;
  100248. },
  100249. enumerable: true,
  100250. configurable: true
  100251. });
  100252. /**
  100253. * Disposes of the gizmo manager
  100254. */
  100255. GizmoManager.prototype.dispose = function () {
  100256. this.scene.onPointerObservable.remove(this._pointerObserver);
  100257. for (var key in this.gizmos) {
  100258. var gizmo = (this.gizmos[key]);
  100259. if (gizmo) {
  100260. gizmo.dispose();
  100261. }
  100262. }
  100263. this.boundingBoxDragBehavior.detach();
  100264. };
  100265. return GizmoManager;
  100266. }());
  100267. BABYLON.GizmoManager = GizmoManager;
  100268. })(BABYLON || (BABYLON = {}));
  100269. //# sourceMappingURL=babylon.gizmoManager.js.map
  100270. var BABYLON;
  100271. (function (BABYLON) {
  100272. /**
  100273. * Defines a target to use with MorphTargetManager
  100274. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  100275. */
  100276. var MorphTarget = /** @class */ (function () {
  100277. /**
  100278. * Creates a new MorphTarget
  100279. * @param name defines the name of the target
  100280. * @param influence defines the influence to use
  100281. */
  100282. function MorphTarget(
  100283. /** defines the name of the target */
  100284. name, influence, scene) {
  100285. if (influence === void 0) { influence = 0; }
  100286. if (scene === void 0) { scene = null; }
  100287. this.name = name;
  100288. /**
  100289. * Gets or sets the list of animations
  100290. */
  100291. this.animations = new Array();
  100292. this._positions = null;
  100293. this._normals = null;
  100294. this._tangents = null;
  100295. /**
  100296. * Observable raised when the influence changes
  100297. */
  100298. this.onInfluenceChanged = new BABYLON.Observable();
  100299. this._animationPropertiesOverride = null;
  100300. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  100301. this.influence = influence;
  100302. }
  100303. Object.defineProperty(MorphTarget.prototype, "influence", {
  100304. /**
  100305. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  100306. */
  100307. get: function () {
  100308. return this._influence;
  100309. },
  100310. set: function (influence) {
  100311. if (this._influence === influence) {
  100312. return;
  100313. }
  100314. var previous = this._influence;
  100315. this._influence = influence;
  100316. if (this.onInfluenceChanged.hasObservers) {
  100317. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  100318. }
  100319. },
  100320. enumerable: true,
  100321. configurable: true
  100322. });
  100323. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  100324. /**
  100325. * Gets or sets the animation properties override
  100326. */
  100327. get: function () {
  100328. if (!this._animationPropertiesOverride && this._scene) {
  100329. return this._scene.animationPropertiesOverride;
  100330. }
  100331. return this._animationPropertiesOverride;
  100332. },
  100333. set: function (value) {
  100334. this._animationPropertiesOverride = value;
  100335. },
  100336. enumerable: true,
  100337. configurable: true
  100338. });
  100339. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  100340. /**
  100341. * Gets a boolean defining if the target contains position data
  100342. */
  100343. get: function () {
  100344. return !!this._positions;
  100345. },
  100346. enumerable: true,
  100347. configurable: true
  100348. });
  100349. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  100350. /**
  100351. * Gets a boolean defining if the target contains normal data
  100352. */
  100353. get: function () {
  100354. return !!this._normals;
  100355. },
  100356. enumerable: true,
  100357. configurable: true
  100358. });
  100359. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  100360. /**
  100361. * Gets a boolean defining if the target contains tangent data
  100362. */
  100363. get: function () {
  100364. return !!this._tangents;
  100365. },
  100366. enumerable: true,
  100367. configurable: true
  100368. });
  100369. /**
  100370. * Affects position data to this target
  100371. * @param data defines the position data to use
  100372. */
  100373. MorphTarget.prototype.setPositions = function (data) {
  100374. this._positions = data;
  100375. };
  100376. /**
  100377. * Gets the position data stored in this target
  100378. * @returns a FloatArray containing the position data (or null if not present)
  100379. */
  100380. MorphTarget.prototype.getPositions = function () {
  100381. return this._positions;
  100382. };
  100383. /**
  100384. * Affects normal data to this target
  100385. * @param data defines the normal data to use
  100386. */
  100387. MorphTarget.prototype.setNormals = function (data) {
  100388. this._normals = data;
  100389. };
  100390. /**
  100391. * Gets the normal data stored in this target
  100392. * @returns a FloatArray containing the normal data (or null if not present)
  100393. */
  100394. MorphTarget.prototype.getNormals = function () {
  100395. return this._normals;
  100396. };
  100397. /**
  100398. * Affects tangent data to this target
  100399. * @param data defines the tangent data to use
  100400. */
  100401. MorphTarget.prototype.setTangents = function (data) {
  100402. this._tangents = data;
  100403. };
  100404. /**
  100405. * Gets the tangent data stored in this target
  100406. * @returns a FloatArray containing the tangent data (or null if not present)
  100407. */
  100408. MorphTarget.prototype.getTangents = function () {
  100409. return this._tangents;
  100410. };
  100411. /**
  100412. * Serializes the current target into a Serialization object
  100413. * @returns the serialized object
  100414. */
  100415. MorphTarget.prototype.serialize = function () {
  100416. var serializationObject = {};
  100417. serializationObject.name = this.name;
  100418. serializationObject.influence = this.influence;
  100419. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  100420. if (this.hasNormals) {
  100421. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  100422. }
  100423. if (this.hasTangents) {
  100424. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  100425. }
  100426. // Animations
  100427. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  100428. return serializationObject;
  100429. };
  100430. // Statics
  100431. /**
  100432. * Creates a new target from serialized data
  100433. * @param serializationObject defines the serialized data to use
  100434. * @returns a new MorphTarget
  100435. */
  100436. MorphTarget.Parse = function (serializationObject) {
  100437. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  100438. result.setPositions(serializationObject.positions);
  100439. if (serializationObject.normals) {
  100440. result.setNormals(serializationObject.normals);
  100441. }
  100442. if (serializationObject.tangents) {
  100443. result.setTangents(serializationObject.tangents);
  100444. }
  100445. // Animations
  100446. if (serializationObject.animations) {
  100447. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  100448. var parsedAnimation = serializationObject.animations[animationIndex];
  100449. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  100450. }
  100451. }
  100452. return result;
  100453. };
  100454. /**
  100455. * Creates a MorphTarget from mesh data
  100456. * @param mesh defines the source mesh
  100457. * @param name defines the name to use for the new target
  100458. * @param influence defines the influence to attach to the target
  100459. * @returns a new MorphTarget
  100460. */
  100461. MorphTarget.FromMesh = function (mesh, name, influence) {
  100462. if (!name) {
  100463. name = mesh.name;
  100464. }
  100465. var result = new MorphTarget(name, influence, mesh.getScene());
  100466. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  100467. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  100468. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  100469. }
  100470. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  100471. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  100472. }
  100473. return result;
  100474. };
  100475. return MorphTarget;
  100476. }());
  100477. BABYLON.MorphTarget = MorphTarget;
  100478. })(BABYLON || (BABYLON = {}));
  100479. //# sourceMappingURL=babylon.morphTarget.js.map
  100480. var BABYLON;
  100481. (function (BABYLON) {
  100482. /**
  100483. * This class is used to deform meshes using morphing between different targets
  100484. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  100485. */
  100486. var MorphTargetManager = /** @class */ (function () {
  100487. /**
  100488. * Creates a new MorphTargetManager
  100489. * @param scene defines the current scene
  100490. */
  100491. function MorphTargetManager(scene) {
  100492. if (scene === void 0) { scene = null; }
  100493. this._targets = new Array();
  100494. this._targetObservable = new Array();
  100495. this._activeTargets = new BABYLON.SmartArray(16);
  100496. this._supportsNormals = false;
  100497. this._supportsTangents = false;
  100498. this._vertexCount = 0;
  100499. this._uniqueId = 0;
  100500. this._tempInfluences = new Array();
  100501. if (!scene) {
  100502. scene = BABYLON.Engine.LastCreatedScene;
  100503. }
  100504. this._scene = scene;
  100505. if (this._scene) {
  100506. this._scene.morphTargetManagers.push(this);
  100507. this._uniqueId = this._scene.getUniqueId();
  100508. }
  100509. }
  100510. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  100511. /**
  100512. * Gets the unique ID of this manager
  100513. */
  100514. get: function () {
  100515. return this._uniqueId;
  100516. },
  100517. enumerable: true,
  100518. configurable: true
  100519. });
  100520. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  100521. /**
  100522. * Gets the number of vertices handled by this manager
  100523. */
  100524. get: function () {
  100525. return this._vertexCount;
  100526. },
  100527. enumerable: true,
  100528. configurable: true
  100529. });
  100530. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  100531. /**
  100532. * Gets a boolean indicating if this manager supports morphing of normals
  100533. */
  100534. get: function () {
  100535. return this._supportsNormals;
  100536. },
  100537. enumerable: true,
  100538. configurable: true
  100539. });
  100540. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  100541. /**
  100542. * Gets a boolean indicating if this manager supports morphing of tangents
  100543. */
  100544. get: function () {
  100545. return this._supportsTangents;
  100546. },
  100547. enumerable: true,
  100548. configurable: true
  100549. });
  100550. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  100551. /**
  100552. * Gets the number of targets stored in this manager
  100553. */
  100554. get: function () {
  100555. return this._targets.length;
  100556. },
  100557. enumerable: true,
  100558. configurable: true
  100559. });
  100560. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  100561. /**
  100562. * Gets the number of influencers (ie. the number of targets with influences > 0)
  100563. */
  100564. get: function () {
  100565. return this._activeTargets.length;
  100566. },
  100567. enumerable: true,
  100568. configurable: true
  100569. });
  100570. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  100571. /**
  100572. * Gets the list of influences (one per target)
  100573. */
  100574. get: function () {
  100575. return this._influences;
  100576. },
  100577. enumerable: true,
  100578. configurable: true
  100579. });
  100580. /**
  100581. * Gets the active target at specified index. An active target is a target with an influence > 0
  100582. * @param index defines the index to check
  100583. * @returns the requested target
  100584. */
  100585. MorphTargetManager.prototype.getActiveTarget = function (index) {
  100586. return this._activeTargets.data[index];
  100587. };
  100588. /**
  100589. * Gets the target at specified index
  100590. * @param index defines the index to check
  100591. * @returns the requested target
  100592. */
  100593. MorphTargetManager.prototype.getTarget = function (index) {
  100594. return this._targets[index];
  100595. };
  100596. /**
  100597. * Add a new target to this manager
  100598. * @param target defines the target to add
  100599. */
  100600. MorphTargetManager.prototype.addTarget = function (target) {
  100601. var _this = this;
  100602. this._targets.push(target);
  100603. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  100604. _this._syncActiveTargets(needUpdate);
  100605. }));
  100606. this._syncActiveTargets(true);
  100607. };
  100608. /**
  100609. * Removes a target from the manager
  100610. * @param target defines the target to remove
  100611. */
  100612. MorphTargetManager.prototype.removeTarget = function (target) {
  100613. var index = this._targets.indexOf(target);
  100614. if (index >= 0) {
  100615. this._targets.splice(index, 1);
  100616. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  100617. this._syncActiveTargets(true);
  100618. }
  100619. };
  100620. /**
  100621. * Serializes the current manager into a Serialization object
  100622. * @returns the serialized object
  100623. */
  100624. MorphTargetManager.prototype.serialize = function () {
  100625. var serializationObject = {};
  100626. serializationObject.id = this.uniqueId;
  100627. serializationObject.targets = [];
  100628. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  100629. var target = _a[_i];
  100630. serializationObject.targets.push(target.serialize());
  100631. }
  100632. return serializationObject;
  100633. };
  100634. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  100635. var influenceCount = 0;
  100636. this._activeTargets.reset();
  100637. this._supportsNormals = true;
  100638. this._supportsTangents = true;
  100639. this._vertexCount = 0;
  100640. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  100641. var target = _a[_i];
  100642. this._activeTargets.push(target);
  100643. this._tempInfluences[influenceCount++] = target.influence;
  100644. var positions = target.getPositions();
  100645. if (positions) {
  100646. this._supportsNormals = this._supportsNormals && target.hasNormals;
  100647. this._supportsTangents = this._supportsTangents && target.hasTangents;
  100648. var vertexCount = positions.length / 3;
  100649. if (this._vertexCount === 0) {
  100650. this._vertexCount = vertexCount;
  100651. }
  100652. else if (this._vertexCount !== vertexCount) {
  100653. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  100654. return;
  100655. }
  100656. }
  100657. }
  100658. if (!this._influences || this._influences.length !== influenceCount) {
  100659. this._influences = new Float32Array(influenceCount);
  100660. }
  100661. for (var index = 0; index < influenceCount; index++) {
  100662. this._influences[index] = this._tempInfluences[index];
  100663. }
  100664. if (needUpdate) {
  100665. this.synchronize();
  100666. }
  100667. };
  100668. /**
  100669. * Syncrhonize the targets with all the meshes using this morph target manager
  100670. */
  100671. MorphTargetManager.prototype.synchronize = function () {
  100672. if (!this._scene) {
  100673. return;
  100674. }
  100675. // Flag meshes as dirty to resync with the active targets
  100676. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  100677. var mesh = _a[_i];
  100678. if (mesh.morphTargetManager === this) {
  100679. mesh._syncGeometryWithMorphTargetManager();
  100680. }
  100681. }
  100682. };
  100683. // Statics
  100684. /**
  100685. * Creates a new MorphTargetManager from serialized data
  100686. * @param serializationObject defines the serialized data
  100687. * @param scene defines the hosting scene
  100688. * @returns the new MorphTargetManager
  100689. */
  100690. MorphTargetManager.Parse = function (serializationObject, scene) {
  100691. var result = new MorphTargetManager(scene);
  100692. result._uniqueId = serializationObject.id;
  100693. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  100694. var targetData = _a[_i];
  100695. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  100696. }
  100697. return result;
  100698. };
  100699. return MorphTargetManager;
  100700. }());
  100701. BABYLON.MorphTargetManager = MorphTargetManager;
  100702. })(BABYLON || (BABYLON = {}));
  100703. //# sourceMappingURL=babylon.morphTargetManager.js.map
  100704. var BABYLON;
  100705. (function (BABYLON) {
  100706. /**
  100707. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  100708. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100709. */
  100710. var Octree = /** @class */ (function () {
  100711. /**
  100712. * Creates a octree
  100713. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100714. * @param creationFunc function to be used to instatiate the octree
  100715. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  100716. * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
  100717. */
  100718. function Octree(creationFunc, maxBlockCapacity,
  100719. /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
  100720. maxDepth) {
  100721. if (maxDepth === void 0) { maxDepth = 2; }
  100722. this.maxDepth = maxDepth;
  100723. /**
  100724. * Content stored in the octree
  100725. */
  100726. this.dynamicContent = new Array();
  100727. this._maxBlockCapacity = maxBlockCapacity || 64;
  100728. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  100729. this._creationFunc = creationFunc;
  100730. }
  100731. // Methods
  100732. /**
  100733. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  100734. * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100735. * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100736. * @param entries meshes to be added to the octree blocks
  100737. */
  100738. Octree.prototype.update = function (worldMin, worldMax, entries) {
  100739. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  100740. };
  100741. /**
  100742. * Adds a mesh to the octree
  100743. * @param entry Mesh to add to the octree
  100744. */
  100745. Octree.prototype.addMesh = function (entry) {
  100746. for (var index = 0; index < this.blocks.length; index++) {
  100747. var block = this.blocks[index];
  100748. block.addEntry(entry);
  100749. }
  100750. };
  100751. /**
  100752. * Selects an array of meshes within the frustum
  100753. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  100754. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  100755. * @returns array of meshes within the frustum
  100756. */
  100757. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  100758. this._selectionContent.reset();
  100759. for (var index = 0; index < this.blocks.length; index++) {
  100760. var block = this.blocks[index];
  100761. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  100762. }
  100763. if (allowDuplicate) {
  100764. this._selectionContent.concat(this.dynamicContent);
  100765. }
  100766. else {
  100767. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100768. }
  100769. return this._selectionContent;
  100770. };
  100771. /**
  100772. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  100773. * @param sphereCenter defines the bounding sphere center
  100774. * @param sphereRadius defines the bounding sphere radius
  100775. * @param allowDuplicate defines if the selection array can contains duplicated entries
  100776. * @returns an array of objects that intersect the sphere
  100777. */
  100778. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  100779. this._selectionContent.reset();
  100780. for (var index = 0; index < this.blocks.length; index++) {
  100781. var block = this.blocks[index];
  100782. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  100783. }
  100784. if (allowDuplicate) {
  100785. this._selectionContent.concat(this.dynamicContent);
  100786. }
  100787. else {
  100788. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100789. }
  100790. return this._selectionContent;
  100791. };
  100792. /**
  100793. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  100794. * @param ray defines the ray to test with
  100795. * @returns array of intersected objects
  100796. */
  100797. Octree.prototype.intersectsRay = function (ray) {
  100798. this._selectionContent.reset();
  100799. for (var index = 0; index < this.blocks.length; index++) {
  100800. var block = this.blocks[index];
  100801. block.intersectsRay(ray, this._selectionContent);
  100802. }
  100803. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100804. return this._selectionContent;
  100805. };
  100806. /**
  100807. * @hidden
  100808. */
  100809. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  100810. target.blocks = new Array();
  100811. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100812. // Segmenting space
  100813. for (var x = 0; x < 2; x++) {
  100814. for (var y = 0; y < 2; y++) {
  100815. for (var z = 0; z < 2; z++) {
  100816. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  100817. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  100818. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  100819. block.addEntries(entries);
  100820. target.blocks.push(block);
  100821. }
  100822. }
  100823. }
  100824. };
  100825. /**
  100826. * Adds a mesh into the octree block if it intersects the block
  100827. */
  100828. Octree.CreationFuncForMeshes = function (entry, block) {
  100829. var boundingInfo = entry.getBoundingInfo();
  100830. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  100831. block.entries.push(entry);
  100832. }
  100833. };
  100834. /**
  100835. * Adds a submesh into the octree block if it intersects the block
  100836. */
  100837. Octree.CreationFuncForSubMeshes = function (entry, block) {
  100838. var boundingInfo = entry.getBoundingInfo();
  100839. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  100840. block.entries.push(entry);
  100841. }
  100842. };
  100843. return Octree;
  100844. }());
  100845. BABYLON.Octree = Octree;
  100846. })(BABYLON || (BABYLON = {}));
  100847. //# sourceMappingURL=babylon.octree.js.map
  100848. var BABYLON;
  100849. (function (BABYLON) {
  100850. /**
  100851. * Class used to store a cell in an octree
  100852. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100853. */
  100854. var OctreeBlock = /** @class */ (function () {
  100855. /**
  100856. * Creates a new block
  100857. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  100858. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  100859. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  100860. * @param depth defines the current depth of this block in the octree
  100861. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  100862. * @param creationFunc defines a callback to call when an element is added to the block
  100863. */
  100864. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  100865. /**
  100866. * Gets the content of the current block
  100867. */
  100868. this.entries = new Array();
  100869. this._boundingVectors = new Array();
  100870. this._capacity = capacity;
  100871. this._depth = depth;
  100872. this._maxDepth = maxDepth;
  100873. this._creationFunc = creationFunc;
  100874. this._minPoint = minPoint;
  100875. this._maxPoint = maxPoint;
  100876. this._boundingVectors.push(minPoint.clone());
  100877. this._boundingVectors.push(maxPoint.clone());
  100878. this._boundingVectors.push(minPoint.clone());
  100879. this._boundingVectors[2].x = maxPoint.x;
  100880. this._boundingVectors.push(minPoint.clone());
  100881. this._boundingVectors[3].y = maxPoint.y;
  100882. this._boundingVectors.push(minPoint.clone());
  100883. this._boundingVectors[4].z = maxPoint.z;
  100884. this._boundingVectors.push(maxPoint.clone());
  100885. this._boundingVectors[5].z = minPoint.z;
  100886. this._boundingVectors.push(maxPoint.clone());
  100887. this._boundingVectors[6].x = minPoint.x;
  100888. this._boundingVectors.push(maxPoint.clone());
  100889. this._boundingVectors[7].y = minPoint.y;
  100890. }
  100891. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  100892. // Property
  100893. /**
  100894. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  100895. */
  100896. get: function () {
  100897. return this._capacity;
  100898. },
  100899. enumerable: true,
  100900. configurable: true
  100901. });
  100902. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  100903. /**
  100904. * Gets the minimum vector (in world space) of the block's bounding box
  100905. */
  100906. get: function () {
  100907. return this._minPoint;
  100908. },
  100909. enumerable: true,
  100910. configurable: true
  100911. });
  100912. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  100913. /**
  100914. * Gets the maximum vector (in world space) of the block's bounding box
  100915. */
  100916. get: function () {
  100917. return this._maxPoint;
  100918. },
  100919. enumerable: true,
  100920. configurable: true
  100921. });
  100922. // Methods
  100923. /**
  100924. * Add a new element to this block
  100925. * @param entry defines the element to add
  100926. */
  100927. OctreeBlock.prototype.addEntry = function (entry) {
  100928. if (this.blocks) {
  100929. for (var index = 0; index < this.blocks.length; index++) {
  100930. var block = this.blocks[index];
  100931. block.addEntry(entry);
  100932. }
  100933. return;
  100934. }
  100935. this._creationFunc(entry, this);
  100936. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  100937. this.createInnerBlocks();
  100938. }
  100939. };
  100940. /**
  100941. * Add an array of elements to this block
  100942. * @param entries defines the array of elements to add
  100943. */
  100944. OctreeBlock.prototype.addEntries = function (entries) {
  100945. for (var index = 0; index < entries.length; index++) {
  100946. var mesh = entries[index];
  100947. this.addEntry(mesh);
  100948. }
  100949. };
  100950. /**
  100951. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  100952. * @param frustumPlanes defines the frustum planes to test
  100953. * @param selection defines the array to store current content if selection is positive
  100954. * @param allowDuplicate defines if the selection array can contains duplicated entries
  100955. */
  100956. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  100957. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  100958. if (this.blocks) {
  100959. for (var index = 0; index < this.blocks.length; index++) {
  100960. var block = this.blocks[index];
  100961. block.select(frustumPlanes, selection, allowDuplicate);
  100962. }
  100963. return;
  100964. }
  100965. if (allowDuplicate) {
  100966. selection.concat(this.entries);
  100967. }
  100968. else {
  100969. selection.concatWithNoDuplicate(this.entries);
  100970. }
  100971. }
  100972. };
  100973. /**
  100974. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  100975. * @param sphereCenter defines the bounding sphere center
  100976. * @param sphereRadius defines the bounding sphere radius
  100977. * @param selection defines the array to store current content if selection is positive
  100978. * @param allowDuplicate defines if the selection array can contains duplicated entries
  100979. */
  100980. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  100981. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  100982. if (this.blocks) {
  100983. for (var index = 0; index < this.blocks.length; index++) {
  100984. var block = this.blocks[index];
  100985. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  100986. }
  100987. return;
  100988. }
  100989. if (allowDuplicate) {
  100990. selection.concat(this.entries);
  100991. }
  100992. else {
  100993. selection.concatWithNoDuplicate(this.entries);
  100994. }
  100995. }
  100996. };
  100997. /**
  100998. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  100999. * @param ray defines the ray to test with
  101000. * @param selection defines the array to store current content if selection is positive
  101001. */
  101002. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  101003. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  101004. if (this.blocks) {
  101005. for (var index = 0; index < this.blocks.length; index++) {
  101006. var block = this.blocks[index];
  101007. block.intersectsRay(ray, selection);
  101008. }
  101009. return;
  101010. }
  101011. selection.concatWithNoDuplicate(this.entries);
  101012. }
  101013. };
  101014. /**
  101015. * Subdivide the content into child blocks (this block will then be empty)
  101016. */
  101017. OctreeBlock.prototype.createInnerBlocks = function () {
  101018. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  101019. };
  101020. return OctreeBlock;
  101021. }());
  101022. BABYLON.OctreeBlock = OctreeBlock;
  101023. })(BABYLON || (BABYLON = {}));
  101024. //# sourceMappingURL=babylon.octreeBlock.js.map
  101025. var BABYLON;
  101026. (function (BABYLON) {
  101027. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  101028. if (maxCapacity === void 0) { maxCapacity = 64; }
  101029. if (maxDepth === void 0) { maxDepth = 2; }
  101030. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  101031. if (!component) {
  101032. component = new OctreeSceneComponent(this);
  101033. this._addComponent(component);
  101034. }
  101035. if (!this._selectionOctree) {
  101036. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  101037. }
  101038. var worldExtends = this.getWorldExtends();
  101039. // Update octree
  101040. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  101041. return this._selectionOctree;
  101042. };
  101043. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  101044. get: function () {
  101045. return this._selectionOctree;
  101046. },
  101047. enumerable: true,
  101048. configurable: true
  101049. });
  101050. /**
  101051. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  101052. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  101053. * @param maxCapacity defines the maximum size of each block (64 by default)
  101054. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  101055. * @returns the new octree
  101056. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  101057. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  101058. */
  101059. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  101060. if (maxCapacity === void 0) { maxCapacity = 64; }
  101061. if (maxDepth === void 0) { maxDepth = 2; }
  101062. var scene = this.getScene();
  101063. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  101064. if (!component) {
  101065. component = new OctreeSceneComponent(scene);
  101066. scene._addComponent(component);
  101067. }
  101068. if (!this._submeshesOctree) {
  101069. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  101070. }
  101071. this.computeWorldMatrix(true);
  101072. var boundingInfo = this.getBoundingInfo();
  101073. // Update octree
  101074. var bbox = boundingInfo.boundingBox;
  101075. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  101076. return this._submeshesOctree;
  101077. };
  101078. /**
  101079. * Defines the octree scene component responsible to manage any octrees
  101080. * in a given scene.
  101081. */
  101082. var OctreeSceneComponent = /** @class */ (function () {
  101083. /**
  101084. * Creates a new instance of the component for the given scene
  101085. * @param scene Defines the scene to register the component in
  101086. */
  101087. function OctreeSceneComponent(scene) {
  101088. /**
  101089. * The component name helpfull to identify the component in the list of scene components.
  101090. */
  101091. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  101092. /**
  101093. * Indicates if the meshes have been checked to make sure they are isEnabled()
  101094. */
  101095. this.checksIsEnabled = true;
  101096. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  101097. this.scene = scene;
  101098. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  101099. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  101100. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  101101. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  101102. }
  101103. /**
  101104. * Registers the component in a given scene
  101105. */
  101106. OctreeSceneComponent.prototype.register = function () {
  101107. var _this = this;
  101108. this.scene.onMeshRemovedObservable.add(function (mesh) {
  101109. var sceneOctree = _this.scene.selectionOctree;
  101110. if (sceneOctree !== undefined && sceneOctree !== null) {
  101111. var index = sceneOctree.dynamicContent.indexOf(mesh);
  101112. if (index !== -1) {
  101113. sceneOctree.dynamicContent.splice(index, 1);
  101114. }
  101115. }
  101116. });
  101117. this.scene.onMeshImportedObservable.add(function (mesh) {
  101118. var sceneOctree = _this.scene.selectionOctree;
  101119. if (sceneOctree !== undefined && sceneOctree !== null) {
  101120. sceneOctree.addMesh(mesh);
  101121. }
  101122. });
  101123. };
  101124. /**
  101125. * Return the list of active meshes
  101126. * @returns the list of active meshes
  101127. */
  101128. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  101129. if (this.scene._selectionOctree) {
  101130. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  101131. return selection;
  101132. }
  101133. return this.scene._getDefaultMeshCandidates();
  101134. };
  101135. /**
  101136. * Return the list of active sub meshes
  101137. * @param mesh The mesh to get the candidates sub meshes from
  101138. * @returns the list of active sub meshes
  101139. */
  101140. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  101141. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  101142. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  101143. return intersections;
  101144. }
  101145. return this.scene._getDefaultSubMeshCandidates(mesh);
  101146. };
  101147. /**
  101148. * Return the list of sub meshes intersecting with a given local ray
  101149. * @param mesh defines the mesh to find the submesh for
  101150. * @param localRay defines the ray in local space
  101151. * @returns the list of intersecting sub meshes
  101152. */
  101153. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  101154. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  101155. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  101156. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  101157. return intersections;
  101158. }
  101159. return this.scene._getDefaultSubMeshCandidates(mesh);
  101160. };
  101161. /**
  101162. * Return the list of sub meshes colliding with a collider
  101163. * @param mesh defines the mesh to find the submesh for
  101164. * @param collider defines the collider to evaluate the collision against
  101165. * @returns the list of colliding sub meshes
  101166. */
  101167. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  101168. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  101169. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  101170. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  101171. return intersections;
  101172. }
  101173. return this.scene._getDefaultSubMeshCandidates(mesh);
  101174. };
  101175. /**
  101176. * Rebuilds the elements related to this component in case of
  101177. * context lost for instance.
  101178. */
  101179. OctreeSceneComponent.prototype.rebuild = function () {
  101180. // Nothing to do here.
  101181. };
  101182. /**
  101183. * Disposes the component and the associated ressources.
  101184. */
  101185. OctreeSceneComponent.prototype.dispose = function () {
  101186. // Nothing to do here.
  101187. };
  101188. return OctreeSceneComponent;
  101189. }());
  101190. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  101191. })(BABYLON || (BABYLON = {}));
  101192. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  101193. var BABYLON;
  101194. (function (BABYLON) {
  101195. /**
  101196. * Postprocess used to generate anaglyphic rendering
  101197. */
  101198. var AnaglyphPostProcess = /** @class */ (function (_super) {
  101199. __extends(AnaglyphPostProcess, _super);
  101200. /**
  101201. * Creates a new AnaglyphPostProcess
  101202. * @param name defines postprocess name
  101203. * @param options defines creation options or target ratio scale
  101204. * @param rigCameras defines cameras using this postprocess
  101205. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  101206. * @param engine defines hosting engine
  101207. * @param reusable defines if the postprocess will be reused multiple times per frame
  101208. */
  101209. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  101210. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  101211. _this._passedProcess = rigCameras[0]._rigPostProcess;
  101212. _this.onApplyObservable.add(function (effect) {
  101213. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  101214. });
  101215. return _this;
  101216. }
  101217. return AnaglyphPostProcess;
  101218. }(BABYLON.PostProcess));
  101219. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  101220. })(BABYLON || (BABYLON = {}));
  101221. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  101222. var BABYLON;
  101223. (function (BABYLON) {
  101224. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  101225. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101226. });
  101227. /**
  101228. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  101229. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101230. */
  101231. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  101232. __extends(AnaglyphArcRotateCamera, _super);
  101233. /**
  101234. * Creates a new AnaglyphArcRotateCamera
  101235. * @param name defines camera name
  101236. * @param alpha defines alpha angle (in radians)
  101237. * @param beta defines beta angle (in radians)
  101238. * @param radius defines radius
  101239. * @param target defines camera target
  101240. * @param interaxialDistance defines distance between each color axis
  101241. * @param scene defines the hosting scene
  101242. */
  101243. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  101244. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  101245. _this.interaxialDistance = interaxialDistance;
  101246. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101247. return _this;
  101248. }
  101249. /**
  101250. * Gets camera class name
  101251. * @returns AnaglyphArcRotateCamera
  101252. */
  101253. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  101254. return "AnaglyphArcRotateCamera";
  101255. };
  101256. return AnaglyphArcRotateCamera;
  101257. }(BABYLON.ArcRotateCamera));
  101258. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  101259. })(BABYLON || (BABYLON = {}));
  101260. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  101261. var BABYLON;
  101262. (function (BABYLON) {
  101263. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  101264. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101265. });
  101266. /**
  101267. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  101268. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101269. */
  101270. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  101271. __extends(AnaglyphFreeCamera, _super);
  101272. /**
  101273. * Creates a new AnaglyphFreeCamera
  101274. * @param name defines camera name
  101275. * @param position defines initial position
  101276. * @param interaxialDistance defines distance between each color axis
  101277. * @param scene defines the hosting scene
  101278. */
  101279. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  101280. var _this = _super.call(this, name, position, scene) || this;
  101281. _this.interaxialDistance = interaxialDistance;
  101282. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101283. return _this;
  101284. }
  101285. /**
  101286. * Gets camera class name
  101287. * @returns AnaglyphFreeCamera
  101288. */
  101289. AnaglyphFreeCamera.prototype.getClassName = function () {
  101290. return "AnaglyphFreeCamera";
  101291. };
  101292. return AnaglyphFreeCamera;
  101293. }(BABYLON.FreeCamera));
  101294. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  101295. })(BABYLON || (BABYLON = {}));
  101296. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  101297. var BABYLON;
  101298. (function (BABYLON) {
  101299. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  101300. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101301. });
  101302. /**
  101303. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  101304. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101305. */
  101306. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  101307. __extends(AnaglyphGamepadCamera, _super);
  101308. /**
  101309. * Creates a new AnaglyphGamepadCamera
  101310. * @param name defines camera name
  101311. * @param position defines initial position
  101312. * @param interaxialDistance defines distance between each color axis
  101313. * @param scene defines the hosting scene
  101314. */
  101315. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  101316. var _this = _super.call(this, name, position, scene) || this;
  101317. _this.interaxialDistance = interaxialDistance;
  101318. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101319. return _this;
  101320. }
  101321. /**
  101322. * Gets camera class name
  101323. * @returns AnaglyphGamepadCamera
  101324. */
  101325. AnaglyphGamepadCamera.prototype.getClassName = function () {
  101326. return "AnaglyphGamepadCamera";
  101327. };
  101328. return AnaglyphGamepadCamera;
  101329. }(BABYLON.GamepadCamera));
  101330. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  101331. })(BABYLON || (BABYLON = {}));
  101332. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  101333. var BABYLON;
  101334. (function (BABYLON) {
  101335. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  101336. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101337. });
  101338. /**
  101339. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  101340. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101341. */
  101342. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  101343. __extends(AnaglyphUniversalCamera, _super);
  101344. /**
  101345. * Creates a new AnaglyphUniversalCamera
  101346. * @param name defines camera name
  101347. * @param position defines initial position
  101348. * @param interaxialDistance defines distance between each color axis
  101349. * @param scene defines the hosting scene
  101350. */
  101351. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  101352. var _this = _super.call(this, name, position, scene) || this;
  101353. _this.interaxialDistance = interaxialDistance;
  101354. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101355. return _this;
  101356. }
  101357. /**
  101358. * Gets camera class name
  101359. * @returns AnaglyphUniversalCamera
  101360. */
  101361. AnaglyphUniversalCamera.prototype.getClassName = function () {
  101362. return "AnaglyphUniversalCamera";
  101363. };
  101364. return AnaglyphUniversalCamera;
  101365. }(BABYLON.UniversalCamera));
  101366. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  101367. })(BABYLON || (BABYLON = {}));
  101368. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  101369. var BABYLON;
  101370. (function (BABYLON) {
  101371. /**
  101372. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  101373. */
  101374. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  101375. __extends(StereoscopicInterlacePostProcess, _super);
  101376. /**
  101377. * Initializes a StereoscopicInterlacePostProcess
  101378. * @param name The name of the effect.
  101379. * @param rigCameras The rig cameras to be appled to the post process
  101380. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  101381. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  101382. * @param engine The engine which the post process will be applied. (default: current engine)
  101383. * @param reusable If the post process can be reused on the same frame. (default: false)
  101384. */
  101385. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  101386. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  101387. _this._passedProcess = rigCameras[0]._rigPostProcess;
  101388. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  101389. _this.onSizeChangedObservable.add(function () {
  101390. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  101391. });
  101392. _this.onApplyObservable.add(function (effect) {
  101393. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  101394. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  101395. });
  101396. return _this;
  101397. }
  101398. return StereoscopicInterlacePostProcess;
  101399. }(BABYLON.PostProcess));
  101400. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  101401. })(BABYLON || (BABYLON = {}));
  101402. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  101403. var BABYLON;
  101404. (function (BABYLON) {
  101405. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  101406. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101407. });
  101408. /**
  101409. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  101410. * @see http://doc.babylonjs.com/features/cameras
  101411. */
  101412. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  101413. __extends(StereoscopicArcRotateCamera, _super);
  101414. /**
  101415. * Creates a new StereoscopicArcRotateCamera
  101416. * @param name defines camera name
  101417. * @param alpha defines alpha angle (in radians)
  101418. * @param beta defines beta angle (in radians)
  101419. * @param radius defines radius
  101420. * @param target defines camera target
  101421. * @param interaxialDistance defines distance between each color axis
  101422. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101423. * @param scene defines the hosting scene
  101424. */
  101425. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  101426. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  101427. _this.interaxialDistance = interaxialDistance;
  101428. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101429. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101430. return _this;
  101431. }
  101432. /**
  101433. * Gets camera class name
  101434. * @returns StereoscopicArcRotateCamera
  101435. */
  101436. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  101437. return "StereoscopicArcRotateCamera";
  101438. };
  101439. return StereoscopicArcRotateCamera;
  101440. }(BABYLON.ArcRotateCamera));
  101441. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  101442. })(BABYLON || (BABYLON = {}));
  101443. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  101444. var BABYLON;
  101445. (function (BABYLON) {
  101446. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  101447. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101448. });
  101449. /**
  101450. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  101451. * @see http://doc.babylonjs.com/features/cameras
  101452. */
  101453. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  101454. __extends(StereoscopicFreeCamera, _super);
  101455. /**
  101456. * Creates a new StereoscopicFreeCamera
  101457. * @param name defines camera name
  101458. * @param position defines initial position
  101459. * @param interaxialDistance defines distance between each color axis
  101460. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101461. * @param scene defines the hosting scene
  101462. */
  101463. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  101464. var _this = _super.call(this, name, position, scene) || this;
  101465. _this.interaxialDistance = interaxialDistance;
  101466. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101467. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101468. return _this;
  101469. }
  101470. /**
  101471. * Gets camera class name
  101472. * @returns StereoscopicFreeCamera
  101473. */
  101474. StereoscopicFreeCamera.prototype.getClassName = function () {
  101475. return "StereoscopicFreeCamera";
  101476. };
  101477. return StereoscopicFreeCamera;
  101478. }(BABYLON.FreeCamera));
  101479. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  101480. })(BABYLON || (BABYLON = {}));
  101481. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  101482. var BABYLON;
  101483. (function (BABYLON) {
  101484. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  101485. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101486. });
  101487. /**
  101488. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  101489. * @see http://doc.babylonjs.com/features/cameras
  101490. */
  101491. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  101492. __extends(StereoscopicGamepadCamera, _super);
  101493. /**
  101494. * Creates a new StereoscopicGamepadCamera
  101495. * @param name defines camera name
  101496. * @param position defines initial position
  101497. * @param interaxialDistance defines distance between each color axis
  101498. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101499. * @param scene defines the hosting scene
  101500. */
  101501. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  101502. var _this = _super.call(this, name, position, scene) || this;
  101503. _this.interaxialDistance = interaxialDistance;
  101504. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101505. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101506. return _this;
  101507. }
  101508. /**
  101509. * Gets camera class name
  101510. * @returns StereoscopicGamepadCamera
  101511. */
  101512. StereoscopicGamepadCamera.prototype.getClassName = function () {
  101513. return "StereoscopicGamepadCamera";
  101514. };
  101515. return StereoscopicGamepadCamera;
  101516. }(BABYLON.GamepadCamera));
  101517. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  101518. })(BABYLON || (BABYLON = {}));
  101519. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  101520. var BABYLON;
  101521. (function (BABYLON) {
  101522. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  101523. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101524. });
  101525. /**
  101526. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  101527. * @see http://doc.babylonjs.com/features/cameras
  101528. */
  101529. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  101530. __extends(StereoscopicUniversalCamera, _super);
  101531. /**
  101532. * Creates a new StereoscopicUniversalCamera
  101533. * @param name defines camera name
  101534. * @param position defines initial position
  101535. * @param interaxialDistance defines distance between each color axis
  101536. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101537. * @param scene defines the hosting scene
  101538. */
  101539. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  101540. var _this = _super.call(this, name, position, scene) || this;
  101541. _this.interaxialDistance = interaxialDistance;
  101542. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101543. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101544. return _this;
  101545. }
  101546. /**
  101547. * Gets camera class name
  101548. * @returns StereoscopicUniversalCamera
  101549. */
  101550. StereoscopicUniversalCamera.prototype.getClassName = function () {
  101551. return "StereoscopicUniversalCamera";
  101552. };
  101553. return StereoscopicUniversalCamera;
  101554. }(BABYLON.UniversalCamera));
  101555. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  101556. })(BABYLON || (BABYLON = {}));
  101557. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  101558. var BABYLON;
  101559. (function (BABYLON) {
  101560. /**
  101561. * VRDistortionCorrectionPostProcess used for mobile VR
  101562. */
  101563. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  101564. __extends(VRDistortionCorrectionPostProcess, _super);
  101565. /**
  101566. * Initializes the VRDistortionCorrectionPostProcess
  101567. * @param name The name of the effect.
  101568. * @param camera The camera to apply the render pass to.
  101569. * @param isRightEye If this is for the right eye distortion
  101570. * @param vrMetrics All the required metrics for the VR camera
  101571. */
  101572. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  101573. var _this = _super.call(this, name, "vrDistortionCorrection", [
  101574. 'LensCenter',
  101575. 'Scale',
  101576. 'ScaleIn',
  101577. 'HmdWarpParam'
  101578. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  101579. _this._isRightEye = isRightEye;
  101580. _this._distortionFactors = vrMetrics.distortionK;
  101581. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  101582. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  101583. _this.adaptScaleToCurrentViewport = true;
  101584. _this.onSizeChangedObservable.add(function () {
  101585. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  101586. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  101587. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  101588. });
  101589. _this.onApplyObservable.add(function (effect) {
  101590. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  101591. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  101592. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  101593. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  101594. });
  101595. return _this;
  101596. }
  101597. return VRDistortionCorrectionPostProcess;
  101598. }(BABYLON.PostProcess));
  101599. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  101600. })(BABYLON || (BABYLON = {}));
  101601. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  101602. var BABYLON;
  101603. (function (BABYLON) {
  101604. /**
  101605. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  101606. * Screen rotation is taken into account.
  101607. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101608. */
  101609. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  101610. /**
  101611. * Instantiates a new input
  101612. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101613. */
  101614. function FreeCameraDeviceOrientationInput() {
  101615. var _this = this;
  101616. this._screenOrientationAngle = 0;
  101617. this._screenQuaternion = new BABYLON.Quaternion();
  101618. this._alpha = 0;
  101619. this._beta = 0;
  101620. this._gamma = 0;
  101621. this._orientationChanged = function () {
  101622. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  101623. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  101624. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  101625. };
  101626. this._deviceOrientation = function (evt) {
  101627. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  101628. _this._beta = evt.beta !== null ? evt.beta : 0;
  101629. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  101630. };
  101631. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  101632. this._orientationChanged();
  101633. }
  101634. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  101635. /**
  101636. * Define the camera controlled by the input.
  101637. */
  101638. get: function () {
  101639. return this._camera;
  101640. },
  101641. set: function (camera) {
  101642. this._camera = camera;
  101643. if (this._camera != null && !this._camera.rotationQuaternion) {
  101644. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  101645. }
  101646. },
  101647. enumerable: true,
  101648. configurable: true
  101649. });
  101650. /**
  101651. * Attach the input controls to a specific dom element to get the input from.
  101652. * @param element Defines the element the controls should be listened from
  101653. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  101654. */
  101655. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  101656. window.addEventListener("orientationchange", this._orientationChanged);
  101657. window.addEventListener("deviceorientation", this._deviceOrientation);
  101658. //In certain cases, the attach control is called AFTER orientation was changed,
  101659. //So this is needed.
  101660. this._orientationChanged();
  101661. };
  101662. /**
  101663. * Detach the current controls from the specified dom element.
  101664. * @param element Defines the element to stop listening the inputs from
  101665. */
  101666. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  101667. window.removeEventListener("orientationchange", this._orientationChanged);
  101668. window.removeEventListener("deviceorientation", this._deviceOrientation);
  101669. };
  101670. /**
  101671. * Update the current camera state depending on the inputs that have been used this frame.
  101672. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  101673. */
  101674. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  101675. //if no device orientation provided, don't update the rotation.
  101676. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  101677. if (!this._alpha)
  101678. return;
  101679. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  101680. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  101681. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  101682. //Mirror on XY Plane
  101683. this._camera.rotationQuaternion.z *= -1;
  101684. this._camera.rotationQuaternion.w *= -1;
  101685. };
  101686. /**
  101687. * Gets the class name of the current intput.
  101688. * @returns the class name
  101689. */
  101690. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  101691. return "FreeCameraDeviceOrientationInput";
  101692. };
  101693. /**
  101694. * Get the friendly name associated with the input class.
  101695. * @returns the input friendly name
  101696. */
  101697. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  101698. return "deviceOrientation";
  101699. };
  101700. return FreeCameraDeviceOrientationInput;
  101701. }());
  101702. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  101703. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  101704. })(BABYLON || (BABYLON = {}));
  101705. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  101706. var BABYLON;
  101707. (function (BABYLON) {
  101708. /**
  101709. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  101710. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101711. */
  101712. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  101713. /**
  101714. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  101715. */
  101716. function ArcRotateCameraVRDeviceOrientationInput() {
  101717. /**
  101718. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  101719. */
  101720. this.alphaCorrection = 1;
  101721. /**
  101722. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  101723. */
  101724. this.betaCorrection = 1;
  101725. /**
  101726. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  101727. */
  101728. this.gammaCorrection = 1;
  101729. this._alpha = 0;
  101730. this._gamma = 0;
  101731. this._dirty = false;
  101732. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  101733. }
  101734. /**
  101735. * Attach the input controls to a specific dom element to get the input from.
  101736. * @param element Defines the element the controls should be listened from
  101737. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  101738. */
  101739. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  101740. this.camera.attachControl(element, noPreventDefault);
  101741. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  101742. };
  101743. /** @hidden */
  101744. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  101745. if (evt.alpha !== null) {
  101746. this._alpha = +evt.alpha | 0;
  101747. }
  101748. if (evt.gamma !== null) {
  101749. this._gamma = +evt.gamma | 0;
  101750. }
  101751. this._dirty = true;
  101752. };
  101753. /**
  101754. * Update the current camera state depending on the inputs that have been used this frame.
  101755. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  101756. */
  101757. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  101758. if (this._dirty) {
  101759. this._dirty = false;
  101760. if (this._gamma < 0) {
  101761. this._gamma = 180 + this._gamma;
  101762. }
  101763. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  101764. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  101765. }
  101766. };
  101767. /**
  101768. * Detach the current controls from the specified dom element.
  101769. * @param element Defines the element to stop listening the inputs from
  101770. */
  101771. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  101772. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  101773. };
  101774. /**
  101775. * Gets the class name of the current intput.
  101776. * @returns the class name
  101777. */
  101778. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  101779. return "ArcRotateCameraVRDeviceOrientationInput";
  101780. };
  101781. /**
  101782. * Get the friendly name associated with the input class.
  101783. * @returns the input friendly name
  101784. */
  101785. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  101786. return "VRDeviceOrientation";
  101787. };
  101788. return ArcRotateCameraVRDeviceOrientationInput;
  101789. }());
  101790. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  101791. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  101792. })(BABYLON || (BABYLON = {}));
  101793. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  101794. var BABYLON;
  101795. (function (BABYLON) {
  101796. /**
  101797. * This represents all the required metrics to create a VR camera.
  101798. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  101799. */
  101800. var VRCameraMetrics = /** @class */ (function () {
  101801. function VRCameraMetrics() {
  101802. /**
  101803. * Define if the current vr camera should compensate the distortion of the lense or not.
  101804. */
  101805. this.compensateDistortion = true;
  101806. }
  101807. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  101808. /**
  101809. * Gets the rendering aspect ratio based on the provided resolutions.
  101810. */
  101811. get: function () {
  101812. return this.hResolution / (2 * this.vResolution);
  101813. },
  101814. enumerable: true,
  101815. configurable: true
  101816. });
  101817. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  101818. /**
  101819. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  101820. */
  101821. get: function () {
  101822. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  101823. },
  101824. enumerable: true,
  101825. configurable: true
  101826. });
  101827. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  101828. /**
  101829. * @hidden
  101830. */
  101831. get: function () {
  101832. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  101833. var h = (4 * meters) / this.hScreenSize;
  101834. return BABYLON.Matrix.Translation(h, 0, 0);
  101835. },
  101836. enumerable: true,
  101837. configurable: true
  101838. });
  101839. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  101840. /**
  101841. * @hidden
  101842. */
  101843. get: function () {
  101844. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  101845. var h = (4 * meters) / this.hScreenSize;
  101846. return BABYLON.Matrix.Translation(-h, 0, 0);
  101847. },
  101848. enumerable: true,
  101849. configurable: true
  101850. });
  101851. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  101852. /**
  101853. * @hidden
  101854. */
  101855. get: function () {
  101856. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  101857. },
  101858. enumerable: true,
  101859. configurable: true
  101860. });
  101861. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  101862. /**
  101863. * @hidden
  101864. */
  101865. get: function () {
  101866. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  101867. },
  101868. enumerable: true,
  101869. configurable: true
  101870. });
  101871. /**
  101872. * Get the default VRMetrics based on the most generic setup.
  101873. * @returns the default vr metrics
  101874. */
  101875. VRCameraMetrics.GetDefault = function () {
  101876. var result = new VRCameraMetrics();
  101877. result.hResolution = 1280;
  101878. result.vResolution = 800;
  101879. result.hScreenSize = 0.149759993;
  101880. result.vScreenSize = 0.0935999975;
  101881. result.vScreenCenter = 0.0467999987;
  101882. result.eyeToScreenDistance = 0.0410000011;
  101883. result.lensSeparationDistance = 0.0635000020;
  101884. result.interpupillaryDistance = 0.0640000030;
  101885. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  101886. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  101887. result.postProcessScaleFactor = 1.714605507808412;
  101888. result.lensCenterOffset = 0.151976421;
  101889. return result;
  101890. };
  101891. return VRCameraMetrics;
  101892. }());
  101893. BABYLON.VRCameraMetrics = VRCameraMetrics;
  101894. })(BABYLON || (BABYLON = {}));
  101895. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  101896. var BABYLON;
  101897. (function (BABYLON) {
  101898. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  101899. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101900. });
  101901. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  101902. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101903. });
  101904. /**
  101905. * This represents a WebVR camera.
  101906. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  101907. * @example http://doc.babylonjs.com/how_to/webvr_camera
  101908. */
  101909. var WebVRFreeCamera = /** @class */ (function (_super) {
  101910. __extends(WebVRFreeCamera, _super);
  101911. /**
  101912. * Instantiates a WebVRFreeCamera.
  101913. * @param name The name of the WebVRFreeCamera
  101914. * @param position The starting anchor position for the camera
  101915. * @param scene The scene the camera belongs to
  101916. * @param webVROptions a set of customizable options for the webVRCamera
  101917. */
  101918. function WebVRFreeCamera(name, position, scene, webVROptions) {
  101919. if (webVROptions === void 0) { webVROptions = {}; }
  101920. var _this = _super.call(this, name, position, scene) || this;
  101921. _this.webVROptions = webVROptions;
  101922. /**
  101923. * @hidden
  101924. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  101925. */
  101926. _this._vrDevice = null;
  101927. /**
  101928. * The rawPose of the vrDevice.
  101929. */
  101930. _this.rawPose = null;
  101931. _this._specsVersion = "1.1";
  101932. _this._attached = false;
  101933. _this._descendants = [];
  101934. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  101935. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  101936. /** @hidden */
  101937. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  101938. _this._standingMatrix = null;
  101939. /**
  101940. * Represents device position in babylon space.
  101941. */
  101942. _this.devicePosition = BABYLON.Vector3.Zero();
  101943. /**
  101944. * Represents device rotation in babylon space.
  101945. */
  101946. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  101947. /**
  101948. * The scale of the device to be used when translating from device space to babylon space.
  101949. */
  101950. _this.deviceScaleFactor = 1;
  101951. _this._deviceToWorld = BABYLON.Matrix.Identity();
  101952. _this._worldToDevice = BABYLON.Matrix.Identity();
  101953. /**
  101954. * References to the webVR controllers for the vrDevice.
  101955. */
  101956. _this.controllers = [];
  101957. /**
  101958. * Emits an event when a controller is attached.
  101959. */
  101960. _this.onControllersAttachedObservable = new BABYLON.Observable();
  101961. /**
  101962. * Emits an event when a controller's mesh has been loaded;
  101963. */
  101964. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  101965. /**
  101966. * Emits an event when the HMD's pose has been updated.
  101967. */
  101968. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  101969. _this._poseSet = false;
  101970. /**
  101971. * If the rig cameras be used as parent instead of this camera.
  101972. */
  101973. _this.rigParenting = true;
  101974. _this._defaultHeight = undefined;
  101975. _this._htmlElementAttached = null;
  101976. _this._detachIfAttached = function () {
  101977. var vrDisplay = _this.getEngine().getVRDevice();
  101978. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  101979. _this.detachControl(_this._htmlElementAttached);
  101980. }
  101981. };
  101982. _this._workingVector = BABYLON.Vector3.Zero();
  101983. _this._oneVector = BABYLON.Vector3.One();
  101984. _this._workingMatrix = BABYLON.Matrix.Identity();
  101985. _this._tmpMatrix = new BABYLON.Matrix();
  101986. _this._cache.position = BABYLON.Vector3.Zero();
  101987. if (webVROptions.defaultHeight) {
  101988. _this._defaultHeight = webVROptions.defaultHeight;
  101989. _this.position.y = _this._defaultHeight;
  101990. }
  101991. _this.minZ = 0.1;
  101992. //legacy support - the compensation boolean was removed.
  101993. if (arguments.length === 5) {
  101994. _this.webVROptions = arguments[4];
  101995. }
  101996. // default webVR options
  101997. if (_this.webVROptions.trackPosition == undefined) {
  101998. _this.webVROptions.trackPosition = true;
  101999. }
  102000. if (_this.webVROptions.controllerMeshes == undefined) {
  102001. _this.webVROptions.controllerMeshes = true;
  102002. }
  102003. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  102004. _this.webVROptions.defaultLightingOnControllers = true;
  102005. }
  102006. _this.rotationQuaternion = new BABYLON.Quaternion();
  102007. if (_this.webVROptions && _this.webVROptions.positionScale) {
  102008. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  102009. }
  102010. //enable VR
  102011. var engine = _this.getEngine();
  102012. _this._onVREnabled = function (success) { if (success) {
  102013. _this.initControllers();
  102014. } };
  102015. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  102016. engine.initWebVR().add(function (event) {
  102017. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  102018. return;
  102019. }
  102020. _this._vrDevice = event.vrDisplay;
  102021. //reset the rig parameters.
  102022. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  102023. if (_this._attached) {
  102024. _this.getEngine().enableVR();
  102025. }
  102026. });
  102027. if (typeof (VRFrameData) !== "undefined")
  102028. _this._frameData = new VRFrameData();
  102029. /**
  102030. * The idea behind the following lines:
  102031. * objects that have the camera as parent should actually have the rig cameras as a parent.
  102032. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  102033. * the second will not show it correctly.
  102034. *
  102035. * To solve this - each object that has the camera as parent will be added to a protected array.
  102036. * When the rig camera renders, it will take this array and set all of those to be its children.
  102037. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  102038. * Amazing!
  102039. */
  102040. scene.onBeforeCameraRenderObservable.add(function (camera) {
  102041. if (camera.parent === _this && _this.rigParenting) {
  102042. _this._descendants = _this.getDescendants(true, function (n) {
  102043. // don't take the cameras or the controllers!
  102044. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  102045. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  102046. return !isController && !isRigCamera;
  102047. });
  102048. _this._descendants.forEach(function (node) {
  102049. node.parent = camera;
  102050. });
  102051. }
  102052. });
  102053. scene.onAfterCameraRenderObservable.add(function (camera) {
  102054. if (camera.parent === _this && _this.rigParenting) {
  102055. _this._descendants.forEach(function (node) {
  102056. node.parent = _this;
  102057. });
  102058. }
  102059. });
  102060. return _this;
  102061. }
  102062. /**
  102063. * Gets the device distance from the ground in meters.
  102064. * @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.
  102065. */
  102066. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  102067. if (this._standingMatrix) {
  102068. // Add standing matrix offset to get real offset from ground in room
  102069. this._standingMatrix.getTranslationToRef(this._workingVector);
  102070. return this._deviceRoomPosition.y + this._workingVector.y;
  102071. }
  102072. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  102073. return this._defaultHeight || 0;
  102074. };
  102075. /**
  102076. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  102077. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  102078. */
  102079. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  102080. var _this = this;
  102081. if (callback === void 0) { callback = function (bool) { }; }
  102082. // Use standing matrix if available
  102083. this.getEngine().initWebVRAsync().then(function (result) {
  102084. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  102085. callback(false);
  102086. }
  102087. else {
  102088. _this._standingMatrix = new BABYLON.Matrix();
  102089. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  102090. if (!_this.getScene().useRightHandedSystem) {
  102091. [2, 6, 8, 9, 14].forEach(function (num) {
  102092. if (_this._standingMatrix) {
  102093. _this._standingMatrix.m[num] *= -1;
  102094. }
  102095. });
  102096. }
  102097. callback(true);
  102098. }
  102099. });
  102100. };
  102101. /**
  102102. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  102103. * @returns A promise with a boolean set to if the standing matrix is supported.
  102104. */
  102105. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  102106. var _this = this;
  102107. return new Promise(function (res, rej) {
  102108. _this.useStandingMatrix(function (supported) {
  102109. res(supported);
  102110. });
  102111. });
  102112. };
  102113. /**
  102114. * Disposes the camera
  102115. */
  102116. WebVRFreeCamera.prototype.dispose = function () {
  102117. this._detachIfAttached();
  102118. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  102119. if (this._updateCacheWhenTrackingDisabledObserver) {
  102120. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  102121. }
  102122. _super.prototype.dispose.call(this);
  102123. };
  102124. /**
  102125. * Gets a vrController by name.
  102126. * @param name The name of the controller to retreive
  102127. * @returns the controller matching the name specified or null if not found
  102128. */
  102129. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  102130. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  102131. var gp = _a[_i];
  102132. if (gp.hand === name) {
  102133. return gp;
  102134. }
  102135. }
  102136. return null;
  102137. };
  102138. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  102139. /**
  102140. * The controller corrisponding to the users left hand.
  102141. */
  102142. get: function () {
  102143. if (!this._leftController) {
  102144. this._leftController = this.getControllerByName("left");
  102145. }
  102146. return this._leftController;
  102147. },
  102148. enumerable: true,
  102149. configurable: true
  102150. });
  102151. ;
  102152. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  102153. /**
  102154. * The controller corrisponding to the users right hand.
  102155. */
  102156. get: function () {
  102157. if (!this._rightController) {
  102158. this._rightController = this.getControllerByName("right");
  102159. }
  102160. return this._rightController;
  102161. },
  102162. enumerable: true,
  102163. configurable: true
  102164. });
  102165. ;
  102166. /**
  102167. * Casts a ray forward from the vrCamera's gaze.
  102168. * @param length Length of the ray (default: 100)
  102169. * @returns the ray corrisponding to the gaze
  102170. */
  102171. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  102172. if (length === void 0) { length = 100; }
  102173. if (this.leftCamera) {
  102174. // Use left eye to avoid computation to compute center on every call
  102175. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  102176. }
  102177. else {
  102178. return _super.prototype.getForwardRay.call(this, length);
  102179. }
  102180. };
  102181. /**
  102182. * @hidden
  102183. * Updates the camera based on device's frame data
  102184. */
  102185. WebVRFreeCamera.prototype._checkInputs = function () {
  102186. if (this._vrDevice && this._vrDevice.isPresenting) {
  102187. this._vrDevice.getFrameData(this._frameData);
  102188. this.updateFromDevice(this._frameData.pose);
  102189. }
  102190. _super.prototype._checkInputs.call(this);
  102191. };
  102192. /**
  102193. * Updates the poseControlled values based on the input device pose.
  102194. * @param poseData Pose coming from the device
  102195. */
  102196. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  102197. if (poseData && poseData.orientation) {
  102198. this.rawPose = poseData;
  102199. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  102200. if (this.getScene().useRightHandedSystem) {
  102201. this._deviceRoomRotationQuaternion.z *= -1;
  102202. this._deviceRoomRotationQuaternion.w *= -1;
  102203. }
  102204. if (this.webVROptions.trackPosition && this.rawPose.position) {
  102205. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  102206. if (this.getScene().useRightHandedSystem) {
  102207. this._deviceRoomPosition.z *= -1;
  102208. }
  102209. }
  102210. this._poseSet = true;
  102211. }
  102212. };
  102213. /**
  102214. * WebVR's attach control will start broadcasting frames to the device.
  102215. * Note that in certain browsers (chrome for example) this function must be called
  102216. * within a user-interaction callback. Example:
  102217. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  102218. *
  102219. * @param element html element to attach the vrDevice to
  102220. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  102221. */
  102222. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  102223. _super.prototype.attachControl.call(this, element, noPreventDefault);
  102224. this._attached = true;
  102225. this._htmlElementAttached = element;
  102226. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  102227. if (this._vrDevice) {
  102228. this.getEngine().enableVR();
  102229. }
  102230. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  102231. };
  102232. /**
  102233. * Detaches the camera from the html element and disables VR
  102234. *
  102235. * @param element html element to detach from
  102236. */
  102237. WebVRFreeCamera.prototype.detachControl = function (element) {
  102238. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  102239. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  102240. _super.prototype.detachControl.call(this, element);
  102241. this._attached = false;
  102242. this.getEngine().disableVR();
  102243. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  102244. };
  102245. /**
  102246. * @returns the name of this class
  102247. */
  102248. WebVRFreeCamera.prototype.getClassName = function () {
  102249. return "WebVRFreeCamera";
  102250. };
  102251. /**
  102252. * Calls resetPose on the vrDisplay
  102253. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  102254. */
  102255. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  102256. //uses the vrDisplay's "resetPose()".
  102257. //pitch and roll won't be affected.
  102258. this._vrDevice.resetPose();
  102259. };
  102260. /**
  102261. * @hidden
  102262. * Updates the rig cameras (left and right eye)
  102263. */
  102264. WebVRFreeCamera.prototype._updateRigCameras = function () {
  102265. var camLeft = this._rigCameras[0];
  102266. var camRight = this._rigCameras[1];
  102267. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  102268. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  102269. camLeft.position.copyFrom(this._deviceRoomPosition);
  102270. camRight.position.copyFrom(this._deviceRoomPosition);
  102271. };
  102272. // Remove translation from 6dof headset if trackposition is set to false
  102273. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  102274. if (isViewMatrix === void 0) { isViewMatrix = false; }
  102275. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  102276. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  102277. if (!isViewMatrix) {
  102278. this._tmpMatrix.invert();
  102279. }
  102280. this._tmpMatrix.multiplyToRef(matrix, matrix);
  102281. }
  102282. };
  102283. /**
  102284. * @hidden
  102285. * Updates the cached values of the camera
  102286. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  102287. */
  102288. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  102289. var _this = this;
  102290. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  102291. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  102292. if (!this.updateCacheCalled) {
  102293. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  102294. this.updateCacheCalled = true;
  102295. this.update();
  102296. }
  102297. // Set working vector to the device position in room space rotated by the new rotation
  102298. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  102299. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  102300. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  102301. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  102302. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  102303. // Add translation from anchor position
  102304. this._deviceToWorld.getTranslationToRef(this._workingVector);
  102305. this._workingVector.addInPlace(this.position);
  102306. this._workingVector.subtractInPlace(this._cache.position);
  102307. this._deviceToWorld.setTranslation(this._workingVector);
  102308. // Set an inverted matrix to be used when updating the camera
  102309. this._deviceToWorld.invertToRef(this._worldToDevice);
  102310. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  102311. this.controllers.forEach(function (controller) {
  102312. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  102313. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  102314. controller.update();
  102315. });
  102316. }
  102317. if (!ignoreParentClass) {
  102318. _super.prototype._updateCache.call(this);
  102319. }
  102320. this.updateCacheCalled = false;
  102321. };
  102322. /**
  102323. * @hidden
  102324. * Get current device position in babylon world
  102325. */
  102326. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  102327. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  102328. };
  102329. /**
  102330. * Updates the current device position and rotation in the babylon world
  102331. */
  102332. WebVRFreeCamera.prototype.update = function () {
  102333. this._computeDevicePosition();
  102334. // Get current device rotation in babylon world
  102335. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  102336. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  102337. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  102338. if (this._poseSet) {
  102339. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  102340. }
  102341. _super.prototype.update.call(this);
  102342. };
  102343. /**
  102344. * @hidden
  102345. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  102346. * @returns an identity matrix
  102347. */
  102348. WebVRFreeCamera.prototype._getViewMatrix = function () {
  102349. return BABYLON.Matrix.Identity();
  102350. };
  102351. /**
  102352. * This function is called by the two RIG cameras.
  102353. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  102354. */
  102355. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  102356. var _this = this;
  102357. // Update the parent camera prior to using a child camera to avoid desynchronization
  102358. var parentCamera = this._cameraRigParams["parentCamera"];
  102359. parentCamera._updateCache();
  102360. //WebVR 1.1
  102361. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  102362. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  102363. if (!this.getScene().useRightHandedSystem) {
  102364. [2, 6, 8, 9, 14].forEach(function (num) {
  102365. _this._webvrViewMatrix.m[num] *= -1;
  102366. });
  102367. }
  102368. // update the camera rotation matrix
  102369. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  102370. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  102371. // Computing target and final matrix
  102372. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  102373. // should the view matrix be updated with scale and position offset?
  102374. if (parentCamera.deviceScaleFactor !== 1) {
  102375. this._webvrViewMatrix.invert();
  102376. // scale the position, if set
  102377. if (parentCamera.deviceScaleFactor) {
  102378. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  102379. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  102380. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  102381. }
  102382. this._webvrViewMatrix.invert();
  102383. }
  102384. // Remove translation from 6dof headset if trackposition is set to false
  102385. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  102386. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  102387. // Compute global position
  102388. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  102389. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  102390. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  102391. this._workingMatrix.getTranslationToRef(this._globalPosition);
  102392. this._markSyncedWithParent();
  102393. return this._webvrViewMatrix;
  102394. };
  102395. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  102396. var _this = this;
  102397. var parentCamera = this.parent;
  102398. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  102399. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  102400. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  102401. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  102402. //babylon compatible matrix
  102403. if (!this.getScene().useRightHandedSystem) {
  102404. [8, 9, 10, 11].forEach(function (num) {
  102405. _this._projectionMatrix.m[num] *= -1;
  102406. });
  102407. }
  102408. return this._projectionMatrix;
  102409. };
  102410. /**
  102411. * Initializes the controllers and their meshes
  102412. */
  102413. WebVRFreeCamera.prototype.initControllers = function () {
  102414. var _this = this;
  102415. this.controllers = [];
  102416. var manager = this.getScene().gamepadManager;
  102417. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  102418. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  102419. var webVrController = gamepad;
  102420. if (webVrController.defaultModel) {
  102421. webVrController.defaultModel.setEnabled(false);
  102422. }
  102423. if (webVrController.hand === "right") {
  102424. _this._rightController = null;
  102425. }
  102426. if (webVrController.hand === "left") {
  102427. _this._leftController = null;
  102428. }
  102429. var controllerIndex = _this.controllers.indexOf(webVrController);
  102430. if (controllerIndex !== -1) {
  102431. _this.controllers.splice(controllerIndex, 1);
  102432. }
  102433. }
  102434. });
  102435. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  102436. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  102437. var webVrController_1 = gamepad;
  102438. if (!_this.webVROptions.trackPosition) {
  102439. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  102440. // Cache must be updated before rendering controllers to avoid them being one frame behind
  102441. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  102442. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  102443. _this._updateCache();
  102444. });
  102445. }
  102446. }
  102447. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  102448. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  102449. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  102450. if (_this.webVROptions.controllerMeshes) {
  102451. if (webVrController_1.defaultModel) {
  102452. webVrController_1.defaultModel.setEnabled(true);
  102453. }
  102454. else {
  102455. // Load the meshes
  102456. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  102457. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  102458. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  102459. if (_this.webVROptions.defaultLightingOnControllers) {
  102460. if (!_this._lightOnControllers) {
  102461. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  102462. }
  102463. var activateLightOnSubMeshes_1 = function (mesh, light) {
  102464. var children = mesh.getChildren();
  102465. if (children && children.length !== 0) {
  102466. children.forEach(function (mesh) {
  102467. light.includedOnlyMeshes.push(mesh);
  102468. activateLightOnSubMeshes_1(mesh, light);
  102469. });
  102470. }
  102471. };
  102472. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  102473. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  102474. }
  102475. });
  102476. }
  102477. }
  102478. webVrController_1.attachToPoseControlledCamera(_this);
  102479. // since this is async - sanity check. Is the controller already stored?
  102480. if (_this.controllers.indexOf(webVrController_1) === -1) {
  102481. //add to the controllers array
  102482. _this.controllers.push(webVrController_1);
  102483. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  102484. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  102485. // So we're overriding setting left & right manually to be sure
  102486. var firstViveWandDetected = false;
  102487. for (var i = 0; i < _this.controllers.length; i++) {
  102488. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  102489. if (!firstViveWandDetected) {
  102490. firstViveWandDetected = true;
  102491. _this.controllers[i].hand = "left";
  102492. }
  102493. else {
  102494. _this.controllers[i].hand = "right";
  102495. }
  102496. }
  102497. }
  102498. //did we find enough controllers? Great! let the developer know.
  102499. if (_this.controllers.length >= 2) {
  102500. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  102501. }
  102502. }
  102503. }
  102504. });
  102505. };
  102506. return WebVRFreeCamera;
  102507. }(BABYLON.FreeCamera));
  102508. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  102509. })(BABYLON || (BABYLON = {}));
  102510. //# sourceMappingURL=babylon.webVRCamera.js.map
  102511. var BABYLON;
  102512. (function (BABYLON) {
  102513. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  102514. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  102515. });
  102516. // We're mainly based on the logic defined into the FreeCamera code
  102517. /**
  102518. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  102519. * being tilted forward or back and left or right.
  102520. */
  102521. var DeviceOrientationCamera = /** @class */ (function (_super) {
  102522. __extends(DeviceOrientationCamera, _super);
  102523. /**
  102524. * Creates a new device orientation camera
  102525. * @param name The name of the camera
  102526. * @param position The start position camera
  102527. * @param scene The scene the camera belongs to
  102528. */
  102529. function DeviceOrientationCamera(name, position, scene) {
  102530. var _this = _super.call(this, name, position, scene) || this;
  102531. _this._quaternionCache = new BABYLON.Quaternion();
  102532. _this.inputs.addDeviceOrientation();
  102533. return _this;
  102534. }
  102535. /**
  102536. * Gets the current instance class name ("DeviceOrientationCamera").
  102537. * This helps avoiding instanceof at run time.
  102538. * @returns the class name
  102539. */
  102540. DeviceOrientationCamera.prototype.getClassName = function () {
  102541. return "DeviceOrientationCamera";
  102542. };
  102543. /**
  102544. * @hidden
  102545. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  102546. */
  102547. DeviceOrientationCamera.prototype._checkInputs = function () {
  102548. _super.prototype._checkInputs.call(this);
  102549. this._quaternionCache.copyFrom(this.rotationQuaternion);
  102550. if (this._initialQuaternion) {
  102551. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  102552. }
  102553. };
  102554. /**
  102555. * Reset the camera to its default orientation on the specified axis only.
  102556. * @param axis The axis to reset
  102557. */
  102558. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  102559. var _this = this;
  102560. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  102561. //can only work if this camera has a rotation quaternion already.
  102562. if (!this.rotationQuaternion)
  102563. return;
  102564. if (!this._initialQuaternion) {
  102565. this._initialQuaternion = new BABYLON.Quaternion();
  102566. }
  102567. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  102568. ['x', 'y', 'z'].forEach(function (axisName) {
  102569. if (!axis[axisName]) {
  102570. _this._initialQuaternion[axisName] = 0;
  102571. }
  102572. else {
  102573. _this._initialQuaternion[axisName] *= -1;
  102574. }
  102575. });
  102576. this._initialQuaternion.normalize();
  102577. //force rotation update
  102578. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  102579. };
  102580. return DeviceOrientationCamera;
  102581. }(BABYLON.FreeCamera));
  102582. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  102583. })(BABYLON || (BABYLON = {}));
  102584. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  102585. var BABYLON;
  102586. (function (BABYLON) {
  102587. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  102588. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  102589. });
  102590. /**
  102591. * Camera used to simulate VR rendering (based on FreeCamera)
  102592. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  102593. */
  102594. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  102595. __extends(VRDeviceOrientationFreeCamera, _super);
  102596. /**
  102597. * Creates a new VRDeviceOrientationFreeCamera
  102598. * @param name defines camera name
  102599. * @param position defines the start position of the camera
  102600. * @param scene defines the scene the camera belongs to
  102601. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  102602. * @param vrCameraMetrics defines the vr metrics associated to the camera
  102603. */
  102604. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  102605. if (compensateDistortion === void 0) { compensateDistortion = true; }
  102606. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  102607. var _this = _super.call(this, name, position, scene) || this;
  102608. vrCameraMetrics.compensateDistortion = compensateDistortion;
  102609. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  102610. return _this;
  102611. }
  102612. /**
  102613. * Gets camera class name
  102614. * @returns VRDeviceOrientationFreeCamera
  102615. */
  102616. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  102617. return "VRDeviceOrientationFreeCamera";
  102618. };
  102619. return VRDeviceOrientationFreeCamera;
  102620. }(BABYLON.DeviceOrientationCamera));
  102621. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  102622. })(BABYLON || (BABYLON = {}));
  102623. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  102624. var BABYLON;
  102625. (function (BABYLON) {
  102626. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  102627. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  102628. });
  102629. /**
  102630. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  102631. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  102632. */
  102633. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  102634. __extends(VRDeviceOrientationArcRotateCamera, _super);
  102635. /**
  102636. * Creates a new VRDeviceOrientationArcRotateCamera
  102637. * @param name defines camera name
  102638. * @param alpha defines the camera rotation along the logitudinal axis
  102639. * @param beta defines the camera rotation along the latitudinal axis
  102640. * @param radius defines the camera distance from its target
  102641. * @param target defines the camera target
  102642. * @param scene defines the scene the camera belongs to
  102643. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  102644. * @param vrCameraMetrics defines the vr metrics associated to the camera
  102645. */
  102646. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  102647. if (compensateDistortion === void 0) { compensateDistortion = true; }
  102648. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  102649. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  102650. vrCameraMetrics.compensateDistortion = compensateDistortion;
  102651. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  102652. _this.inputs.addVRDeviceOrientation();
  102653. return _this;
  102654. }
  102655. /**
  102656. * Gets camera class name
  102657. * @returns VRDeviceOrientationArcRotateCamera
  102658. */
  102659. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  102660. return "VRDeviceOrientationArcRotateCamera";
  102661. };
  102662. return VRDeviceOrientationArcRotateCamera;
  102663. }(BABYLON.ArcRotateCamera));
  102664. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  102665. })(BABYLON || (BABYLON = {}));
  102666. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  102667. var BABYLON;
  102668. (function (BABYLON) {
  102669. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  102670. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  102671. });
  102672. /**
  102673. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  102674. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  102675. */
  102676. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  102677. __extends(VRDeviceOrientationGamepadCamera, _super);
  102678. /**
  102679. * Creates a new VRDeviceOrientationGamepadCamera
  102680. * @param name defines camera name
  102681. * @param position defines the start position of the camera
  102682. * @param scene defines the scene the camera belongs to
  102683. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  102684. * @param vrCameraMetrics defines the vr metrics associated to the camera
  102685. */
  102686. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  102687. if (compensateDistortion === void 0) { compensateDistortion = true; }
  102688. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  102689. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  102690. _this.inputs.addGamepad();
  102691. return _this;
  102692. }
  102693. /**
  102694. * Gets camera class name
  102695. * @returns VRDeviceOrientationGamepadCamera
  102696. */
  102697. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  102698. return "VRDeviceOrientationGamepadCamera";
  102699. };
  102700. return VRDeviceOrientationGamepadCamera;
  102701. }(BABYLON.VRDeviceOrientationFreeCamera));
  102702. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  102703. })(BABYLON || (BABYLON = {}));
  102704. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  102705. var BABYLON;
  102706. (function (BABYLON) {
  102707. var VRExperienceHelperGazer = /** @class */ (function () {
  102708. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  102709. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  102710. this.scene = scene;
  102711. /** @hidden */
  102712. this._pointerDownOnMeshAsked = false;
  102713. /** @hidden */
  102714. this._isActionableMesh = false;
  102715. /** @hidden */
  102716. this._teleportationRequestInitiated = false;
  102717. /** @hidden */
  102718. this._teleportationBackRequestInitiated = false;
  102719. /** @hidden */
  102720. this._rotationRightAsked = false;
  102721. /** @hidden */
  102722. this._rotationLeftAsked = false;
  102723. /** @hidden */
  102724. this._dpadPressed = true;
  102725. /** @hidden */
  102726. this._activePointer = false;
  102727. this._id = VRExperienceHelperGazer._idCounter++;
  102728. // Gaze tracker
  102729. if (!gazeTrackerToClone) {
  102730. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  102731. this._gazeTracker.bakeCurrentTransformIntoVertices();
  102732. this._gazeTracker.isPickable = false;
  102733. this._gazeTracker.isVisible = false;
  102734. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  102735. targetMat.specularColor = BABYLON.Color3.Black();
  102736. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  102737. targetMat.backFaceCulling = false;
  102738. this._gazeTracker.material = targetMat;
  102739. }
  102740. else {
  102741. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  102742. }
  102743. }
  102744. /** @hidden */
  102745. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  102746. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  102747. };
  102748. /** @hidden */
  102749. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  102750. this._pointerDownOnMeshAsked = true;
  102751. if (this._currentHit) {
  102752. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  102753. }
  102754. };
  102755. /** @hidden */
  102756. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  102757. if (this._currentHit) {
  102758. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  102759. }
  102760. this._pointerDownOnMeshAsked = false;
  102761. };
  102762. /** @hidden */
  102763. VRExperienceHelperGazer.prototype._activatePointer = function () {
  102764. this._activePointer = true;
  102765. };
  102766. /** @hidden */
  102767. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  102768. this._activePointer = false;
  102769. };
  102770. /** @hidden */
  102771. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  102772. if (distance === void 0) { distance = 100; }
  102773. };
  102774. VRExperienceHelperGazer.prototype.dispose = function () {
  102775. this._interactionsEnabled = false;
  102776. this._teleportationEnabled = false;
  102777. if (this._gazeTracker) {
  102778. this._gazeTracker.dispose();
  102779. }
  102780. };
  102781. VRExperienceHelperGazer._idCounter = 0;
  102782. return VRExperienceHelperGazer;
  102783. }());
  102784. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  102785. __extends(VRExperienceHelperControllerGazer, _super);
  102786. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  102787. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  102788. _this.webVRController = webVRController;
  102789. // Laser pointer
  102790. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  102791. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  102792. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  102793. laserPointerMaterial.alpha = 0.6;
  102794. _this._laserPointer.material = laserPointerMaterial;
  102795. _this._laserPointer.rotation.x = Math.PI / 2;
  102796. _this._laserPointer.position.z = -0.5;
  102797. _this._laserPointer.isVisible = false;
  102798. _this._laserPointer.isPickable = false;
  102799. if (!webVRController.mesh) {
  102800. // Create an empty mesh that is used prior to loading the high quality model
  102801. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  102802. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  102803. preloadPointerPose.rotation.x = -0.7;
  102804. preloadMesh.addChild(preloadPointerPose);
  102805. webVRController.attachToMesh(preloadMesh);
  102806. }
  102807. _this._setLaserPointerParent(webVRController.mesh);
  102808. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  102809. _this._setLaserPointerParent(mesh);
  102810. });
  102811. return _this;
  102812. }
  102813. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  102814. return this.webVRController.getForwardRay(length);
  102815. };
  102816. /** @hidden */
  102817. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  102818. _super.prototype._activatePointer.call(this);
  102819. this._laserPointer.isVisible = true;
  102820. };
  102821. /** @hidden */
  102822. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  102823. _super.prototype._deactivatePointer.call(this);
  102824. this._laserPointer.isVisible = false;
  102825. };
  102826. /** @hidden */
  102827. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  102828. this._laserPointer.material.emissiveColor = color;
  102829. };
  102830. /** @hidden */
  102831. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  102832. var makeNotPick = function (root) {
  102833. root.isPickable = false;
  102834. root.getChildMeshes().forEach(function (c) {
  102835. makeNotPick(c);
  102836. });
  102837. };
  102838. makeNotPick(mesh);
  102839. var childMeshes = mesh.getChildMeshes();
  102840. this.webVRController._pointingPoseNode = null;
  102841. for (var i = 0; i < childMeshes.length; i++) {
  102842. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  102843. mesh = childMeshes[i];
  102844. this.webVRController._pointingPoseNode = mesh;
  102845. break;
  102846. }
  102847. }
  102848. this._laserPointer.parent = mesh;
  102849. };
  102850. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  102851. if (distance === void 0) { distance = 100; }
  102852. this._laserPointer.scaling.y = distance;
  102853. this._laserPointer.position.z = -distance / 2;
  102854. };
  102855. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  102856. _super.prototype.dispose.call(this);
  102857. this._laserPointer.dispose();
  102858. if (this._meshAttachedObserver) {
  102859. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  102860. }
  102861. };
  102862. return VRExperienceHelperControllerGazer;
  102863. }(VRExperienceHelperGazer));
  102864. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  102865. __extends(VRExperienceHelperCameraGazer, _super);
  102866. function VRExperienceHelperCameraGazer(getCamera, scene) {
  102867. var _this = _super.call(this, scene) || this;
  102868. _this.getCamera = getCamera;
  102869. return _this;
  102870. }
  102871. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  102872. var camera = this.getCamera();
  102873. if (camera) {
  102874. return camera.getForwardRay(length);
  102875. }
  102876. else {
  102877. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  102878. }
  102879. };
  102880. return VRExperienceHelperCameraGazer;
  102881. }(VRExperienceHelperGazer));
  102882. /**
  102883. * Helps to quickly add VR support to an existing scene.
  102884. * See http://doc.babylonjs.com/how_to/webvr_helper
  102885. */
  102886. var VRExperienceHelper = /** @class */ (function () {
  102887. /**
  102888. * Instantiates a VRExperienceHelper.
  102889. * Helps to quickly add VR support to an existing scene.
  102890. * @param scene The scene the VRExperienceHelper belongs to.
  102891. * @param webVROptions Options to modify the vr experience helper's behavior.
  102892. */
  102893. function VRExperienceHelper(scene,
  102894. /** Options to modify the vr experience helper's behavior. */
  102895. webVROptions) {
  102896. if (webVROptions === void 0) { webVROptions = {}; }
  102897. var _this = this;
  102898. this.webVROptions = webVROptions;
  102899. // Can the system support WebVR, even if a headset isn't plugged in?
  102900. this._webVRsupported = false;
  102901. // If WebVR is supported, is a headset plugged in and are we ready to present?
  102902. this._webVRready = false;
  102903. // Are we waiting for the requestPresent callback to complete?
  102904. this._webVRrequesting = false;
  102905. // Are we presenting to the headset right now? (this is the vrDevice state)
  102906. this._webVRpresenting = false;
  102907. // Are we presenting in the fullscreen fallback?
  102908. this._fullscreenVRpresenting = false;
  102909. /**
  102910. * Observable raised when entering VR.
  102911. */
  102912. this.onEnteringVRObservable = new BABYLON.Observable();
  102913. /**
  102914. * Observable raised when exiting VR.
  102915. */
  102916. this.onExitingVRObservable = new BABYLON.Observable();
  102917. /**
  102918. * Observable raised when controller mesh is loaded.
  102919. */
  102920. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  102921. this._useCustomVRButton = false;
  102922. this._teleportationRequested = false;
  102923. this._teleportActive = false;
  102924. this._floorMeshesCollection = [];
  102925. this._rotationAllowed = true;
  102926. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  102927. this._isDefaultTeleportationTarget = true;
  102928. this._teleportationFillColor = "#444444";
  102929. this._teleportationBorderColor = "#FFFFFF";
  102930. this._rotationAngle = 0;
  102931. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  102932. this._padSensibilityUp = 0.65;
  102933. this._padSensibilityDown = 0.35;
  102934. this._leftController = null;
  102935. this._rightController = null;
  102936. /**
  102937. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  102938. */
  102939. this.onNewMeshSelected = new BABYLON.Observable();
  102940. /**
  102941. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  102942. */
  102943. this.onNewMeshPicked = new BABYLON.Observable();
  102944. /**
  102945. * Observable raised before camera teleportation
  102946. */
  102947. this.onBeforeCameraTeleport = new BABYLON.Observable();
  102948. /**
  102949. * Observable raised after camera teleportation
  102950. */
  102951. this.onAfterCameraTeleport = new BABYLON.Observable();
  102952. /**
  102953. * Observable raised when current selected mesh gets unselected
  102954. */
  102955. this.onSelectedMeshUnselected = new BABYLON.Observable();
  102956. /**
  102957. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  102958. */
  102959. this.teleportationEnabled = true;
  102960. this._teleportationInitialized = false;
  102961. this._interactionsEnabled = false;
  102962. this._interactionsRequested = false;
  102963. this._displayGaze = true;
  102964. this._displayLaserPointer = true;
  102965. /**
  102966. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  102967. */
  102968. this.updateGazeTrackerScale = true;
  102969. this._onResize = function () {
  102970. _this.moveButtonToBottomRight();
  102971. if (_this._fullscreenVRpresenting && _this._webVRready) {
  102972. _this.exitVR();
  102973. }
  102974. };
  102975. this._onFullscreenChange = function () {
  102976. if (document.fullscreen !== undefined) {
  102977. _this._fullscreenVRpresenting = document.fullscreen;
  102978. }
  102979. else if (document.mozFullScreen !== undefined) {
  102980. _this._fullscreenVRpresenting = document.mozFullScreen;
  102981. }
  102982. else if (document.webkitIsFullScreen !== undefined) {
  102983. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  102984. }
  102985. else if (document.msIsFullScreen !== undefined) {
  102986. _this._fullscreenVRpresenting = document.msIsFullScreen;
  102987. }
  102988. else if (document.msFullscreenElement !== undefined) {
  102989. _this._fullscreenVRpresenting = document.msFullscreenElement;
  102990. }
  102991. if (!_this._fullscreenVRpresenting && _this._canvas) {
  102992. _this.exitVR();
  102993. if (!_this._useCustomVRButton) {
  102994. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  102995. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  102996. }
  102997. }
  102998. };
  102999. this.beforeRender = function () {
  103000. if (_this._leftController && _this._leftController._activePointer) {
  103001. _this._castRayAndSelectObject(_this._leftController);
  103002. }
  103003. if (_this._rightController && _this._rightController._activePointer) {
  103004. _this._castRayAndSelectObject(_this._rightController);
  103005. }
  103006. if (_this._noControllerIsActive) {
  103007. _this._castRayAndSelectObject(_this._cameraGazer);
  103008. }
  103009. else {
  103010. _this._cameraGazer._gazeTracker.isVisible = false;
  103011. }
  103012. };
  103013. this._onNewGamepadConnected = function (gamepad) {
  103014. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  103015. if (gamepad.leftStick) {
  103016. gamepad.onleftstickchanged(function (stickValues) {
  103017. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  103018. // Listening to classic/xbox gamepad only if no VR controller is active
  103019. if ((!_this._leftController && !_this._rightController) ||
  103020. ((_this._leftController && !_this._leftController._activePointer) &&
  103021. (_this._rightController && !_this._rightController._activePointer))) {
  103022. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  103023. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  103024. }
  103025. }
  103026. });
  103027. }
  103028. if (gamepad.rightStick) {
  103029. gamepad.onrightstickchanged(function (stickValues) {
  103030. if (_this._teleportationInitialized) {
  103031. _this._checkRotate(stickValues, _this._cameraGazer);
  103032. }
  103033. });
  103034. }
  103035. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  103036. gamepad.onbuttondown(function (buttonPressed) {
  103037. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  103038. _this._cameraGazer._selectionPointerDown();
  103039. }
  103040. });
  103041. gamepad.onbuttonup(function (buttonPressed) {
  103042. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  103043. _this._cameraGazer._selectionPointerUp();
  103044. }
  103045. });
  103046. }
  103047. }
  103048. else {
  103049. var webVRController = gamepad;
  103050. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  103051. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  103052. _this._rightController = controller;
  103053. }
  103054. else {
  103055. _this._leftController = controller;
  103056. }
  103057. _this._tryEnableInteractionOnController(controller);
  103058. }
  103059. };
  103060. // 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
  103061. this._tryEnableInteractionOnController = function (controller) {
  103062. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  103063. _this._enableInteractionOnController(controller);
  103064. }
  103065. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  103066. _this._enableTeleportationOnController(controller);
  103067. }
  103068. };
  103069. this._onNewGamepadDisconnected = function (gamepad) {
  103070. if (gamepad instanceof BABYLON.WebVRController) {
  103071. if (gamepad.hand === "left" && _this._leftController != null) {
  103072. _this._leftController.dispose();
  103073. _this._leftController = null;
  103074. }
  103075. if (gamepad.hand === "right" && _this._rightController != null) {
  103076. _this._rightController.dispose();
  103077. _this._rightController = null;
  103078. }
  103079. }
  103080. };
  103081. this._workingVector = BABYLON.Vector3.Zero();
  103082. this._workingQuaternion = BABYLON.Quaternion.Identity();
  103083. this._workingMatrix = BABYLON.Matrix.Identity();
  103084. this._scene = scene;
  103085. this._canvas = scene.getEngine().getRenderingCanvas();
  103086. // Parse options
  103087. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  103088. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  103089. }
  103090. if (webVROptions.createDeviceOrientationCamera === undefined) {
  103091. webVROptions.createDeviceOrientationCamera = true;
  103092. }
  103093. if (webVROptions.laserToggle === undefined) {
  103094. webVROptions.laserToggle = true;
  103095. }
  103096. if (webVROptions.defaultHeight === undefined) {
  103097. webVROptions.defaultHeight = 1.7;
  103098. }
  103099. if (webVROptions.useCustomVRButton) {
  103100. this._useCustomVRButton = true;
  103101. if (webVROptions.customVRButton) {
  103102. this._btnVR = webVROptions.customVRButton;
  103103. }
  103104. }
  103105. if (webVROptions.rayLength) {
  103106. this._rayLength = webVROptions.rayLength;
  103107. }
  103108. this._defaultHeight = webVROptions.defaultHeight;
  103109. if (webVROptions.positionScale) {
  103110. this._rayLength *= webVROptions.positionScale;
  103111. this._defaultHeight *= webVROptions.positionScale;
  103112. }
  103113. this._hasEnteredVR = false;
  103114. // Set position
  103115. if (this._scene.activeCamera) {
  103116. this._position = this._scene.activeCamera.position.clone();
  103117. }
  103118. else {
  103119. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  103120. }
  103121. // Set non-vr camera
  103122. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  103123. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  103124. // Copy data from existing camera
  103125. if (this._scene.activeCamera) {
  103126. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  103127. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  103128. // Set rotation from previous camera
  103129. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  103130. var targetCamera = this._scene.activeCamera;
  103131. if (targetCamera.rotationQuaternion) {
  103132. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  103133. }
  103134. else {
  103135. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  103136. }
  103137. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  103138. }
  103139. }
  103140. this._scene.activeCamera = this._deviceOrientationCamera;
  103141. if (this._canvas) {
  103142. this._scene.activeCamera.attachControl(this._canvas);
  103143. }
  103144. }
  103145. else {
  103146. this._existingCamera = this._scene.activeCamera;
  103147. }
  103148. // Create VR cameras
  103149. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  103150. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  103151. }
  103152. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  103153. this._webVRCamera.useStandingMatrix();
  103154. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  103155. // Create default button
  103156. if (!this._useCustomVRButton) {
  103157. this._btnVR = document.createElement("BUTTON");
  103158. this._btnVR.className = "babylonVRicon";
  103159. this._btnVR.id = "babylonVRiconbtn";
  103160. this._btnVR.title = "Click to switch to VR";
  103161. 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) }";
  103162. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  103163. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  103164. // css += ".babylonVRicon.vrdisplaysupported { }";
  103165. // css += ".babylonVRicon.vrdisplayready { }";
  103166. // css += ".babylonVRicon.vrdisplayrequesting { }";
  103167. var style = document.createElement('style');
  103168. style.appendChild(document.createTextNode(css));
  103169. document.getElementsByTagName('head')[0].appendChild(style);
  103170. this.moveButtonToBottomRight();
  103171. }
  103172. // VR button click event
  103173. if (this._btnVR) {
  103174. this._btnVR.addEventListener("click", function () {
  103175. if (!_this.isInVRMode) {
  103176. _this.enterVR();
  103177. }
  103178. else {
  103179. _this.exitVR();
  103180. }
  103181. });
  103182. }
  103183. // Window events
  103184. window.addEventListener("resize", this._onResize);
  103185. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  103186. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  103187. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  103188. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  103189. document.onmsfullscreenchange = this._onFullscreenChange;
  103190. // Display vr button when headset is connected
  103191. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  103192. this.displayVRButton();
  103193. }
  103194. else {
  103195. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  103196. if (e.vrDisplay) {
  103197. _this.displayVRButton();
  103198. }
  103199. });
  103200. }
  103201. // Exiting VR mode using 'ESC' key on desktop
  103202. this._onKeyDown = function (event) {
  103203. if (event.keyCode === 27 && _this.isInVRMode) {
  103204. _this.exitVR();
  103205. }
  103206. };
  103207. document.addEventListener("keydown", this._onKeyDown);
  103208. // Exiting VR mode double tapping the touch screen
  103209. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  103210. if (_this.isInVRMode) {
  103211. _this.exitVR();
  103212. if (_this._fullscreenVRpresenting) {
  103213. _this._scene.getEngine().switchFullscreen(true);
  103214. }
  103215. }
  103216. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  103217. // Listen for WebVR display changes
  103218. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  103219. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  103220. this._onVRRequestPresentStart = function () {
  103221. _this._webVRrequesting = true;
  103222. _this.updateButtonVisibility();
  103223. };
  103224. this._onVRRequestPresentComplete = function (success) {
  103225. _this._webVRrequesting = false;
  103226. _this.updateButtonVisibility();
  103227. };
  103228. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  103229. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  103230. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  103231. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  103232. scene.onDisposeObservable.add(function () {
  103233. _this.dispose();
  103234. });
  103235. // Gamepad connection events
  103236. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  103237. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  103238. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  103239. this.updateButtonVisibility();
  103240. //create easing functions
  103241. this._circleEase = new BABYLON.CircleEase();
  103242. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  103243. if (this.webVROptions.floorMeshes) {
  103244. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  103245. }
  103246. }
  103247. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  103248. /** Return this.onEnteringVRObservable
  103249. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  103250. */
  103251. get: function () {
  103252. return this.onEnteringVRObservable;
  103253. },
  103254. enumerable: true,
  103255. configurable: true
  103256. });
  103257. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  103258. /** Return this.onExitingVRObservable
  103259. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  103260. */
  103261. get: function () {
  103262. return this.onExitingVRObservable;
  103263. },
  103264. enumerable: true,
  103265. configurable: true
  103266. });
  103267. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  103268. /** Return this.onControllerMeshLoadedObservable
  103269. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  103270. */
  103271. get: function () {
  103272. return this.onControllerMeshLoadedObservable;
  103273. },
  103274. enumerable: true,
  103275. configurable: true
  103276. });
  103277. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  103278. /**
  103279. * The mesh used to display where the user is going to teleport.
  103280. */
  103281. get: function () {
  103282. return this._teleportationTarget;
  103283. },
  103284. /**
  103285. * Sets the mesh to be used to display where the user is going to teleport.
  103286. */
  103287. set: function (value) {
  103288. if (value) {
  103289. value.name = "teleportationTarget";
  103290. this._isDefaultTeleportationTarget = false;
  103291. this._teleportationTarget = value;
  103292. }
  103293. },
  103294. enumerable: true,
  103295. configurable: true
  103296. });
  103297. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  103298. /**
  103299. * 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
  103300. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  103301. * See http://doc.babylonjs.com/resources/baking_transformations
  103302. */
  103303. get: function () {
  103304. return this._cameraGazer._gazeTracker;
  103305. },
  103306. set: function (value) {
  103307. if (value) {
  103308. // Dispose of existing meshes
  103309. if (this._cameraGazer._gazeTracker) {
  103310. this._cameraGazer._gazeTracker.dispose();
  103311. }
  103312. if (this._leftController && this._leftController._gazeTracker) {
  103313. this._leftController._gazeTracker.dispose();
  103314. }
  103315. if (this._rightController && this._rightController._gazeTracker) {
  103316. this._rightController._gazeTracker.dispose();
  103317. }
  103318. // Set and create gaze trackers on head and controllers
  103319. this._cameraGazer._gazeTracker = value;
  103320. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  103321. this._cameraGazer._gazeTracker.isPickable = false;
  103322. this._cameraGazer._gazeTracker.isVisible = false;
  103323. this._cameraGazer._gazeTracker.name = "gazeTracker";
  103324. if (this._leftController) {
  103325. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  103326. }
  103327. if (this._rightController) {
  103328. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  103329. }
  103330. }
  103331. },
  103332. enumerable: true,
  103333. configurable: true
  103334. });
  103335. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  103336. /**
  103337. * The gaze tracking mesh corresponding to the left controller
  103338. */
  103339. get: function () {
  103340. if (this._leftController) {
  103341. return this._leftController._gazeTracker;
  103342. }
  103343. return null;
  103344. },
  103345. enumerable: true,
  103346. configurable: true
  103347. });
  103348. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  103349. /**
  103350. * The gaze tracking mesh corresponding to the right controller
  103351. */
  103352. get: function () {
  103353. if (this._rightController) {
  103354. return this._rightController._gazeTracker;
  103355. }
  103356. return null;
  103357. },
  103358. enumerable: true,
  103359. configurable: true
  103360. });
  103361. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  103362. /**
  103363. * If the ray of the gaze should be displayed.
  103364. */
  103365. get: function () {
  103366. return this._displayGaze;
  103367. },
  103368. /**
  103369. * Sets if the ray of the gaze should be displayed.
  103370. */
  103371. set: function (value) {
  103372. this._displayGaze = value;
  103373. if (!value) {
  103374. this._cameraGazer._gazeTracker.isVisible = false;
  103375. if (this._leftController) {
  103376. this._leftController._gazeTracker.isVisible = false;
  103377. }
  103378. if (this._rightController) {
  103379. this._rightController._gazeTracker.isVisible = false;
  103380. }
  103381. }
  103382. },
  103383. enumerable: true,
  103384. configurable: true
  103385. });
  103386. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  103387. /**
  103388. * If the ray of the LaserPointer should be displayed.
  103389. */
  103390. get: function () {
  103391. return this._displayLaserPointer;
  103392. },
  103393. /**
  103394. * Sets if the ray of the LaserPointer should be displayed.
  103395. */
  103396. set: function (value) {
  103397. this._displayLaserPointer = value;
  103398. if (!value) {
  103399. if (this._rightController) {
  103400. this._rightController._deactivatePointer();
  103401. this._rightController._gazeTracker.isVisible = false;
  103402. }
  103403. if (this._leftController) {
  103404. this._leftController._deactivatePointer();
  103405. this._leftController._gazeTracker.isVisible = false;
  103406. }
  103407. }
  103408. else {
  103409. if (this._rightController) {
  103410. this._rightController._activatePointer();
  103411. }
  103412. if (this._leftController) {
  103413. this._leftController._activatePointer();
  103414. }
  103415. }
  103416. },
  103417. enumerable: true,
  103418. configurable: true
  103419. });
  103420. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  103421. /**
  103422. * The deviceOrientationCamera used as the camera when not in VR.
  103423. */
  103424. get: function () {
  103425. return this._deviceOrientationCamera;
  103426. },
  103427. enumerable: true,
  103428. configurable: true
  103429. });
  103430. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  103431. /**
  103432. * Based on the current WebVR support, returns the current VR camera used.
  103433. */
  103434. get: function () {
  103435. if (this._webVRready) {
  103436. return this._webVRCamera;
  103437. }
  103438. else {
  103439. return this._scene.activeCamera;
  103440. }
  103441. },
  103442. enumerable: true,
  103443. configurable: true
  103444. });
  103445. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  103446. /**
  103447. * The webVRCamera which is used when in VR.
  103448. */
  103449. get: function () {
  103450. return this._webVRCamera;
  103451. },
  103452. enumerable: true,
  103453. configurable: true
  103454. });
  103455. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  103456. /**
  103457. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  103458. */
  103459. get: function () {
  103460. return this._vrDeviceOrientationCamera;
  103461. },
  103462. enumerable: true,
  103463. configurable: true
  103464. });
  103465. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  103466. get: function () {
  103467. var result = this._cameraGazer._teleportationRequestInitiated
  103468. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  103469. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  103470. return result;
  103471. },
  103472. enumerable: true,
  103473. configurable: true
  103474. });
  103475. // Raised when one of the controller has loaded successfully its associated default mesh
  103476. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  103477. if (this._leftController && this._leftController.webVRController == webVRController) {
  103478. if (webVRController.mesh) {
  103479. this._leftController._setLaserPointerParent(webVRController.mesh);
  103480. }
  103481. }
  103482. if (this._rightController && this._rightController.webVRController == webVRController) {
  103483. if (webVRController.mesh) {
  103484. this._rightController._setLaserPointerParent(webVRController.mesh);
  103485. }
  103486. }
  103487. try {
  103488. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  103489. }
  103490. catch (err) {
  103491. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  103492. }
  103493. };
  103494. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  103495. /**
  103496. * Gets a value indicating if we are currently in VR mode.
  103497. */
  103498. get: function () {
  103499. return this._webVRpresenting || this._fullscreenVRpresenting;
  103500. },
  103501. enumerable: true,
  103502. configurable: true
  103503. });
  103504. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  103505. var vrDisplay = this._scene.getEngine().getVRDevice();
  103506. if (vrDisplay) {
  103507. var wasPresenting = this._webVRpresenting;
  103508. this._webVRpresenting = vrDisplay.isPresenting;
  103509. if (wasPresenting && !this._webVRpresenting)
  103510. this.exitVR();
  103511. }
  103512. else {
  103513. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  103514. }
  103515. this.updateButtonVisibility();
  103516. };
  103517. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  103518. this._webVRsupported = eventArgs.vrSupported;
  103519. this._webVRready = !!eventArgs.vrDisplay;
  103520. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  103521. this.updateButtonVisibility();
  103522. };
  103523. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  103524. if (this._canvas && !this._useCustomVRButton) {
  103525. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  103526. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  103527. }
  103528. };
  103529. VRExperienceHelper.prototype.displayVRButton = function () {
  103530. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  103531. document.body.appendChild(this._btnVR);
  103532. this._btnVRDisplayed = true;
  103533. }
  103534. };
  103535. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  103536. if (!this._btnVR || this._useCustomVRButton) {
  103537. return;
  103538. }
  103539. this._btnVR.className = "babylonVRicon";
  103540. if (this.isInVRMode) {
  103541. this._btnVR.className += " vrdisplaypresenting";
  103542. }
  103543. else {
  103544. if (this._webVRready)
  103545. this._btnVR.className += " vrdisplayready";
  103546. if (this._webVRsupported)
  103547. this._btnVR.className += " vrdisplaysupported";
  103548. if (this._webVRrequesting)
  103549. this._btnVR.className += " vrdisplayrequesting";
  103550. }
  103551. };
  103552. /**
  103553. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  103554. * Otherwise, will use the fullscreen API.
  103555. */
  103556. VRExperienceHelper.prototype.enterVR = function () {
  103557. if (this.onEnteringVRObservable) {
  103558. try {
  103559. this.onEnteringVRObservable.notifyObservers(this);
  103560. }
  103561. catch (err) {
  103562. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  103563. }
  103564. }
  103565. if (this._scene.activeCamera) {
  103566. this._position = this._scene.activeCamera.position.clone();
  103567. // make sure that we return to the last active camera
  103568. this._existingCamera = this._scene.activeCamera;
  103569. }
  103570. if (this._webVRrequesting)
  103571. return;
  103572. // If WebVR is supported and a headset is connected
  103573. if (this._webVRready) {
  103574. if (!this._webVRpresenting) {
  103575. this._webVRCamera.position = this._position;
  103576. this._scene.activeCamera = this._webVRCamera;
  103577. }
  103578. }
  103579. else if (this._vrDeviceOrientationCamera) {
  103580. this._vrDeviceOrientationCamera.position = this._position;
  103581. if (this._scene.activeCamera) {
  103582. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  103583. }
  103584. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  103585. this._scene.getEngine().switchFullscreen(true);
  103586. this.updateButtonVisibility();
  103587. }
  103588. if (this._scene.activeCamera && this._canvas) {
  103589. this._scene.activeCamera.attachControl(this._canvas);
  103590. }
  103591. if (this._interactionsEnabled) {
  103592. this._scene.registerBeforeRender(this.beforeRender);
  103593. }
  103594. this._hasEnteredVR = true;
  103595. };
  103596. /**
  103597. * Attempt to exit VR, or fullscreen.
  103598. */
  103599. VRExperienceHelper.prototype.exitVR = function () {
  103600. if (this._hasEnteredVR) {
  103601. if (this.onExitingVRObservable) {
  103602. try {
  103603. this.onExitingVRObservable.notifyObservers(this);
  103604. }
  103605. catch (err) {
  103606. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  103607. }
  103608. }
  103609. if (this._webVRpresenting) {
  103610. this._scene.getEngine().disableVR();
  103611. }
  103612. if (this._scene.activeCamera) {
  103613. this._position = this._scene.activeCamera.position.clone();
  103614. }
  103615. if (this._deviceOrientationCamera) {
  103616. this._deviceOrientationCamera.position = this._position;
  103617. this._scene.activeCamera = this._deviceOrientationCamera;
  103618. if (this._canvas) {
  103619. this._scene.activeCamera.attachControl(this._canvas);
  103620. }
  103621. }
  103622. else if (this._existingCamera) {
  103623. this._existingCamera.position = this._position;
  103624. this._scene.activeCamera = this._existingCamera;
  103625. }
  103626. this.updateButtonVisibility();
  103627. if (this._interactionsEnabled) {
  103628. this._scene.unregisterBeforeRender(this.beforeRender);
  103629. this._cameraGazer._gazeTracker.isVisible = false;
  103630. if (this._leftController) {
  103631. this._leftController._gazeTracker.isVisible = false;
  103632. }
  103633. if (this._rightController) {
  103634. this._rightController._gazeTracker.isVisible = false;
  103635. }
  103636. }
  103637. // resize to update width and height when exiting vr exits fullscreen
  103638. this._scene.getEngine().resize();
  103639. this._hasEnteredVR = false;
  103640. }
  103641. };
  103642. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  103643. /**
  103644. * The position of the vr experience helper.
  103645. */
  103646. get: function () {
  103647. return this._position;
  103648. },
  103649. /**
  103650. * Sets the position of the vr experience helper.
  103651. */
  103652. set: function (value) {
  103653. this._position = value;
  103654. if (this._scene.activeCamera) {
  103655. this._scene.activeCamera.position = value;
  103656. }
  103657. },
  103658. enumerable: true,
  103659. configurable: true
  103660. });
  103661. /**
  103662. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  103663. */
  103664. VRExperienceHelper.prototype.enableInteractions = function () {
  103665. var _this = this;
  103666. if (!this._interactionsEnabled) {
  103667. this._interactionsRequested = true;
  103668. if (this._leftController) {
  103669. this._enableInteractionOnController(this._leftController);
  103670. }
  103671. if (this._rightController) {
  103672. this._enableInteractionOnController(this._rightController);
  103673. }
  103674. this.raySelectionPredicate = function (mesh) {
  103675. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  103676. };
  103677. this.meshSelectionPredicate = function (mesh) {
  103678. return true;
  103679. };
  103680. this._raySelectionPredicate = function (mesh) {
  103681. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  103682. && mesh.name.indexOf("teleportationTarget") === -1
  103683. && mesh.name.indexOf("torusTeleportation") === -1)) {
  103684. return _this.raySelectionPredicate(mesh);
  103685. }
  103686. return false;
  103687. };
  103688. this._interactionsEnabled = true;
  103689. }
  103690. };
  103691. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  103692. get: function () {
  103693. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  103694. },
  103695. enumerable: true,
  103696. configurable: true
  103697. });
  103698. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  103699. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  103700. if (this._floorMeshesCollection[i].id === mesh.id) {
  103701. return true;
  103702. }
  103703. }
  103704. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  103705. return true;
  103706. }
  103707. return false;
  103708. };
  103709. /**
  103710. * Adds a floor mesh to be used for teleportation.
  103711. * @param floorMesh the mesh to be used for teleportation.
  103712. */
  103713. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  103714. if (!this._floorMeshesCollection) {
  103715. return;
  103716. }
  103717. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  103718. return;
  103719. }
  103720. this._floorMeshesCollection.push(floorMesh);
  103721. };
  103722. /**
  103723. * Removes a floor mesh from being used for teleportation.
  103724. * @param floorMesh the mesh to be removed.
  103725. */
  103726. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  103727. if (!this._floorMeshesCollection) {
  103728. return;
  103729. }
  103730. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  103731. if (meshIndex !== -1) {
  103732. this._floorMeshesCollection.splice(meshIndex, 1);
  103733. }
  103734. };
  103735. /**
  103736. * Enables interactions and teleportation using the VR controllers and gaze.
  103737. * @param vrTeleportationOptions options to modify teleportation behavior.
  103738. */
  103739. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  103740. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  103741. if (!this._teleportationInitialized) {
  103742. this._teleportationRequested = true;
  103743. this.enableInteractions();
  103744. if (vrTeleportationOptions.floorMeshName) {
  103745. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  103746. }
  103747. if (vrTeleportationOptions.floorMeshes) {
  103748. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  103749. }
  103750. if (this._leftController != null) {
  103751. this._enableTeleportationOnController(this._leftController);
  103752. }
  103753. if (this._rightController != null) {
  103754. this._enableTeleportationOnController(this._rightController);
  103755. }
  103756. // Creates an image processing post process for the vignette not relying
  103757. // on the main scene configuration for image processing to reduce setup and spaces
  103758. // (gamma/linear) conflicts.
  103759. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  103760. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  103761. imageProcessingConfiguration.vignetteEnabled = true;
  103762. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  103763. this._webVRCamera.detachPostProcess(this._postProcessMove);
  103764. this._teleportationInitialized = true;
  103765. if (this._isDefaultTeleportationTarget) {
  103766. this._createTeleportationCircles();
  103767. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  103768. }
  103769. }
  103770. };
  103771. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  103772. var _this = this;
  103773. var controllerMesh = controller.webVRController.mesh;
  103774. if (controllerMesh) {
  103775. controller._interactionsEnabled = true;
  103776. controller._activatePointer();
  103777. if (this.webVROptions.laserToggle) {
  103778. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  103779. // Enabling / disabling laserPointer
  103780. if (_this._displayLaserPointer && stateObject.value === 1) {
  103781. if (controller._activePointer) {
  103782. controller._deactivatePointer();
  103783. }
  103784. else {
  103785. controller._activatePointer();
  103786. }
  103787. if (_this.displayGaze) {
  103788. controller._gazeTracker.isVisible = controller._activePointer;
  103789. }
  103790. }
  103791. });
  103792. }
  103793. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  103794. var gazer = controller;
  103795. if (_this._noControllerIsActive) {
  103796. gazer = _this._cameraGazer;
  103797. }
  103798. if (!gazer._pointerDownOnMeshAsked) {
  103799. if (stateObject.value > _this._padSensibilityUp) {
  103800. gazer._selectionPointerDown();
  103801. }
  103802. }
  103803. else if (stateObject.value < _this._padSensibilityDown) {
  103804. gazer._selectionPointerUp();
  103805. }
  103806. });
  103807. }
  103808. };
  103809. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  103810. // Dont teleport if another gaze already requested teleportation
  103811. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  103812. return;
  103813. }
  103814. if (!gazer._teleportationRequestInitiated) {
  103815. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  103816. gazer._activatePointer();
  103817. gazer._teleportationRequestInitiated = true;
  103818. }
  103819. }
  103820. else {
  103821. // Listening to the proper controller values changes to confirm teleportation
  103822. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  103823. if (this._teleportActive) {
  103824. this.teleportCamera(this._haloCenter);
  103825. }
  103826. gazer._teleportationRequestInitiated = false;
  103827. }
  103828. }
  103829. };
  103830. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  103831. // Only rotate when user is not currently selecting a teleportation location
  103832. if (gazer._teleportationRequestInitiated) {
  103833. return;
  103834. }
  103835. if (!gazer._rotationLeftAsked) {
  103836. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  103837. gazer._rotationLeftAsked = true;
  103838. if (this._rotationAllowed) {
  103839. this._rotateCamera(false);
  103840. }
  103841. }
  103842. }
  103843. else {
  103844. if (stateObject.x > -this._padSensibilityDown) {
  103845. gazer._rotationLeftAsked = false;
  103846. }
  103847. }
  103848. if (!gazer._rotationRightAsked) {
  103849. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  103850. gazer._rotationRightAsked = true;
  103851. if (this._rotationAllowed) {
  103852. this._rotateCamera(true);
  103853. }
  103854. }
  103855. }
  103856. else {
  103857. if (stateObject.x < this._padSensibilityDown) {
  103858. gazer._rotationRightAsked = false;
  103859. }
  103860. }
  103861. };
  103862. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  103863. // Only teleport backwards when user is not currently selecting a teleportation location
  103864. if (gazer._teleportationRequestInitiated) {
  103865. return;
  103866. }
  103867. // Teleport backwards
  103868. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  103869. if (!gazer._teleportationBackRequestInitiated) {
  103870. if (!this.currentVRCamera) {
  103871. return;
  103872. }
  103873. // Get rotation and position of the current camera
  103874. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  103875. var position = this.currentVRCamera.position;
  103876. // If the camera has device position, use that instead
  103877. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  103878. rotation = this.currentVRCamera.deviceRotationQuaternion;
  103879. position = this.currentVRCamera.devicePosition;
  103880. }
  103881. // Get matrix with only the y rotation of the device rotation
  103882. rotation.toEulerAnglesToRef(this._workingVector);
  103883. this._workingVector.z = 0;
  103884. this._workingVector.x = 0;
  103885. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  103886. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  103887. // Rotate backwards ray by device rotation to cast at the ground behind the user
  103888. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  103889. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  103890. var ray = new BABYLON.Ray(position, this._workingVector);
  103891. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  103892. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  103893. this.teleportCamera(hit.pickedPoint);
  103894. }
  103895. gazer._teleportationBackRequestInitiated = true;
  103896. }
  103897. }
  103898. else {
  103899. gazer._teleportationBackRequestInitiated = false;
  103900. }
  103901. };
  103902. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  103903. var _this = this;
  103904. var controllerMesh = controller.webVRController.mesh;
  103905. if (controllerMesh) {
  103906. if (!controller._interactionsEnabled) {
  103907. this._enableInteractionOnController(controller);
  103908. }
  103909. controller._interactionsEnabled = true;
  103910. controller._teleportationEnabled = true;
  103911. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  103912. controller._dpadPressed = false;
  103913. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  103914. controller._dpadPressed = stateObject.pressed;
  103915. if (!controller._dpadPressed) {
  103916. controller._rotationLeftAsked = false;
  103917. controller._rotationRightAsked = false;
  103918. controller._teleportationBackRequestInitiated = false;
  103919. }
  103920. });
  103921. }
  103922. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  103923. if (_this.teleportationEnabled) {
  103924. _this._checkTeleportBackwards(stateObject, controller);
  103925. _this._checkTeleportWithRay(stateObject, controller);
  103926. }
  103927. _this._checkRotate(stateObject, controller);
  103928. });
  103929. }
  103930. };
  103931. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  103932. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  103933. this._teleportationTarget.isPickable = false;
  103934. var length = 512;
  103935. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  103936. dynamicTexture.hasAlpha = true;
  103937. var context = dynamicTexture.getContext();
  103938. var centerX = length / 2;
  103939. var centerY = length / 2;
  103940. var radius = 200;
  103941. context.beginPath();
  103942. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  103943. context.fillStyle = this._teleportationFillColor;
  103944. context.fill();
  103945. context.lineWidth = 10;
  103946. context.strokeStyle = this._teleportationBorderColor;
  103947. context.stroke();
  103948. context.closePath();
  103949. dynamicTexture.update();
  103950. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  103951. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  103952. this._teleportationTarget.material = teleportationCircleMaterial;
  103953. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  103954. torus.isPickable = false;
  103955. torus.parent = this._teleportationTarget;
  103956. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  103957. var keys = [];
  103958. keys.push({
  103959. frame: 0,
  103960. value: 0
  103961. });
  103962. keys.push({
  103963. frame: 30,
  103964. value: 0.4
  103965. });
  103966. keys.push({
  103967. frame: 60,
  103968. value: 0
  103969. });
  103970. animationInnerCircle.setKeys(keys);
  103971. var easingFunction = new BABYLON.SineEase();
  103972. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  103973. animationInnerCircle.setEasingFunction(easingFunction);
  103974. torus.animations = [];
  103975. torus.animations.push(animationInnerCircle);
  103976. this._scene.beginAnimation(torus, 0, 60, true);
  103977. this._hideTeleportationTarget();
  103978. };
  103979. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  103980. this._teleportActive = true;
  103981. if (this._teleportationInitialized) {
  103982. this._teleportationTarget.isVisible = true;
  103983. if (this._isDefaultTeleportationTarget) {
  103984. this._teleportationTarget.getChildren()[0].isVisible = true;
  103985. }
  103986. }
  103987. };
  103988. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  103989. this._teleportActive = false;
  103990. if (this._teleportationInitialized) {
  103991. this._teleportationTarget.isVisible = false;
  103992. if (this._isDefaultTeleportationTarget) {
  103993. this._teleportationTarget.getChildren()[0].isVisible = false;
  103994. }
  103995. }
  103996. };
  103997. VRExperienceHelper.prototype._rotateCamera = function (right) {
  103998. var _this = this;
  103999. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  104000. return;
  104001. }
  104002. if (right) {
  104003. this._rotationAngle++;
  104004. }
  104005. else {
  104006. this._rotationAngle--;
  104007. }
  104008. this.currentVRCamera.animations = [];
  104009. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  104010. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104011. var animationRotationKeys = [];
  104012. animationRotationKeys.push({
  104013. frame: 0,
  104014. value: this.currentVRCamera.rotationQuaternion
  104015. });
  104016. animationRotationKeys.push({
  104017. frame: 6,
  104018. value: target
  104019. });
  104020. animationRotation.setKeys(animationRotationKeys);
  104021. animationRotation.setEasingFunction(this._circleEase);
  104022. this.currentVRCamera.animations.push(animationRotation);
  104023. this._postProcessMove.animations = [];
  104024. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104025. var vignetteWeightKeys = [];
  104026. vignetteWeightKeys.push({
  104027. frame: 0,
  104028. value: 0
  104029. });
  104030. vignetteWeightKeys.push({
  104031. frame: 3,
  104032. value: 4
  104033. });
  104034. vignetteWeightKeys.push({
  104035. frame: 6,
  104036. value: 0
  104037. });
  104038. animationPP.setKeys(vignetteWeightKeys);
  104039. animationPP.setEasingFunction(this._circleEase);
  104040. this._postProcessMove.animations.push(animationPP);
  104041. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104042. var vignetteStretchKeys = [];
  104043. vignetteStretchKeys.push({
  104044. frame: 0,
  104045. value: 0
  104046. });
  104047. vignetteStretchKeys.push({
  104048. frame: 3,
  104049. value: 10
  104050. });
  104051. vignetteStretchKeys.push({
  104052. frame: 6,
  104053. value: 0
  104054. });
  104055. animationPP2.setKeys(vignetteStretchKeys);
  104056. animationPP2.setEasingFunction(this._circleEase);
  104057. this._postProcessMove.animations.push(animationPP2);
  104058. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  104059. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  104060. this._postProcessMove.samples = 4;
  104061. this._webVRCamera.attachPostProcess(this._postProcessMove);
  104062. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  104063. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  104064. });
  104065. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  104066. };
  104067. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  104068. if (hit.pickedPoint) {
  104069. if (gazer._teleportationRequestInitiated) {
  104070. this._displayTeleportationTarget();
  104071. this._haloCenter.copyFrom(hit.pickedPoint);
  104072. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  104073. }
  104074. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  104075. if (pickNormal) {
  104076. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  104077. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  104078. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  104079. }
  104080. this._teleportationTarget.position.y += 0.1;
  104081. }
  104082. };
  104083. /**
  104084. * Teleports the users feet to the desired location
  104085. * @param location The location where the user's feet should be placed
  104086. */
  104087. VRExperienceHelper.prototype.teleportCamera = function (location) {
  104088. var _this = this;
  104089. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  104090. return;
  104091. }
  104092. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  104093. // offset of the headset from the anchor.
  104094. if (this.webVRCamera.leftCamera) {
  104095. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  104096. this._workingVector.subtractInPlace(this.webVRCamera.position);
  104097. location.subtractToRef(this._workingVector, this._workingVector);
  104098. }
  104099. else {
  104100. this._workingVector.copyFrom(location);
  104101. }
  104102. // Add height to account for user's height offset
  104103. if (this.isInVRMode) {
  104104. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  104105. }
  104106. else {
  104107. this._workingVector.y += this._defaultHeight;
  104108. }
  104109. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  104110. // Create animation from the camera's position to the new location
  104111. this.currentVRCamera.animations = [];
  104112. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104113. var animationCameraTeleportationKeys = [{
  104114. frame: 0,
  104115. value: this.currentVRCamera.position
  104116. },
  104117. {
  104118. frame: 11,
  104119. value: this._workingVector
  104120. }
  104121. ];
  104122. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  104123. animationCameraTeleportation.setEasingFunction(this._circleEase);
  104124. this.currentVRCamera.animations.push(animationCameraTeleportation);
  104125. this._postProcessMove.animations = [];
  104126. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104127. var vignetteWeightKeys = [];
  104128. vignetteWeightKeys.push({
  104129. frame: 0,
  104130. value: 0
  104131. });
  104132. vignetteWeightKeys.push({
  104133. frame: 5,
  104134. value: 8
  104135. });
  104136. vignetteWeightKeys.push({
  104137. frame: 11,
  104138. value: 0
  104139. });
  104140. animationPP.setKeys(vignetteWeightKeys);
  104141. this._postProcessMove.animations.push(animationPP);
  104142. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104143. var vignetteStretchKeys = [];
  104144. vignetteStretchKeys.push({
  104145. frame: 0,
  104146. value: 0
  104147. });
  104148. vignetteStretchKeys.push({
  104149. frame: 5,
  104150. value: 10
  104151. });
  104152. vignetteStretchKeys.push({
  104153. frame: 11,
  104154. value: 0
  104155. });
  104156. animationPP2.setKeys(vignetteStretchKeys);
  104157. this._postProcessMove.animations.push(animationPP2);
  104158. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  104159. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  104160. this._webVRCamera.attachPostProcess(this._postProcessMove);
  104161. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  104162. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  104163. });
  104164. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  104165. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  104166. });
  104167. this._hideTeleportationTarget();
  104168. };
  104169. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  104170. if (normal) {
  104171. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  104172. if (angle < Math.PI / 2) {
  104173. normal.scaleInPlace(-1);
  104174. }
  104175. }
  104176. return normal;
  104177. };
  104178. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  104179. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  104180. return;
  104181. }
  104182. var ray = gazer._getForwardRay(this._rayLength);
  104183. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  104184. if (hit) {
  104185. // Populate the contrllers mesh that can be used for drag/drop
  104186. if (gazer._laserPointer) {
  104187. hit.originMesh = gazer._laserPointer.parent;
  104188. }
  104189. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  104190. }
  104191. gazer._currentHit = hit;
  104192. // Moving the gazeTracker on the mesh face targetted
  104193. if (hit && hit.pickedPoint) {
  104194. if (this._displayGaze) {
  104195. var multiplier = 1;
  104196. gazer._gazeTracker.isVisible = true;
  104197. if (gazer._isActionableMesh) {
  104198. multiplier = 3;
  104199. }
  104200. if (this.updateGazeTrackerScale) {
  104201. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  104202. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  104203. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  104204. }
  104205. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  104206. // To avoid z-fighting
  104207. var deltaFighting = 0.002;
  104208. if (pickNormal) {
  104209. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  104210. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  104211. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  104212. }
  104213. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  104214. if (gazer._gazeTracker.position.x < 0) {
  104215. gazer._gazeTracker.position.x += deltaFighting;
  104216. }
  104217. else {
  104218. gazer._gazeTracker.position.x -= deltaFighting;
  104219. }
  104220. if (gazer._gazeTracker.position.y < 0) {
  104221. gazer._gazeTracker.position.y += deltaFighting;
  104222. }
  104223. else {
  104224. gazer._gazeTracker.position.y -= deltaFighting;
  104225. }
  104226. if (gazer._gazeTracker.position.z < 0) {
  104227. gazer._gazeTracker.position.z += deltaFighting;
  104228. }
  104229. else {
  104230. gazer._gazeTracker.position.z -= deltaFighting;
  104231. }
  104232. }
  104233. // Changing the size of the laser pointer based on the distance from the targetted point
  104234. gazer._updatePointerDistance(hit.distance);
  104235. }
  104236. else {
  104237. gazer._updatePointerDistance();
  104238. gazer._gazeTracker.isVisible = false;
  104239. }
  104240. if (hit && hit.pickedMesh) {
  104241. // The object selected is the floor, we're in a teleportation scenario
  104242. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  104243. // Moving the teleportation area to this targetted point
  104244. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  104245. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  104246. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  104247. }
  104248. gazer._currentMeshSelected = null;
  104249. if (gazer._teleportationRequestInitiated) {
  104250. this._moveTeleportationSelectorTo(hit, gazer, ray);
  104251. }
  104252. return;
  104253. }
  104254. // If not, we're in a selection scenario
  104255. //this._teleportationAllowed = false;
  104256. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  104257. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  104258. this.onNewMeshPicked.notifyObservers(hit);
  104259. gazer._currentMeshSelected = hit.pickedMesh;
  104260. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  104261. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  104262. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  104263. gazer._isActionableMesh = true;
  104264. }
  104265. else {
  104266. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104267. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104268. gazer._isActionableMesh = false;
  104269. }
  104270. try {
  104271. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  104272. }
  104273. catch (err) {
  104274. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  104275. }
  104276. }
  104277. else {
  104278. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  104279. gazer._currentMeshSelected = null;
  104280. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104281. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104282. }
  104283. }
  104284. }
  104285. else {
  104286. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  104287. gazer._currentMeshSelected = null;
  104288. //this._teleportationAllowed = false;
  104289. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104290. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104291. }
  104292. };
  104293. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  104294. if (mesh) {
  104295. this.onSelectedMeshUnselected.notifyObservers(mesh);
  104296. }
  104297. };
  104298. /**
  104299. * Sets the color of the laser ray from the vr controllers.
  104300. * @param color new color for the ray.
  104301. */
  104302. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  104303. if (this._leftController) {
  104304. this._leftController._setLaserPointerColor(color);
  104305. }
  104306. if (this._rightController) {
  104307. this._rightController._setLaserPointerColor(color);
  104308. }
  104309. };
  104310. /**
  104311. * Sets the color of the ray from the vr headsets gaze.
  104312. * @param color new color for the ray.
  104313. */
  104314. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  104315. if (!this._cameraGazer._gazeTracker.material) {
  104316. return;
  104317. }
  104318. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  104319. if (this._leftController) {
  104320. this._leftController._gazeTracker.material.emissiveColor = color;
  104321. }
  104322. if (this._rightController) {
  104323. this._rightController._gazeTracker.material.emissiveColor = color;
  104324. }
  104325. };
  104326. /**
  104327. * Exits VR and disposes of the vr experience helper
  104328. */
  104329. VRExperienceHelper.prototype.dispose = function () {
  104330. if (this.isInVRMode) {
  104331. this.exitVR();
  104332. }
  104333. if (this._postProcessMove) {
  104334. this._postProcessMove.dispose();
  104335. }
  104336. if (this._webVRCamera) {
  104337. this._webVRCamera.dispose();
  104338. }
  104339. if (this._vrDeviceOrientationCamera) {
  104340. this._vrDeviceOrientationCamera.dispose();
  104341. }
  104342. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  104343. document.body.removeChild(this._btnVR);
  104344. }
  104345. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  104346. this._deviceOrientationCamera.dispose();
  104347. }
  104348. if (this._cameraGazer) {
  104349. this._cameraGazer.dispose();
  104350. }
  104351. if (this._leftController) {
  104352. this._leftController.dispose();
  104353. }
  104354. if (this._rightController) {
  104355. this._rightController.dispose();
  104356. }
  104357. if (this._teleportationTarget) {
  104358. this._teleportationTarget.dispose();
  104359. }
  104360. this._floorMeshesCollection = [];
  104361. document.removeEventListener("keydown", this._onKeyDown);
  104362. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104363. window.removeEventListener("resize", this._onResize);
  104364. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  104365. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  104366. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  104367. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  104368. document.onmsfullscreenchange = null;
  104369. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  104370. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  104371. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  104372. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104373. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  104374. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  104375. this._scene.unregisterBeforeRender(this.beforeRender);
  104376. };
  104377. /**
  104378. * Gets the name of the VRExperienceHelper class
  104379. * @returns "VRExperienceHelper"
  104380. */
  104381. VRExperienceHelper.prototype.getClassName = function () {
  104382. return "VRExperienceHelper";
  104383. };
  104384. return VRExperienceHelper;
  104385. }());
  104386. BABYLON.VRExperienceHelper = VRExperienceHelper;
  104387. })(BABYLON || (BABYLON = {}));
  104388. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  104389. // Mainly based on these 2 articles :
  104390. // 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
  104391. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  104392. var BABYLON;
  104393. (function (BABYLON) {
  104394. /**
  104395. * Defines the potential axis of a Joystick
  104396. */
  104397. var JoystickAxis;
  104398. (function (JoystickAxis) {
  104399. /** X axis */
  104400. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  104401. /** Y axis */
  104402. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  104403. /** Z axis */
  104404. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  104405. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  104406. /**
  104407. * Class used to define virtual joystick (used in touch mode)
  104408. */
  104409. var VirtualJoystick = /** @class */ (function () {
  104410. /**
  104411. * Creates a new virtual joystick
  104412. * @param leftJoystick defines that the joystick is for left hand (false by default)
  104413. */
  104414. function VirtualJoystick(leftJoystick) {
  104415. var _this = this;
  104416. if (leftJoystick) {
  104417. this._leftJoystick = true;
  104418. }
  104419. else {
  104420. this._leftJoystick = false;
  104421. }
  104422. VirtualJoystick._globalJoystickIndex++;
  104423. // By default left & right arrow keys are moving the X
  104424. // and up & down keys are moving the Y
  104425. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  104426. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  104427. this.reverseLeftRight = false;
  104428. this.reverseUpDown = false;
  104429. // collections of pointers
  104430. this._touches = new BABYLON.StringDictionary();
  104431. this.deltaPosition = BABYLON.Vector3.Zero();
  104432. this._joystickSensibility = 25;
  104433. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  104434. this._onResize = function (evt) {
  104435. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  104436. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  104437. if (VirtualJoystick.vjCanvas) {
  104438. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  104439. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  104440. }
  104441. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  104442. };
  104443. // injecting a canvas element on top of the canvas 3D game
  104444. if (!VirtualJoystick.vjCanvas) {
  104445. window.addEventListener("resize", this._onResize, false);
  104446. VirtualJoystick.vjCanvas = document.createElement("canvas");
  104447. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  104448. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  104449. VirtualJoystick.vjCanvas.width = window.innerWidth;
  104450. VirtualJoystick.vjCanvas.height = window.innerHeight;
  104451. VirtualJoystick.vjCanvas.style.width = "100%";
  104452. VirtualJoystick.vjCanvas.style.height = "100%";
  104453. VirtualJoystick.vjCanvas.style.position = "absolute";
  104454. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  104455. VirtualJoystick.vjCanvas.style.top = "0px";
  104456. VirtualJoystick.vjCanvas.style.left = "0px";
  104457. VirtualJoystick.vjCanvas.style.zIndex = "5";
  104458. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  104459. // Support for jQuery PEP polyfill
  104460. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  104461. var context = VirtualJoystick.vjCanvas.getContext('2d');
  104462. if (!context) {
  104463. throw new Error("Unable to create canvas for virtual joystick");
  104464. }
  104465. VirtualJoystick.vjCanvasContext = context;
  104466. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  104467. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  104468. document.body.appendChild(VirtualJoystick.vjCanvas);
  104469. }
  104470. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  104471. this.pressed = false;
  104472. // default joystick color
  104473. this._joystickColor = "cyan";
  104474. this._joystickPointerID = -1;
  104475. // current joystick position
  104476. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  104477. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  104478. // origin joystick position
  104479. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  104480. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  104481. this._onPointerDownHandlerRef = function (evt) {
  104482. _this._onPointerDown(evt);
  104483. };
  104484. this._onPointerMoveHandlerRef = function (evt) {
  104485. _this._onPointerMove(evt);
  104486. };
  104487. this._onPointerUpHandlerRef = function (evt) {
  104488. _this._onPointerUp(evt);
  104489. };
  104490. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  104491. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  104492. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  104493. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  104494. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  104495. evt.preventDefault(); // Disables system menu
  104496. }, false);
  104497. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  104498. }
  104499. /**
  104500. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  104501. * @param newJoystickSensibility defines the new sensibility
  104502. */
  104503. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  104504. this._joystickSensibility = newJoystickSensibility;
  104505. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  104506. };
  104507. VirtualJoystick.prototype._onPointerDown = function (e) {
  104508. var positionOnScreenCondition;
  104509. e.preventDefault();
  104510. if (this._leftJoystick === true) {
  104511. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  104512. }
  104513. else {
  104514. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  104515. }
  104516. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  104517. // First contact will be dedicated to the virtual joystick
  104518. this._joystickPointerID = e.pointerId;
  104519. this._joystickPointerStartPos.x = e.clientX;
  104520. this._joystickPointerStartPos.y = e.clientY;
  104521. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  104522. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  104523. this._deltaJoystickVector.x = 0;
  104524. this._deltaJoystickVector.y = 0;
  104525. this.pressed = true;
  104526. this._touches.add(e.pointerId.toString(), e);
  104527. }
  104528. else {
  104529. // You can only trigger the action buttons with a joystick declared
  104530. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  104531. this._action();
  104532. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  104533. }
  104534. }
  104535. };
  104536. VirtualJoystick.prototype._onPointerMove = function (e) {
  104537. // If the current pointer is the one associated to the joystick (first touch contact)
  104538. if (this._joystickPointerID == e.pointerId) {
  104539. this._joystickPointerPos.x = e.clientX;
  104540. this._joystickPointerPos.y = e.clientY;
  104541. this._deltaJoystickVector = this._joystickPointerPos.clone();
  104542. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  104543. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  104544. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  104545. switch (this._axisTargetedByLeftAndRight) {
  104546. case JoystickAxis.X:
  104547. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  104548. break;
  104549. case JoystickAxis.Y:
  104550. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  104551. break;
  104552. case JoystickAxis.Z:
  104553. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  104554. break;
  104555. }
  104556. var directionUpDown = this.reverseUpDown ? 1 : -1;
  104557. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  104558. switch (this._axisTargetedByUpAndDown) {
  104559. case JoystickAxis.X:
  104560. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  104561. break;
  104562. case JoystickAxis.Y:
  104563. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  104564. break;
  104565. case JoystickAxis.Z:
  104566. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  104567. break;
  104568. }
  104569. }
  104570. else {
  104571. var data = this._touches.get(e.pointerId.toString());
  104572. if (data) {
  104573. data.x = e.clientX;
  104574. data.y = e.clientY;
  104575. }
  104576. }
  104577. };
  104578. VirtualJoystick.prototype._onPointerUp = function (e) {
  104579. if (this._joystickPointerID == e.pointerId) {
  104580. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  104581. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  104582. this._joystickPointerID = -1;
  104583. this.pressed = false;
  104584. }
  104585. else {
  104586. var touch = this._touches.get(e.pointerId.toString());
  104587. if (touch) {
  104588. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  104589. }
  104590. }
  104591. this._deltaJoystickVector.x = 0;
  104592. this._deltaJoystickVector.y = 0;
  104593. this._touches.remove(e.pointerId.toString());
  104594. };
  104595. /**
  104596. * Change the color of the virtual joystick
  104597. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  104598. */
  104599. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  104600. this._joystickColor = newColor;
  104601. };
  104602. /**
  104603. * Defines a callback to call when the joystick is touched
  104604. * @param action defines the callback
  104605. */
  104606. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  104607. this._action = action;
  104608. };
  104609. /**
  104610. * Defines which axis you'd like to control for left & right
  104611. * @param axis defines the axis to use
  104612. */
  104613. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  104614. switch (axis) {
  104615. case JoystickAxis.X:
  104616. case JoystickAxis.Y:
  104617. case JoystickAxis.Z:
  104618. this._axisTargetedByLeftAndRight = axis;
  104619. break;
  104620. default:
  104621. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  104622. break;
  104623. }
  104624. };
  104625. /**
  104626. * Defines which axis you'd like to control for up & down
  104627. * @param axis defines the axis to use
  104628. */
  104629. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  104630. switch (axis) {
  104631. case JoystickAxis.X:
  104632. case JoystickAxis.Y:
  104633. case JoystickAxis.Z:
  104634. this._axisTargetedByUpAndDown = axis;
  104635. break;
  104636. default:
  104637. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  104638. break;
  104639. }
  104640. };
  104641. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  104642. var _this = this;
  104643. if (this.pressed) {
  104644. this._touches.forEach(function (key, touch) {
  104645. if (touch.pointerId === _this._joystickPointerID) {
  104646. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  104647. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  104648. VirtualJoystick.vjCanvasContext.beginPath();
  104649. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  104650. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  104651. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  104652. VirtualJoystick.vjCanvasContext.stroke();
  104653. VirtualJoystick.vjCanvasContext.closePath();
  104654. VirtualJoystick.vjCanvasContext.beginPath();
  104655. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  104656. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  104657. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  104658. VirtualJoystick.vjCanvasContext.stroke();
  104659. VirtualJoystick.vjCanvasContext.closePath();
  104660. VirtualJoystick.vjCanvasContext.beginPath();
  104661. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  104662. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  104663. VirtualJoystick.vjCanvasContext.stroke();
  104664. VirtualJoystick.vjCanvasContext.closePath();
  104665. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  104666. }
  104667. else {
  104668. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  104669. VirtualJoystick.vjCanvasContext.beginPath();
  104670. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  104671. VirtualJoystick.vjCanvasContext.beginPath();
  104672. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  104673. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  104674. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  104675. VirtualJoystick.vjCanvasContext.stroke();
  104676. VirtualJoystick.vjCanvasContext.closePath();
  104677. touch.prevX = touch.x;
  104678. touch.prevY = touch.y;
  104679. }
  104680. ;
  104681. });
  104682. }
  104683. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  104684. };
  104685. /**
  104686. * Release internal HTML canvas
  104687. */
  104688. VirtualJoystick.prototype.releaseCanvas = function () {
  104689. if (VirtualJoystick.vjCanvas) {
  104690. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  104691. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  104692. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  104693. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  104694. window.removeEventListener("resize", this._onResize);
  104695. document.body.removeChild(VirtualJoystick.vjCanvas);
  104696. VirtualJoystick.vjCanvas = null;
  104697. }
  104698. };
  104699. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  104700. VirtualJoystick._globalJoystickIndex = 0;
  104701. return VirtualJoystick;
  104702. }());
  104703. BABYLON.VirtualJoystick = VirtualJoystick;
  104704. })(BABYLON || (BABYLON = {}));
  104705. //# sourceMappingURL=babylon.virtualJoystick.js.map
  104706. var BABYLON;
  104707. (function (BABYLON) {
  104708. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  104709. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  104710. });
  104711. /**
  104712. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  104713. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  104714. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  104715. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  104716. */
  104717. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  104718. __extends(VirtualJoysticksCamera, _super);
  104719. /**
  104720. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  104721. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  104722. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  104723. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  104724. * @param name Define the name of the camera in the scene
  104725. * @param position Define the start position of the camera in the scene
  104726. * @param scene Define the scene the camera belongs to
  104727. */
  104728. function VirtualJoysticksCamera(name, position, scene) {
  104729. var _this = _super.call(this, name, position, scene) || this;
  104730. _this.inputs.addVirtualJoystick();
  104731. return _this;
  104732. }
  104733. /**
  104734. * Gets the current object class name.
  104735. * @return the class name
  104736. */
  104737. VirtualJoysticksCamera.prototype.getClassName = function () {
  104738. return "VirtualJoysticksCamera";
  104739. };
  104740. return VirtualJoysticksCamera;
  104741. }(BABYLON.FreeCamera));
  104742. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  104743. })(BABYLON || (BABYLON = {}));
  104744. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  104745. var BABYLON;
  104746. (function (BABYLON) {
  104747. /**
  104748. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  104749. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104750. */
  104751. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  104752. function FreeCameraVirtualJoystickInput() {
  104753. }
  104754. /**
  104755. * Gets the left stick of the virtual joystick.
  104756. * @returns The virtual Joystick
  104757. */
  104758. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  104759. return this._leftjoystick;
  104760. };
  104761. /**
  104762. * Gets the right stick of the virtual joystick.
  104763. * @returns The virtual Joystick
  104764. */
  104765. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  104766. return this._rightjoystick;
  104767. };
  104768. /**
  104769. * Update the current camera state depending on the inputs that have been used this frame.
  104770. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104771. */
  104772. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  104773. if (this._leftjoystick) {
  104774. var camera = this.camera;
  104775. var speed = camera._computeLocalCameraSpeed() * 50;
  104776. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  104777. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  104778. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  104779. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  104780. if (!this._leftjoystick.pressed) {
  104781. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  104782. }
  104783. if (!this._rightjoystick.pressed) {
  104784. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  104785. }
  104786. }
  104787. };
  104788. /**
  104789. * Attach the input controls to a specific dom element to get the input from.
  104790. * @param element Defines the element the controls should be listened from
  104791. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104792. */
  104793. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  104794. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  104795. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  104796. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  104797. this._leftjoystick.setJoystickSensibility(0.15);
  104798. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  104799. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  104800. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  104801. this._rightjoystick.reverseUpDown = true;
  104802. this._rightjoystick.setJoystickSensibility(0.05);
  104803. this._rightjoystick.setJoystickColor("yellow");
  104804. };
  104805. /**
  104806. * Detach the current controls from the specified dom element.
  104807. * @param element Defines the element to stop listening the inputs from
  104808. */
  104809. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  104810. this._leftjoystick.releaseCanvas();
  104811. this._rightjoystick.releaseCanvas();
  104812. };
  104813. /**
  104814. * Gets the class name of the current intput.
  104815. * @returns the class name
  104816. */
  104817. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  104818. return "FreeCameraVirtualJoystickInput";
  104819. };
  104820. /**
  104821. * Get the friendly name associated with the input class.
  104822. * @returns the input friendly name
  104823. */
  104824. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  104825. return "virtualJoystick";
  104826. };
  104827. return FreeCameraVirtualJoystickInput;
  104828. }());
  104829. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  104830. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  104831. })(BABYLON || (BABYLON = {}));
  104832. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  104833. var BABYLON;
  104834. (function (BABYLON) {
  104835. /**
  104836. * Class used to specify simplification options
  104837. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104838. */
  104839. var SimplificationSettings = /** @class */ (function () {
  104840. /**
  104841. * Creates a SimplificationSettings
  104842. * @param quality expected quality
  104843. * @param distance distance when this optimized version should be used
  104844. * @param optimizeMesh already optimized mesh
  104845. */
  104846. function SimplificationSettings(
  104847. /** expected quality */
  104848. quality,
  104849. /** distance when this optimized version should be used */
  104850. distance,
  104851. /** already optimized mesh */
  104852. optimizeMesh) {
  104853. this.quality = quality;
  104854. this.distance = distance;
  104855. this.optimizeMesh = optimizeMesh;
  104856. }
  104857. return SimplificationSettings;
  104858. }());
  104859. BABYLON.SimplificationSettings = SimplificationSettings;
  104860. /**
  104861. * Queue used to order the simplification tasks
  104862. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104863. */
  104864. var SimplificationQueue = /** @class */ (function () {
  104865. /**
  104866. * Creates a new queue
  104867. */
  104868. function SimplificationQueue() {
  104869. this.running = false;
  104870. this._simplificationArray = [];
  104871. }
  104872. /**
  104873. * Adds a new simplification task
  104874. * @param task defines a task to add
  104875. */
  104876. SimplificationQueue.prototype.addTask = function (task) {
  104877. this._simplificationArray.push(task);
  104878. };
  104879. /**
  104880. * Execute next task
  104881. */
  104882. SimplificationQueue.prototype.executeNext = function () {
  104883. var task = this._simplificationArray.pop();
  104884. if (task) {
  104885. this.running = true;
  104886. this.runSimplification(task);
  104887. }
  104888. else {
  104889. this.running = false;
  104890. }
  104891. };
  104892. /**
  104893. * Execute a simplification task
  104894. * @param task defines the task to run
  104895. */
  104896. SimplificationQueue.prototype.runSimplification = function (task) {
  104897. var _this = this;
  104898. if (task.parallelProcessing) {
  104899. //parallel simplifier
  104900. task.settings.forEach(function (setting) {
  104901. var simplifier = _this.getSimplifier(task);
  104902. simplifier.simplify(setting, function (newMesh) {
  104903. task.mesh.addLODLevel(setting.distance, newMesh);
  104904. newMesh.isVisible = true;
  104905. //check if it is the last
  104906. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  104907. //all done, run the success callback.
  104908. task.successCallback();
  104909. }
  104910. _this.executeNext();
  104911. });
  104912. });
  104913. }
  104914. else {
  104915. //single simplifier.
  104916. var simplifier = this.getSimplifier(task);
  104917. var runDecimation = function (setting, callback) {
  104918. simplifier.simplify(setting, function (newMesh) {
  104919. task.mesh.addLODLevel(setting.distance, newMesh);
  104920. newMesh.isVisible = true;
  104921. //run the next quality level
  104922. callback();
  104923. });
  104924. };
  104925. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  104926. runDecimation(task.settings[loop.index], function () {
  104927. loop.executeNext();
  104928. });
  104929. }, function () {
  104930. //execution ended, run the success callback.
  104931. if (task.successCallback) {
  104932. task.successCallback();
  104933. }
  104934. _this.executeNext();
  104935. });
  104936. }
  104937. };
  104938. SimplificationQueue.prototype.getSimplifier = function (task) {
  104939. switch (task.simplificationType) {
  104940. case SimplificationType.QUADRATIC:
  104941. default:
  104942. return new QuadraticErrorSimplification(task.mesh);
  104943. }
  104944. };
  104945. return SimplificationQueue;
  104946. }());
  104947. BABYLON.SimplificationQueue = SimplificationQueue;
  104948. /**
  104949. * The implemented types of simplification
  104950. * At the moment only Quadratic Error Decimation is implemented
  104951. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104952. */
  104953. var SimplificationType;
  104954. (function (SimplificationType) {
  104955. /** Quadratic error decimation */
  104956. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  104957. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  104958. var DecimationTriangle = /** @class */ (function () {
  104959. function DecimationTriangle(vertices) {
  104960. this.vertices = vertices;
  104961. this.error = new Array(4);
  104962. this.deleted = false;
  104963. this.isDirty = false;
  104964. this.deletePending = false;
  104965. this.borderFactor = 0;
  104966. }
  104967. return DecimationTriangle;
  104968. }());
  104969. var DecimationVertex = /** @class */ (function () {
  104970. function DecimationVertex(position, id) {
  104971. this.position = position;
  104972. this.id = id;
  104973. this.isBorder = true;
  104974. this.q = new QuadraticMatrix();
  104975. this.triangleCount = 0;
  104976. this.triangleStart = 0;
  104977. this.originalOffsets = [];
  104978. }
  104979. DecimationVertex.prototype.updatePosition = function (newPosition) {
  104980. this.position.copyFrom(newPosition);
  104981. };
  104982. return DecimationVertex;
  104983. }());
  104984. var QuadraticMatrix = /** @class */ (function () {
  104985. function QuadraticMatrix(data) {
  104986. this.data = new Array(10);
  104987. for (var i = 0; i < 10; ++i) {
  104988. if (data && data[i]) {
  104989. this.data[i] = data[i];
  104990. }
  104991. else {
  104992. this.data[i] = 0;
  104993. }
  104994. }
  104995. }
  104996. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  104997. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  104998. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  104999. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  105000. return det;
  105001. };
  105002. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  105003. for (var i = 0; i < 10; ++i) {
  105004. this.data[i] += matrix.data[i];
  105005. }
  105006. };
  105007. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  105008. for (var i = 0; i < 10; ++i) {
  105009. this.data[i] += data[i];
  105010. }
  105011. };
  105012. QuadraticMatrix.prototype.add = function (matrix) {
  105013. var m = new QuadraticMatrix();
  105014. for (var i = 0; i < 10; ++i) {
  105015. m.data[i] = this.data[i] + matrix.data[i];
  105016. }
  105017. return m;
  105018. };
  105019. QuadraticMatrix.FromData = function (a, b, c, d) {
  105020. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  105021. };
  105022. //returning an array to avoid garbage collection
  105023. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  105024. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  105025. };
  105026. return QuadraticMatrix;
  105027. }());
  105028. var Reference = /** @class */ (function () {
  105029. function Reference(vertexId, triangleId) {
  105030. this.vertexId = vertexId;
  105031. this.triangleId = triangleId;
  105032. }
  105033. return Reference;
  105034. }());
  105035. /**
  105036. * An implementation of the Quadratic Error simplification algorithm.
  105037. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  105038. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  105039. * @author RaananW
  105040. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  105041. */
  105042. var QuadraticErrorSimplification = /** @class */ (function () {
  105043. function QuadraticErrorSimplification(_mesh) {
  105044. this._mesh = _mesh;
  105045. this.syncIterations = 5000;
  105046. this.aggressiveness = 7;
  105047. this.decimationIterations = 100;
  105048. this.boundingBoxEpsilon = BABYLON.Epsilon;
  105049. }
  105050. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  105051. var _this = this;
  105052. this.initDecimatedMesh();
  105053. //iterating through the submeshes array, one after the other.
  105054. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  105055. _this.initWithMesh(loop.index, function () {
  105056. _this.runDecimation(settings, loop.index, function () {
  105057. loop.executeNext();
  105058. });
  105059. }, settings.optimizeMesh);
  105060. }, function () {
  105061. setTimeout(function () {
  105062. successCallback(_this._reconstructedMesh);
  105063. }, 0);
  105064. });
  105065. };
  105066. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  105067. var _this = this;
  105068. var targetCount = ~~(this.triangles.length * settings.quality);
  105069. var deletedTriangles = 0;
  105070. var triangleCount = this.triangles.length;
  105071. var iterationFunction = function (iteration, callback) {
  105072. setTimeout(function () {
  105073. if (iteration % 5 === 0) {
  105074. _this.updateMesh(iteration === 0);
  105075. }
  105076. for (var i = 0; i < _this.triangles.length; ++i) {
  105077. _this.triangles[i].isDirty = false;
  105078. }
  105079. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  105080. var trianglesIterator = function (i) {
  105081. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  105082. var t = _this.triangles[tIdx];
  105083. if (!t)
  105084. return;
  105085. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  105086. return;
  105087. }
  105088. for (var j = 0; j < 3; ++j) {
  105089. if (t.error[j] < threshold) {
  105090. var deleted0 = [];
  105091. var deleted1 = [];
  105092. var v0 = t.vertices[j];
  105093. var v1 = t.vertices[(j + 1) % 3];
  105094. if (v0.isBorder || v1.isBorder)
  105095. continue;
  105096. var p = BABYLON.Vector3.Zero();
  105097. var n = BABYLON.Vector3.Zero();
  105098. var uv = BABYLON.Vector2.Zero();
  105099. var color = new BABYLON.Color4(0, 0, 0, 1);
  105100. _this.calculateError(v0, v1, p, n, uv, color);
  105101. var delTr = new Array();
  105102. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  105103. continue;
  105104. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  105105. continue;
  105106. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  105107. continue;
  105108. var uniqueArray = new Array();
  105109. delTr.forEach(function (deletedT) {
  105110. if (uniqueArray.indexOf(deletedT) === -1) {
  105111. deletedT.deletePending = true;
  105112. uniqueArray.push(deletedT);
  105113. }
  105114. });
  105115. if (uniqueArray.length % 2 !== 0) {
  105116. continue;
  105117. }
  105118. v0.q = v1.q.add(v0.q);
  105119. v0.updatePosition(p);
  105120. var tStart = _this.references.length;
  105121. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  105122. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  105123. var tCount = _this.references.length - tStart;
  105124. if (tCount <= v0.triangleCount) {
  105125. if (tCount) {
  105126. for (var c = 0; c < tCount; c++) {
  105127. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  105128. }
  105129. }
  105130. }
  105131. else {
  105132. v0.triangleStart = tStart;
  105133. }
  105134. v0.triangleCount = tCount;
  105135. break;
  105136. }
  105137. }
  105138. };
  105139. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  105140. }, 0);
  105141. };
  105142. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  105143. if (triangleCount - deletedTriangles <= targetCount)
  105144. loop.breakLoop();
  105145. else {
  105146. iterationFunction(loop.index, function () {
  105147. loop.executeNext();
  105148. });
  105149. }
  105150. }, function () {
  105151. setTimeout(function () {
  105152. //reconstruct this part of the mesh
  105153. _this.reconstructMesh(submeshIndex);
  105154. successCallback();
  105155. }, 0);
  105156. });
  105157. };
  105158. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  105159. var _this = this;
  105160. this.vertices = [];
  105161. this.triangles = [];
  105162. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  105163. var indices = this._mesh.getIndices();
  105164. var submesh = this._mesh.subMeshes[submeshIndex];
  105165. var findInVertices = function (positionToSearch) {
  105166. if (optimizeMesh) {
  105167. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  105168. if (_this.vertices[ii].position.equals(positionToSearch)) {
  105169. return _this.vertices[ii];
  105170. }
  105171. }
  105172. }
  105173. return null;
  105174. };
  105175. var vertexReferences = [];
  105176. var vertexInit = function (i) {
  105177. if (!positionData) {
  105178. return;
  105179. }
  105180. var offset = i + submesh.verticesStart;
  105181. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  105182. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  105183. vertex.originalOffsets.push(offset);
  105184. if (vertex.id === _this.vertices.length) {
  105185. _this.vertices.push(vertex);
  105186. }
  105187. vertexReferences.push(vertex.id);
  105188. };
  105189. //var totalVertices = mesh.getTotalVertices();
  105190. var totalVertices = submesh.verticesCount;
  105191. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  105192. var indicesInit = function (i) {
  105193. if (!indices) {
  105194. return;
  105195. }
  105196. var offset = (submesh.indexStart / 3) + i;
  105197. var pos = (offset * 3);
  105198. var i0 = indices[pos + 0];
  105199. var i1 = indices[pos + 1];
  105200. var i2 = indices[pos + 2];
  105201. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  105202. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  105203. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  105204. var triangle = new DecimationTriangle([v0, v1, v2]);
  105205. triangle.originalOffset = pos;
  105206. _this.triangles.push(triangle);
  105207. };
  105208. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  105209. _this.init(callback);
  105210. });
  105211. });
  105212. };
  105213. QuadraticErrorSimplification.prototype.init = function (callback) {
  105214. var _this = this;
  105215. var triangleInit1 = function (i) {
  105216. var t = _this.triangles[i];
  105217. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  105218. for (var j = 0; j < 3; j++) {
  105219. 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))));
  105220. }
  105221. };
  105222. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  105223. var triangleInit2 = function (i) {
  105224. var t = _this.triangles[i];
  105225. for (var j = 0; j < 3; ++j) {
  105226. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  105227. }
  105228. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  105229. };
  105230. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  105231. callback();
  105232. });
  105233. });
  105234. };
  105235. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  105236. var newTriangles = [];
  105237. var i;
  105238. for (i = 0; i < this.vertices.length; ++i) {
  105239. this.vertices[i].triangleCount = 0;
  105240. }
  105241. var t;
  105242. var j;
  105243. for (i = 0; i < this.triangles.length; ++i) {
  105244. if (!this.triangles[i].deleted) {
  105245. t = this.triangles[i];
  105246. for (j = 0; j < 3; ++j) {
  105247. t.vertices[j].triangleCount = 1;
  105248. }
  105249. newTriangles.push(t);
  105250. }
  105251. }
  105252. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  105253. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  105254. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  105255. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  105256. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  105257. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  105258. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  105259. var vertexCount = 0;
  105260. for (i = 0; i < this.vertices.length; ++i) {
  105261. var vertex = this.vertices[i];
  105262. vertex.id = vertexCount;
  105263. if (vertex.triangleCount) {
  105264. vertex.originalOffsets.forEach(function (originalOffset) {
  105265. if (!normalData) {
  105266. return;
  105267. }
  105268. newPositionData.push(vertex.position.x);
  105269. newPositionData.push(vertex.position.y);
  105270. newPositionData.push(vertex.position.z);
  105271. newNormalData.push(normalData[originalOffset * 3]);
  105272. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  105273. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  105274. if (uvs && uvs.length) {
  105275. newUVsData.push(uvs[(originalOffset * 2)]);
  105276. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  105277. }
  105278. else if (colorsData && colorsData.length) {
  105279. newColorsData.push(colorsData[(originalOffset * 4)]);
  105280. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  105281. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  105282. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  105283. }
  105284. ++vertexCount;
  105285. });
  105286. }
  105287. }
  105288. var startingIndex = this._reconstructedMesh.getTotalIndices();
  105289. var startingVertex = this._reconstructedMesh.getTotalVertices();
  105290. var submeshesArray = this._reconstructedMesh.subMeshes;
  105291. this._reconstructedMesh.subMeshes = [];
  105292. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  105293. var originalIndices = this._mesh.getIndices();
  105294. for (i = 0; i < newTriangles.length; ++i) {
  105295. t = newTriangles[i]; //now get the new referencing point for each vertex
  105296. [0, 1, 2].forEach(function (idx) {
  105297. var id = originalIndices[t.originalOffset + idx];
  105298. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  105299. if (offset < 0)
  105300. offset = 0;
  105301. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  105302. });
  105303. }
  105304. //overwriting the old vertex buffers and indices.
  105305. this._reconstructedMesh.setIndices(newIndicesArray);
  105306. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  105307. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  105308. if (newUVsData.length > 0)
  105309. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  105310. if (newColorsData.length > 0)
  105311. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  105312. //create submesh
  105313. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  105314. if (submeshIndex > 0) {
  105315. this._reconstructedMesh.subMeshes = [];
  105316. submeshesArray.forEach(function (submesh) {
  105317. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  105318. });
  105319. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  105320. }
  105321. };
  105322. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  105323. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  105324. this._reconstructedMesh.material = this._mesh.material;
  105325. this._reconstructedMesh.parent = this._mesh.parent;
  105326. this._reconstructedMesh.isVisible = false;
  105327. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  105328. };
  105329. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  105330. for (var i = 0; i < vertex1.triangleCount; ++i) {
  105331. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  105332. if (t.deleted)
  105333. continue;
  105334. var s = this.references[vertex1.triangleStart + i].vertexId;
  105335. var v1 = t.vertices[(s + 1) % 3];
  105336. var v2 = t.vertices[(s + 2) % 3];
  105337. if ((v1 === vertex2 || v2 === vertex2)) {
  105338. deletedArray[i] = true;
  105339. delTr.push(t);
  105340. continue;
  105341. }
  105342. var d1 = v1.position.subtract(point);
  105343. d1 = d1.normalize();
  105344. var d2 = v2.position.subtract(point);
  105345. d2 = d2.normalize();
  105346. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  105347. return true;
  105348. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  105349. deletedArray[i] = false;
  105350. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  105351. return true;
  105352. }
  105353. return false;
  105354. };
  105355. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  105356. var newDeleted = deletedTriangles;
  105357. for (var i = 0; i < vertex.triangleCount; ++i) {
  105358. var ref = this.references[vertex.triangleStart + i];
  105359. var t = this.triangles[ref.triangleId];
  105360. if (t.deleted)
  105361. continue;
  105362. if (deletedArray[i] && t.deletePending) {
  105363. t.deleted = true;
  105364. newDeleted++;
  105365. continue;
  105366. }
  105367. t.vertices[ref.vertexId] = origVertex;
  105368. t.isDirty = true;
  105369. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  105370. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  105371. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  105372. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  105373. this.references.push(ref);
  105374. }
  105375. return newDeleted;
  105376. };
  105377. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  105378. for (var i = 0; i < this.vertices.length; ++i) {
  105379. var vCount = [];
  105380. var vId = [];
  105381. var v = this.vertices[i];
  105382. var j;
  105383. for (j = 0; j < v.triangleCount; ++j) {
  105384. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  105385. for (var ii = 0; ii < 3; ii++) {
  105386. var ofs = 0;
  105387. var vv = triangle.vertices[ii];
  105388. while (ofs < vCount.length) {
  105389. if (vId[ofs] === vv.id)
  105390. break;
  105391. ++ofs;
  105392. }
  105393. if (ofs === vCount.length) {
  105394. vCount.push(1);
  105395. vId.push(vv.id);
  105396. }
  105397. else {
  105398. vCount[ofs]++;
  105399. }
  105400. }
  105401. }
  105402. for (j = 0; j < vCount.length; ++j) {
  105403. if (vCount[j] === 1) {
  105404. this.vertices[vId[j]].isBorder = true;
  105405. }
  105406. else {
  105407. this.vertices[vId[j]].isBorder = false;
  105408. }
  105409. }
  105410. }
  105411. };
  105412. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  105413. if (identifyBorders === void 0) { identifyBorders = false; }
  105414. var i;
  105415. if (!identifyBorders) {
  105416. var newTrianglesVector = [];
  105417. for (i = 0; i < this.triangles.length; ++i) {
  105418. if (!this.triangles[i].deleted) {
  105419. newTrianglesVector.push(this.triangles[i]);
  105420. }
  105421. }
  105422. this.triangles = newTrianglesVector;
  105423. }
  105424. for (i = 0; i < this.vertices.length; ++i) {
  105425. this.vertices[i].triangleCount = 0;
  105426. this.vertices[i].triangleStart = 0;
  105427. }
  105428. var t;
  105429. var j;
  105430. var v;
  105431. for (i = 0; i < this.triangles.length; ++i) {
  105432. t = this.triangles[i];
  105433. for (j = 0; j < 3; ++j) {
  105434. v = t.vertices[j];
  105435. v.triangleCount++;
  105436. }
  105437. }
  105438. var tStart = 0;
  105439. for (i = 0; i < this.vertices.length; ++i) {
  105440. this.vertices[i].triangleStart = tStart;
  105441. tStart += this.vertices[i].triangleCount;
  105442. this.vertices[i].triangleCount = 0;
  105443. }
  105444. var newReferences = new Array(this.triangles.length * 3);
  105445. for (i = 0; i < this.triangles.length; ++i) {
  105446. t = this.triangles[i];
  105447. for (j = 0; j < 3; ++j) {
  105448. v = t.vertices[j];
  105449. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  105450. v.triangleCount++;
  105451. }
  105452. }
  105453. this.references = newReferences;
  105454. if (identifyBorders) {
  105455. this.identifyBorder();
  105456. }
  105457. };
  105458. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  105459. var x = point.x;
  105460. var y = point.y;
  105461. var z = point.z;
  105462. 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
  105463. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  105464. };
  105465. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  105466. var q = vertex1.q.add(vertex2.q);
  105467. var border = vertex1.isBorder && vertex2.isBorder;
  105468. var error = 0;
  105469. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  105470. if (qDet !== 0 && !border) {
  105471. if (!pointResult) {
  105472. pointResult = BABYLON.Vector3.Zero();
  105473. }
  105474. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  105475. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  105476. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  105477. error = this.vertexError(q, pointResult);
  105478. }
  105479. else {
  105480. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  105481. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  105482. var error1 = this.vertexError(q, vertex1.position);
  105483. var error2 = this.vertexError(q, vertex2.position);
  105484. var error3 = this.vertexError(q, p3);
  105485. error = Math.min(error1, error2, error3);
  105486. if (error === error1) {
  105487. if (pointResult) {
  105488. pointResult.copyFrom(vertex1.position);
  105489. }
  105490. }
  105491. else if (error === error2) {
  105492. if (pointResult) {
  105493. pointResult.copyFrom(vertex2.position);
  105494. }
  105495. }
  105496. else {
  105497. if (pointResult) {
  105498. pointResult.copyFrom(p3);
  105499. }
  105500. }
  105501. }
  105502. return error;
  105503. };
  105504. return QuadraticErrorSimplification;
  105505. }());
  105506. })(BABYLON || (BABYLON = {}));
  105507. //# sourceMappingURL=babylon.meshSimplification.js.map
  105508. var BABYLON;
  105509. (function (BABYLON) {
  105510. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  105511. get: function () {
  105512. if (!this._simplificationQueue) {
  105513. this._simplificationQueue = new BABYLON.SimplificationQueue();
  105514. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  105515. if (!component) {
  105516. component = new SimplicationQueueSceneComponent(this);
  105517. this._addComponent(component);
  105518. }
  105519. }
  105520. return this._simplificationQueue;
  105521. },
  105522. set: function (value) {
  105523. this._simplificationQueue = value;
  105524. },
  105525. enumerable: true,
  105526. configurable: true
  105527. });
  105528. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  105529. if (parallelProcessing === void 0) { parallelProcessing = true; }
  105530. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  105531. this.getScene().simplificationQueue.addTask({
  105532. settings: settings,
  105533. parallelProcessing: parallelProcessing,
  105534. mesh: this,
  105535. simplificationType: simplificationType,
  105536. successCallback: successCallback
  105537. });
  105538. return this;
  105539. };
  105540. /**
  105541. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  105542. * created in a scene
  105543. */
  105544. var SimplicationQueueSceneComponent = /** @class */ (function () {
  105545. /**
  105546. * Creates a new instance of the component for the given scene
  105547. * @param scene Defines the scene to register the component in
  105548. */
  105549. function SimplicationQueueSceneComponent(scene) {
  105550. /**
  105551. * The component name helpfull to identify the component in the list of scene components.
  105552. */
  105553. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  105554. this.scene = scene;
  105555. }
  105556. /**
  105557. * Registers the component in a given scene
  105558. */
  105559. SimplicationQueueSceneComponent.prototype.register = function () {
  105560. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  105561. };
  105562. /**
  105563. * Rebuilds the elements related to this component in case of
  105564. * context lost for instance.
  105565. */
  105566. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  105567. // Nothing to do for this component
  105568. };
  105569. /**
  105570. * Disposes the component and the associated ressources
  105571. */
  105572. SimplicationQueueSceneComponent.prototype.dispose = function () {
  105573. // Nothing to do for this component
  105574. };
  105575. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  105576. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  105577. this.scene._simplificationQueue.executeNext();
  105578. }
  105579. };
  105580. return SimplicationQueueSceneComponent;
  105581. }());
  105582. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  105583. })(BABYLON || (BABYLON = {}));
  105584. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  105585. var BABYLON;
  105586. (function (BABYLON) {
  105587. /**
  105588. * Class used to represent a specific level of detail of a mesh
  105589. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  105590. */
  105591. var MeshLODLevel = /** @class */ (function () {
  105592. /**
  105593. * Creates a new LOD level
  105594. * @param distance defines the distance where this level should star being displayed
  105595. * @param mesh defines the mesh to use to render this level
  105596. */
  105597. function MeshLODLevel(
  105598. /** Defines the distance where this level should star being displayed */
  105599. distance,
  105600. /** Defines the mesh to use to render this level */
  105601. mesh) {
  105602. this.distance = distance;
  105603. this.mesh = mesh;
  105604. }
  105605. return MeshLODLevel;
  105606. }());
  105607. BABYLON.MeshLODLevel = MeshLODLevel;
  105608. })(BABYLON || (BABYLON = {}));
  105609. //# sourceMappingURL=babylon.meshLODLevel.js.map
  105610. var BABYLON;
  105611. (function (BABYLON) {
  105612. /**
  105613. * Defines the root class used to create scene optimization to use with SceneOptimizer
  105614. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105615. */
  105616. var SceneOptimization = /** @class */ (function () {
  105617. /**
  105618. * Creates the SceneOptimization object
  105619. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105620. * @param desc defines the description associated with the optimization
  105621. */
  105622. function SceneOptimization(
  105623. /**
  105624. * Defines the priority of this optimization (0 by default which means first in the list)
  105625. */
  105626. priority) {
  105627. if (priority === void 0) { priority = 0; }
  105628. this.priority = priority;
  105629. }
  105630. /**
  105631. * Gets a string describing the action executed by the current optimization
  105632. * @returns description string
  105633. */
  105634. SceneOptimization.prototype.getDescription = function () {
  105635. return "";
  105636. };
  105637. /**
  105638. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105639. * @param scene defines the current scene where to apply this optimization
  105640. * @param optimizer defines the current optimizer
  105641. * @returns true if everything that can be done was applied
  105642. */
  105643. SceneOptimization.prototype.apply = function (scene, optimizer) {
  105644. return true;
  105645. };
  105646. ;
  105647. return SceneOptimization;
  105648. }());
  105649. BABYLON.SceneOptimization = SceneOptimization;
  105650. /**
  105651. * Defines an optimization used to reduce the size of render target textures
  105652. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105653. */
  105654. var TextureOptimization = /** @class */ (function (_super) {
  105655. __extends(TextureOptimization, _super);
  105656. /**
  105657. * Creates the TextureOptimization object
  105658. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105659. * @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
  105660. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  105661. */
  105662. function TextureOptimization(
  105663. /**
  105664. * Defines the priority of this optimization (0 by default which means first in the list)
  105665. */
  105666. priority,
  105667. /**
  105668. * 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
  105669. */
  105670. maximumSize,
  105671. /**
  105672. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  105673. */
  105674. step) {
  105675. if (priority === void 0) { priority = 0; }
  105676. if (maximumSize === void 0) { maximumSize = 1024; }
  105677. if (step === void 0) { step = 0.5; }
  105678. var _this = _super.call(this, priority) || this;
  105679. _this.priority = priority;
  105680. _this.maximumSize = maximumSize;
  105681. _this.step = step;
  105682. return _this;
  105683. }
  105684. /**
  105685. * Gets a string describing the action executed by the current optimization
  105686. * @returns description string
  105687. */
  105688. TextureOptimization.prototype.getDescription = function () {
  105689. return "Reducing render target texture size to " + this.maximumSize;
  105690. };
  105691. /**
  105692. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105693. * @param scene defines the current scene where to apply this optimization
  105694. * @param optimizer defines the current optimizer
  105695. * @returns true if everything that can be done was applied
  105696. */
  105697. TextureOptimization.prototype.apply = function (scene, optimizer) {
  105698. var allDone = true;
  105699. for (var index = 0; index < scene.textures.length; index++) {
  105700. var texture = scene.textures[index];
  105701. if (!texture.canRescale || texture.getContext) {
  105702. continue;
  105703. }
  105704. var currentSize = texture.getSize();
  105705. var maxDimension = Math.max(currentSize.width, currentSize.height);
  105706. if (maxDimension > this.maximumSize) {
  105707. texture.scale(this.step);
  105708. allDone = false;
  105709. }
  105710. }
  105711. return allDone;
  105712. };
  105713. return TextureOptimization;
  105714. }(SceneOptimization));
  105715. BABYLON.TextureOptimization = TextureOptimization;
  105716. /**
  105717. * Defines an optimization used to increase or decrease the rendering resolution
  105718. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105719. */
  105720. var HardwareScalingOptimization = /** @class */ (function (_super) {
  105721. __extends(HardwareScalingOptimization, _super);
  105722. /**
  105723. * Creates the HardwareScalingOptimization object
  105724. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105725. * @param maximumScale defines the maximum scale to use (2 by default)
  105726. * @param step defines the step to use between two passes (0.5 by default)
  105727. */
  105728. function HardwareScalingOptimization(
  105729. /**
  105730. * Defines the priority of this optimization (0 by default which means first in the list)
  105731. */
  105732. priority,
  105733. /**
  105734. * Defines the maximum scale to use (2 by default)
  105735. */
  105736. maximumScale,
  105737. /**
  105738. * Defines the step to use between two passes (0.5 by default)
  105739. */
  105740. step) {
  105741. if (priority === void 0) { priority = 0; }
  105742. if (maximumScale === void 0) { maximumScale = 2; }
  105743. if (step === void 0) { step = 0.25; }
  105744. var _this = _super.call(this, priority) || this;
  105745. _this.priority = priority;
  105746. _this.maximumScale = maximumScale;
  105747. _this.step = step;
  105748. _this._currentScale = -1;
  105749. _this._directionOffset = 1;
  105750. return _this;
  105751. }
  105752. /**
  105753. * Gets a string describing the action executed by the current optimization
  105754. * @return description string
  105755. */
  105756. HardwareScalingOptimization.prototype.getDescription = function () {
  105757. return "Setting hardware scaling level to " + this._currentScale;
  105758. };
  105759. /**
  105760. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105761. * @param scene defines the current scene where to apply this optimization
  105762. * @param optimizer defines the current optimizer
  105763. * @returns true if everything that can be done was applied
  105764. */
  105765. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  105766. if (this._currentScale === -1) {
  105767. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  105768. if (this._currentScale > this.maximumScale) {
  105769. this._directionOffset = -1;
  105770. }
  105771. }
  105772. this._currentScale += this._directionOffset * this.step;
  105773. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  105774. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  105775. };
  105776. ;
  105777. return HardwareScalingOptimization;
  105778. }(SceneOptimization));
  105779. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  105780. /**
  105781. * Defines an optimization used to remove shadows
  105782. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105783. */
  105784. var ShadowsOptimization = /** @class */ (function (_super) {
  105785. __extends(ShadowsOptimization, _super);
  105786. function ShadowsOptimization() {
  105787. return _super !== null && _super.apply(this, arguments) || this;
  105788. }
  105789. /**
  105790. * Gets a string describing the action executed by the current optimization
  105791. * @return description string
  105792. */
  105793. ShadowsOptimization.prototype.getDescription = function () {
  105794. return "Turning shadows on/off";
  105795. };
  105796. /**
  105797. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105798. * @param scene defines the current scene where to apply this optimization
  105799. * @param optimizer defines the current optimizer
  105800. * @returns true if everything that can be done was applied
  105801. */
  105802. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  105803. scene.shadowsEnabled = optimizer.isInImprovementMode;
  105804. return true;
  105805. };
  105806. ;
  105807. return ShadowsOptimization;
  105808. }(SceneOptimization));
  105809. BABYLON.ShadowsOptimization = ShadowsOptimization;
  105810. /**
  105811. * Defines an optimization used to turn post-processes off
  105812. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105813. */
  105814. var PostProcessesOptimization = /** @class */ (function (_super) {
  105815. __extends(PostProcessesOptimization, _super);
  105816. function PostProcessesOptimization() {
  105817. return _super !== null && _super.apply(this, arguments) || this;
  105818. }
  105819. /**
  105820. * Gets a string describing the action executed by the current optimization
  105821. * @return description string
  105822. */
  105823. PostProcessesOptimization.prototype.getDescription = function () {
  105824. return "Turning post-processes on/off";
  105825. };
  105826. /**
  105827. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105828. * @param scene defines the current scene where to apply this optimization
  105829. * @param optimizer defines the current optimizer
  105830. * @returns true if everything that can be done was applied
  105831. */
  105832. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  105833. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  105834. return true;
  105835. };
  105836. ;
  105837. return PostProcessesOptimization;
  105838. }(SceneOptimization));
  105839. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  105840. /**
  105841. * Defines an optimization used to turn lens flares off
  105842. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105843. */
  105844. var LensFlaresOptimization = /** @class */ (function (_super) {
  105845. __extends(LensFlaresOptimization, _super);
  105846. function LensFlaresOptimization() {
  105847. return _super !== null && _super.apply(this, arguments) || this;
  105848. }
  105849. /**
  105850. * Gets a string describing the action executed by the current optimization
  105851. * @return description string
  105852. */
  105853. LensFlaresOptimization.prototype.getDescription = function () {
  105854. return "Turning lens flares on/off";
  105855. };
  105856. /**
  105857. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105858. * @param scene defines the current scene where to apply this optimization
  105859. * @param optimizer defines the current optimizer
  105860. * @returns true if everything that can be done was applied
  105861. */
  105862. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  105863. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  105864. return true;
  105865. };
  105866. ;
  105867. return LensFlaresOptimization;
  105868. }(SceneOptimization));
  105869. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  105870. /**
  105871. * Defines an optimization based on user defined callback.
  105872. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105873. */
  105874. var CustomOptimization = /** @class */ (function (_super) {
  105875. __extends(CustomOptimization, _super);
  105876. function CustomOptimization() {
  105877. return _super !== null && _super.apply(this, arguments) || this;
  105878. }
  105879. /**
  105880. * Gets a string describing the action executed by the current optimization
  105881. * @returns description string
  105882. */
  105883. CustomOptimization.prototype.getDescription = function () {
  105884. if (this.onGetDescription) {
  105885. return this.onGetDescription();
  105886. }
  105887. return "Running user defined callback";
  105888. };
  105889. /**
  105890. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105891. * @param scene defines the current scene where to apply this optimization
  105892. * @param optimizer defines the current optimizer
  105893. * @returns true if everything that can be done was applied
  105894. */
  105895. CustomOptimization.prototype.apply = function (scene, optimizer) {
  105896. if (this.onApply) {
  105897. return this.onApply(scene, optimizer);
  105898. }
  105899. return true;
  105900. };
  105901. ;
  105902. return CustomOptimization;
  105903. }(SceneOptimization));
  105904. BABYLON.CustomOptimization = CustomOptimization;
  105905. /**
  105906. * Defines an optimization used to turn particles off
  105907. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105908. */
  105909. var ParticlesOptimization = /** @class */ (function (_super) {
  105910. __extends(ParticlesOptimization, _super);
  105911. function ParticlesOptimization() {
  105912. return _super !== null && _super.apply(this, arguments) || this;
  105913. }
  105914. /**
  105915. * Gets a string describing the action executed by the current optimization
  105916. * @return description string
  105917. */
  105918. ParticlesOptimization.prototype.getDescription = function () {
  105919. return "Turning particles on/off";
  105920. };
  105921. /**
  105922. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105923. * @param scene defines the current scene where to apply this optimization
  105924. * @param optimizer defines the current optimizer
  105925. * @returns true if everything that can be done was applied
  105926. */
  105927. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  105928. scene.particlesEnabled = optimizer.isInImprovementMode;
  105929. return true;
  105930. };
  105931. ;
  105932. return ParticlesOptimization;
  105933. }(SceneOptimization));
  105934. BABYLON.ParticlesOptimization = ParticlesOptimization;
  105935. /**
  105936. * Defines an optimization used to turn render targets off
  105937. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105938. */
  105939. var RenderTargetsOptimization = /** @class */ (function (_super) {
  105940. __extends(RenderTargetsOptimization, _super);
  105941. function RenderTargetsOptimization() {
  105942. return _super !== null && _super.apply(this, arguments) || this;
  105943. }
  105944. /**
  105945. * Gets a string describing the action executed by the current optimization
  105946. * @return description string
  105947. */
  105948. RenderTargetsOptimization.prototype.getDescription = function () {
  105949. return "Turning render targets off";
  105950. };
  105951. /**
  105952. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105953. * @param scene defines the current scene where to apply this optimization
  105954. * @param optimizer defines the current optimizer
  105955. * @returns true if everything that can be done was applied
  105956. */
  105957. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  105958. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  105959. return true;
  105960. };
  105961. ;
  105962. return RenderTargetsOptimization;
  105963. }(SceneOptimization));
  105964. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  105965. /**
  105966. * Defines an optimization used to merge meshes with compatible materials
  105967. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105968. */
  105969. var MergeMeshesOptimization = /** @class */ (function (_super) {
  105970. __extends(MergeMeshesOptimization, _super);
  105971. function MergeMeshesOptimization() {
  105972. var _this = _super !== null && _super.apply(this, arguments) || this;
  105973. _this._canBeMerged = function (abstractMesh) {
  105974. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  105975. return false;
  105976. }
  105977. var mesh = abstractMesh;
  105978. if (mesh.isDisposed()) {
  105979. return false;
  105980. }
  105981. if (!mesh.isVisible || !mesh.isEnabled()) {
  105982. return false;
  105983. }
  105984. if (mesh.instances.length > 0) {
  105985. return false;
  105986. }
  105987. if (mesh.skeleton || mesh.hasLODLevels) {
  105988. return false;
  105989. }
  105990. return true;
  105991. };
  105992. return _this;
  105993. }
  105994. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  105995. /**
  105996. * Gets or sets a boolean which defines if optimization octree has to be updated
  105997. */
  105998. get: function () {
  105999. return MergeMeshesOptimization._UpdateSelectionTree;
  106000. },
  106001. /**
  106002. * Gets or sets a boolean which defines if optimization octree has to be updated
  106003. */
  106004. set: function (value) {
  106005. MergeMeshesOptimization._UpdateSelectionTree = value;
  106006. },
  106007. enumerable: true,
  106008. configurable: true
  106009. });
  106010. /**
  106011. * Gets a string describing the action executed by the current optimization
  106012. * @return description string
  106013. */
  106014. MergeMeshesOptimization.prototype.getDescription = function () {
  106015. return "Merging similar meshes together";
  106016. };
  106017. /**
  106018. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  106019. * @param scene defines the current scene where to apply this optimization
  106020. * @param optimizer defines the current optimizer
  106021. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  106022. * @returns true if everything that can be done was applied
  106023. */
  106024. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  106025. var globalPool = scene.meshes.slice(0);
  106026. var globalLength = globalPool.length;
  106027. for (var index = 0; index < globalLength; index++) {
  106028. var currentPool = new Array();
  106029. var current = globalPool[index];
  106030. // Checks
  106031. if (!this._canBeMerged(current)) {
  106032. continue;
  106033. }
  106034. currentPool.push(current);
  106035. // Find compatible meshes
  106036. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  106037. var otherMesh = globalPool[subIndex];
  106038. if (!this._canBeMerged(otherMesh)) {
  106039. continue;
  106040. }
  106041. if (otherMesh.material !== current.material) {
  106042. continue;
  106043. }
  106044. if (otherMesh.checkCollisions !== current.checkCollisions) {
  106045. continue;
  106046. }
  106047. currentPool.push(otherMesh);
  106048. globalLength--;
  106049. globalPool.splice(subIndex, 1);
  106050. subIndex--;
  106051. }
  106052. if (currentPool.length < 2) {
  106053. continue;
  106054. }
  106055. // Merge meshes
  106056. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  106057. }
  106058. // Call the octree system optimization if it is defined.
  106059. var sceneAsAny = scene;
  106060. if (sceneAsAny.createOrUpdateSelectionOctree) {
  106061. if (updateSelectionTree != undefined) {
  106062. if (updateSelectionTree) {
  106063. sceneAsAny.createOrUpdateSelectionOctree();
  106064. }
  106065. }
  106066. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  106067. sceneAsAny.createOrUpdateSelectionOctree();
  106068. }
  106069. }
  106070. return true;
  106071. };
  106072. ;
  106073. MergeMeshesOptimization._UpdateSelectionTree = false;
  106074. return MergeMeshesOptimization;
  106075. }(SceneOptimization));
  106076. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  106077. /**
  106078. * Defines a list of options used by SceneOptimizer
  106079. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  106080. */
  106081. var SceneOptimizerOptions = /** @class */ (function () {
  106082. /**
  106083. * Creates a new list of options used by SceneOptimizer
  106084. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  106085. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  106086. */
  106087. function SceneOptimizerOptions(
  106088. /**
  106089. * Defines the target frame rate to reach (60 by default)
  106090. */
  106091. targetFrameRate,
  106092. /**
  106093. * Defines the interval between two checkes (2000ms by default)
  106094. */
  106095. trackerDuration) {
  106096. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  106097. if (trackerDuration === void 0) { trackerDuration = 2000; }
  106098. this.targetFrameRate = targetFrameRate;
  106099. this.trackerDuration = trackerDuration;
  106100. /**
  106101. * Gets the list of optimizations to apply
  106102. */
  106103. this.optimizations = new Array();
  106104. }
  106105. /**
  106106. * Add a new optimization
  106107. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  106108. * @returns the current SceneOptimizerOptions
  106109. */
  106110. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  106111. this.optimizations.push(optimization);
  106112. return this;
  106113. };
  106114. /**
  106115. * Add a new custom optimization
  106116. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  106117. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  106118. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  106119. * @returns the current SceneOptimizerOptions
  106120. */
  106121. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  106122. if (priority === void 0) { priority = 0; }
  106123. var optimization = new CustomOptimization(priority);
  106124. optimization.onApply = onApply;
  106125. optimization.onGetDescription = onGetDescription;
  106126. this.optimizations.push(optimization);
  106127. return this;
  106128. };
  106129. /**
  106130. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  106131. * @param targetFrameRate defines the target frame rate (60 by default)
  106132. * @returns a SceneOptimizerOptions object
  106133. */
  106134. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  106135. var result = new SceneOptimizerOptions(targetFrameRate);
  106136. var priority = 0;
  106137. result.addOptimization(new MergeMeshesOptimization(priority));
  106138. result.addOptimization(new ShadowsOptimization(priority));
  106139. result.addOptimization(new LensFlaresOptimization(priority));
  106140. // Next priority
  106141. priority++;
  106142. result.addOptimization(new PostProcessesOptimization(priority));
  106143. result.addOptimization(new ParticlesOptimization(priority));
  106144. // Next priority
  106145. priority++;
  106146. result.addOptimization(new TextureOptimization(priority, 1024));
  106147. return result;
  106148. };
  106149. /**
  106150. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  106151. * @param targetFrameRate defines the target frame rate (60 by default)
  106152. * @returns a SceneOptimizerOptions object
  106153. */
  106154. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  106155. var result = new SceneOptimizerOptions(targetFrameRate);
  106156. var priority = 0;
  106157. result.addOptimization(new MergeMeshesOptimization(priority));
  106158. result.addOptimization(new ShadowsOptimization(priority));
  106159. result.addOptimization(new LensFlaresOptimization(priority));
  106160. // Next priority
  106161. priority++;
  106162. result.addOptimization(new PostProcessesOptimization(priority));
  106163. result.addOptimization(new ParticlesOptimization(priority));
  106164. // Next priority
  106165. priority++;
  106166. result.addOptimization(new TextureOptimization(priority, 512));
  106167. // Next priority
  106168. priority++;
  106169. result.addOptimization(new RenderTargetsOptimization(priority));
  106170. // Next priority
  106171. priority++;
  106172. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  106173. return result;
  106174. };
  106175. /**
  106176. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  106177. * @param targetFrameRate defines the target frame rate (60 by default)
  106178. * @returns a SceneOptimizerOptions object
  106179. */
  106180. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  106181. var result = new SceneOptimizerOptions(targetFrameRate);
  106182. var priority = 0;
  106183. result.addOptimization(new MergeMeshesOptimization(priority));
  106184. result.addOptimization(new ShadowsOptimization(priority));
  106185. result.addOptimization(new LensFlaresOptimization(priority));
  106186. // Next priority
  106187. priority++;
  106188. result.addOptimization(new PostProcessesOptimization(priority));
  106189. result.addOptimization(new ParticlesOptimization(priority));
  106190. // Next priority
  106191. priority++;
  106192. result.addOptimization(new TextureOptimization(priority, 256));
  106193. // Next priority
  106194. priority++;
  106195. result.addOptimization(new RenderTargetsOptimization(priority));
  106196. // Next priority
  106197. priority++;
  106198. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  106199. return result;
  106200. };
  106201. return SceneOptimizerOptions;
  106202. }());
  106203. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  106204. /**
  106205. * Class used to run optimizations in order to reach a target frame rate
  106206. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  106207. */
  106208. var SceneOptimizer = /** @class */ (function () {
  106209. /**
  106210. * Creates a new SceneOptimizer
  106211. * @param scene defines the scene to work on
  106212. * @param options defines the options to use with the SceneOptimizer
  106213. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  106214. * @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)
  106215. */
  106216. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  106217. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  106218. if (improvementMode === void 0) { improvementMode = false; }
  106219. var _this = this;
  106220. this._isRunning = false;
  106221. this._currentPriorityLevel = 0;
  106222. this._targetFrameRate = 60;
  106223. this._trackerDuration = 2000;
  106224. this._currentFrameRate = 0;
  106225. this._improvementMode = false;
  106226. /**
  106227. * Defines an observable called when the optimizer reaches the target frame rate
  106228. */
  106229. this.onSuccessObservable = new BABYLON.Observable();
  106230. /**
  106231. * Defines an observable called when the optimizer enables an optimization
  106232. */
  106233. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  106234. /**
  106235. * Defines an observable called when the optimizer is not able to reach the target frame rate
  106236. */
  106237. this.onFailureObservable = new BABYLON.Observable();
  106238. if (!options) {
  106239. this._options = new SceneOptimizerOptions();
  106240. }
  106241. else {
  106242. this._options = options;
  106243. }
  106244. if (this._options.targetFrameRate) {
  106245. this._targetFrameRate = this._options.targetFrameRate;
  106246. }
  106247. if (this._options.trackerDuration) {
  106248. this._trackerDuration = this._options.trackerDuration;
  106249. }
  106250. if (autoGeneratePriorities) {
  106251. var priority = 0;
  106252. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  106253. var optim = _a[_i];
  106254. optim.priority = priority++;
  106255. }
  106256. }
  106257. this._improvementMode = improvementMode;
  106258. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  106259. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  106260. _this._sceneDisposeObserver = null;
  106261. _this.dispose();
  106262. });
  106263. }
  106264. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  106265. /**
  106266. * Gets a boolean indicating if the optimizer is in improvement mode
  106267. */
  106268. get: function () {
  106269. return this._improvementMode;
  106270. },
  106271. enumerable: true,
  106272. configurable: true
  106273. });
  106274. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  106275. /**
  106276. * Gets the current priority level (0 at start)
  106277. */
  106278. get: function () {
  106279. return this._currentPriorityLevel;
  106280. },
  106281. enumerable: true,
  106282. configurable: true
  106283. });
  106284. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  106285. /**
  106286. * Gets the current frame rate checked by the SceneOptimizer
  106287. */
  106288. get: function () {
  106289. return this._currentFrameRate;
  106290. },
  106291. enumerable: true,
  106292. configurable: true
  106293. });
  106294. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  106295. /**
  106296. * Gets or sets the current target frame rate (60 by default)
  106297. */
  106298. get: function () {
  106299. return this._targetFrameRate;
  106300. },
  106301. /**
  106302. * Gets or sets the current target frame rate (60 by default)
  106303. */
  106304. set: function (value) {
  106305. this._targetFrameRate = value;
  106306. },
  106307. enumerable: true,
  106308. configurable: true
  106309. });
  106310. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  106311. /**
  106312. * Gets or sets the current interval between two checks (every 2000ms by default)
  106313. */
  106314. get: function () {
  106315. return this._trackerDuration;
  106316. },
  106317. /**
  106318. * Gets or sets the current interval between two checks (every 2000ms by default)
  106319. */
  106320. set: function (value) {
  106321. this._trackerDuration = value;
  106322. },
  106323. enumerable: true,
  106324. configurable: true
  106325. });
  106326. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  106327. /**
  106328. * Gets the list of active optimizations
  106329. */
  106330. get: function () {
  106331. return this._options.optimizations;
  106332. },
  106333. enumerable: true,
  106334. configurable: true
  106335. });
  106336. /**
  106337. * Stops the current optimizer
  106338. */
  106339. SceneOptimizer.prototype.stop = function () {
  106340. this._isRunning = false;
  106341. };
  106342. /**
  106343. * Reset the optimizer to initial step (current priority level = 0)
  106344. */
  106345. SceneOptimizer.prototype.reset = function () {
  106346. this._currentPriorityLevel = 0;
  106347. };
  106348. /**
  106349. * Start the optimizer. By default it will try to reach a specific framerate
  106350. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  106351. */
  106352. SceneOptimizer.prototype.start = function () {
  106353. var _this = this;
  106354. if (this._isRunning) {
  106355. return;
  106356. }
  106357. this._isRunning = true;
  106358. // Let's wait for the scene to be ready before running our check
  106359. this._scene.executeWhenReady(function () {
  106360. setTimeout(function () {
  106361. _this._checkCurrentState();
  106362. }, _this._trackerDuration);
  106363. });
  106364. };
  106365. SceneOptimizer.prototype._checkCurrentState = function () {
  106366. var _this = this;
  106367. if (!this._isRunning) {
  106368. return;
  106369. }
  106370. var scene = this._scene;
  106371. var options = this._options;
  106372. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  106373. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  106374. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  106375. this._isRunning = false;
  106376. this.onSuccessObservable.notifyObservers(this);
  106377. return;
  106378. }
  106379. // Apply current level of optimizations
  106380. var allDone = true;
  106381. var noOptimizationApplied = true;
  106382. for (var index = 0; index < options.optimizations.length; index++) {
  106383. var optimization = options.optimizations[index];
  106384. if (optimization.priority === this._currentPriorityLevel) {
  106385. noOptimizationApplied = false;
  106386. allDone = allDone && optimization.apply(scene, this);
  106387. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  106388. }
  106389. }
  106390. // If no optimization was applied, this is a failure :(
  106391. if (noOptimizationApplied) {
  106392. this._isRunning = false;
  106393. this.onFailureObservable.notifyObservers(this);
  106394. return;
  106395. }
  106396. // If all optimizations were done, move to next level
  106397. if (allDone) {
  106398. this._currentPriorityLevel++;
  106399. }
  106400. // Let's the system running for a specific amount of time before checking FPS
  106401. scene.executeWhenReady(function () {
  106402. setTimeout(function () {
  106403. _this._checkCurrentState();
  106404. }, _this._trackerDuration);
  106405. });
  106406. };
  106407. /**
  106408. * Release all resources
  106409. */
  106410. SceneOptimizer.prototype.dispose = function () {
  106411. this.stop();
  106412. this.onSuccessObservable.clear();
  106413. this.onFailureObservable.clear();
  106414. this.onNewOptimizationAppliedObservable.clear();
  106415. if (this._sceneDisposeObserver) {
  106416. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  106417. }
  106418. };
  106419. /**
  106420. * Helper function to create a SceneOptimizer with one single line of code
  106421. * @param scene defines the scene to work on
  106422. * @param options defines the options to use with the SceneOptimizer
  106423. * @param onSuccess defines a callback to call on success
  106424. * @param onFailure defines a callback to call on failure
  106425. * @returns the new SceneOptimizer object
  106426. */
  106427. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  106428. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  106429. if (onSuccess) {
  106430. optimizer.onSuccessObservable.add(function () {
  106431. onSuccess();
  106432. });
  106433. }
  106434. if (onFailure) {
  106435. optimizer.onFailureObservable.add(function () {
  106436. onFailure();
  106437. });
  106438. }
  106439. optimizer.start();
  106440. return optimizer;
  106441. };
  106442. return SceneOptimizer;
  106443. }());
  106444. BABYLON.SceneOptimizer = SceneOptimizer;
  106445. })(BABYLON || (BABYLON = {}));
  106446. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  106447. var BABYLON;
  106448. (function (BABYLON) {
  106449. /**
  106450. * Gets the outline renderer associated with the scene
  106451. * @returns a OutlineRenderer
  106452. */
  106453. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  106454. if (!this._outlineRenderer) {
  106455. this._outlineRenderer = new OutlineRenderer(this);
  106456. }
  106457. return this._outlineRenderer;
  106458. };
  106459. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  106460. get: function () {
  106461. return this._renderOutline;
  106462. },
  106463. set: function (value) {
  106464. if (value) {
  106465. // Lazy Load the component.
  106466. this.getScene().getOutlineRenderer();
  106467. }
  106468. this._renderOutline = value;
  106469. },
  106470. enumerable: true,
  106471. configurable: true
  106472. });
  106473. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  106474. get: function () {
  106475. return this._renderOverlay;
  106476. },
  106477. set: function (value) {
  106478. if (value) {
  106479. // Lazy Load the component.
  106480. this.getScene().getOutlineRenderer();
  106481. }
  106482. this._renderOverlay = value;
  106483. },
  106484. enumerable: true,
  106485. configurable: true
  106486. });
  106487. /**
  106488. * This class is responsible to draw bothe outline/overlay of meshes.
  106489. * It should not be used directly but through the available method on mesh.
  106490. */
  106491. var OutlineRenderer = /** @class */ (function () {
  106492. /**
  106493. * Instantiates a new outline renderer. (There could be only one per scene).
  106494. * @param scene Defines the scene it belongs to
  106495. */
  106496. function OutlineRenderer(scene) {
  106497. /**
  106498. * The name of the component. Each component must have a unique name.
  106499. */
  106500. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  106501. /**
  106502. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  106503. */
  106504. this.zOffset = 1;
  106505. this.scene = scene;
  106506. this._engine = scene.getEngine();
  106507. this.scene._addComponent(this);
  106508. }
  106509. /**
  106510. * Register the component to one instance of a scene.
  106511. */
  106512. OutlineRenderer.prototype.register = function () {
  106513. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  106514. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  106515. };
  106516. /**
  106517. * Rebuilds the elements related to this component in case of
  106518. * context lost for instance.
  106519. */
  106520. OutlineRenderer.prototype.rebuild = function () {
  106521. // Nothing to do here.
  106522. };
  106523. /**
  106524. * Disposes the component and the associated ressources.
  106525. */
  106526. OutlineRenderer.prototype.dispose = function () {
  106527. // Nothing to do here.
  106528. };
  106529. /**
  106530. * Renders the outline in the canvas.
  106531. * @param subMesh Defines the sumesh to render
  106532. * @param batch Defines the batch of meshes in case of instances
  106533. * @param useOverlay Defines if the rendering is for the overlay or the outline
  106534. */
  106535. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  106536. var _this = this;
  106537. if (useOverlay === void 0) { useOverlay = false; }
  106538. var scene = this.scene;
  106539. var engine = scene.getEngine();
  106540. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  106541. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  106542. return;
  106543. }
  106544. var mesh = subMesh.getRenderingMesh();
  106545. var material = subMesh.getMaterial();
  106546. if (!material || !scene.activeCamera) {
  106547. return;
  106548. }
  106549. engine.enableEffect(this._effect);
  106550. // Logarithmic depth
  106551. if (material.useLogarithmicDepth) {
  106552. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  106553. }
  106554. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  106555. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  106556. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  106557. // Bones
  106558. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  106559. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  106560. }
  106561. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  106562. // Alpha test
  106563. if (material && material.needAlphaTesting()) {
  106564. var alphaTexture = material.getAlphaTestTexture();
  106565. if (alphaTexture) {
  106566. this._effect.setTexture("diffuseSampler", alphaTexture);
  106567. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  106568. }
  106569. }
  106570. engine.setZOffset(-this.zOffset);
  106571. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  106572. engine.setZOffset(0);
  106573. };
  106574. /**
  106575. * Returns whether or not the outline renderer is ready for a given submesh.
  106576. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  106577. * @param subMesh Defines the submesh to check readyness for
  106578. * @param useInstances Defines wheter wee are trying to render instances or not
  106579. * @returns true if ready otherwise false
  106580. */
  106581. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  106582. var defines = [];
  106583. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  106584. var mesh = subMesh.getMesh();
  106585. var material = subMesh.getMaterial();
  106586. if (material) {
  106587. // Alpha test
  106588. if (material.needAlphaTesting()) {
  106589. defines.push("#define ALPHATEST");
  106590. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  106591. attribs.push(BABYLON.VertexBuffer.UVKind);
  106592. defines.push("#define UV1");
  106593. }
  106594. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  106595. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  106596. defines.push("#define UV2");
  106597. }
  106598. }
  106599. //Logarithmic depth
  106600. if (material.useLogarithmicDepth) {
  106601. defines.push("#define LOGARITHMICDEPTH");
  106602. }
  106603. }
  106604. // Bones
  106605. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  106606. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  106607. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  106608. if (mesh.numBoneInfluencers > 4) {
  106609. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  106610. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  106611. }
  106612. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  106613. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  106614. }
  106615. else {
  106616. defines.push("#define NUM_BONE_INFLUENCERS 0");
  106617. }
  106618. // Instances
  106619. if (useInstances) {
  106620. defines.push("#define INSTANCES");
  106621. attribs.push("world0");
  106622. attribs.push("world1");
  106623. attribs.push("world2");
  106624. attribs.push("world3");
  106625. }
  106626. // Get correct effect
  106627. var join = defines.join("\n");
  106628. if (this._cachedDefines !== join) {
  106629. this._cachedDefines = join;
  106630. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  106631. }
  106632. return this._effect.isReady();
  106633. };
  106634. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  106635. // Outline - step 1
  106636. this._savedDepthWrite = this._engine.getDepthWrite();
  106637. if (mesh.renderOutline) {
  106638. this._engine.setDepthWrite(false);
  106639. this.render(subMesh, batch);
  106640. this._engine.setDepthWrite(this._savedDepthWrite);
  106641. }
  106642. };
  106643. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  106644. // Outline - step 2
  106645. if (mesh.renderOutline && this._savedDepthWrite) {
  106646. this._engine.setDepthWrite(true);
  106647. this._engine.setColorWrite(false);
  106648. this.render(subMesh, batch);
  106649. this._engine.setColorWrite(true);
  106650. }
  106651. // Overlay
  106652. if (mesh.renderOverlay) {
  106653. var currentMode = this._engine.getAlphaMode();
  106654. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  106655. this.render(subMesh, batch, true);
  106656. this._engine.setAlphaMode(currentMode);
  106657. }
  106658. };
  106659. return OutlineRenderer;
  106660. }());
  106661. BABYLON.OutlineRenderer = OutlineRenderer;
  106662. })(BABYLON || (BABYLON = {}));
  106663. //# sourceMappingURL=babylon.outlineRenderer.js.map
  106664. var BABYLON;
  106665. (function (BABYLON) {
  106666. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  106667. if (this._edgesRenderer) {
  106668. this._edgesRenderer.dispose();
  106669. this._edgesRenderer = null;
  106670. }
  106671. return this;
  106672. };
  106673. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  106674. if (epsilon === void 0) { epsilon = 0.95; }
  106675. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106676. this.disableEdgesRendering();
  106677. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  106678. return this;
  106679. };
  106680. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  106681. get: function () {
  106682. return this._edgesRenderer;
  106683. },
  106684. enumerable: true,
  106685. configurable: true
  106686. });
  106687. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  106688. if (epsilon === void 0) { epsilon = 0.95; }
  106689. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106690. this.disableEdgesRendering();
  106691. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  106692. return this;
  106693. };
  106694. /**
  106695. * FaceAdjacencies Helper class to generate edges
  106696. */
  106697. var FaceAdjacencies = /** @class */ (function () {
  106698. function FaceAdjacencies() {
  106699. this.edges = new Array();
  106700. this.edgesConnectedCount = 0;
  106701. }
  106702. return FaceAdjacencies;
  106703. }());
  106704. /**
  106705. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  106706. */
  106707. var EdgesRenderer = /** @class */ (function () {
  106708. /**
  106709. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  106710. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  106711. * @param source Mesh used to create edges
  106712. * @param epsilon sum of angles in adjacency to check for edge
  106713. * @param checkVerticesInsteadOfIndices
  106714. * @param generateEdgesLines - should generate Lines or only prepare resources.
  106715. */
  106716. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  106717. if (epsilon === void 0) { epsilon = 0.95; }
  106718. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106719. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  106720. var _this = this;
  106721. /**
  106722. * Define the size of the edges with an orthographic camera
  106723. */
  106724. this.edgesWidthScalerForOrthographic = 1000.0;
  106725. /**
  106726. * Define the size of the edges with a perspective camera
  106727. */
  106728. this.edgesWidthScalerForPerspective = 50.0;
  106729. this._linesPositions = new Array();
  106730. this._linesNormals = new Array();
  106731. this._linesIndices = new Array();
  106732. this._buffers = {};
  106733. this._checkVerticesInsteadOfIndices = false;
  106734. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  106735. this.isEnabled = true;
  106736. this._source = source;
  106737. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  106738. this._epsilon = epsilon;
  106739. this._prepareRessources();
  106740. if (generateEdgesLines) {
  106741. this._generateEdgesLines();
  106742. }
  106743. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  106744. _this._rebuild();
  106745. });
  106746. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  106747. _this.dispose();
  106748. });
  106749. }
  106750. EdgesRenderer.prototype._prepareRessources = function () {
  106751. if (this._lineShader) {
  106752. return;
  106753. }
  106754. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  106755. attributes: ["position", "normal"],
  106756. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  106757. });
  106758. this._lineShader.disableDepthWrite = true;
  106759. this._lineShader.backFaceCulling = false;
  106760. };
  106761. /** @hidden */
  106762. EdgesRenderer.prototype._rebuild = function () {
  106763. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  106764. if (buffer) {
  106765. buffer._rebuild();
  106766. }
  106767. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  106768. if (buffer) {
  106769. buffer._rebuild();
  106770. }
  106771. var scene = this._source.getScene();
  106772. var engine = scene.getEngine();
  106773. this._ib = engine.createIndexBuffer(this._linesIndices);
  106774. };
  106775. /**
  106776. * Releases the required resources for the edges renderer
  106777. */
  106778. EdgesRenderer.prototype.dispose = function () {
  106779. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  106780. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  106781. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  106782. if (buffer) {
  106783. buffer.dispose();
  106784. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  106785. }
  106786. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  106787. if (buffer) {
  106788. buffer.dispose();
  106789. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  106790. }
  106791. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  106792. this._lineShader.dispose();
  106793. };
  106794. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  106795. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  106796. return 0;
  106797. }
  106798. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  106799. return 1;
  106800. }
  106801. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  106802. return 2;
  106803. }
  106804. return -1;
  106805. };
  106806. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  106807. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  106808. return 0;
  106809. }
  106810. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  106811. return 1;
  106812. }
  106813. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  106814. return 2;
  106815. }
  106816. return -1;
  106817. };
  106818. /**
  106819. * Checks if the pair of p0 and p1 is en edge
  106820. * @param faceIndex
  106821. * @param edge
  106822. * @param faceNormals
  106823. * @param p0
  106824. * @param p1
  106825. * @private
  106826. */
  106827. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  106828. var needToCreateLine;
  106829. if (edge === undefined) {
  106830. needToCreateLine = true;
  106831. }
  106832. else {
  106833. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  106834. needToCreateLine = dotProduct < this._epsilon;
  106835. }
  106836. if (needToCreateLine) {
  106837. var offset = this._linesPositions.length / 3;
  106838. var normal = p0.subtract(p1);
  106839. normal.normalize();
  106840. // Positions
  106841. this._linesPositions.push(p0.x);
  106842. this._linesPositions.push(p0.y);
  106843. this._linesPositions.push(p0.z);
  106844. this._linesPositions.push(p0.x);
  106845. this._linesPositions.push(p0.y);
  106846. this._linesPositions.push(p0.z);
  106847. this._linesPositions.push(p1.x);
  106848. this._linesPositions.push(p1.y);
  106849. this._linesPositions.push(p1.z);
  106850. this._linesPositions.push(p1.x);
  106851. this._linesPositions.push(p1.y);
  106852. this._linesPositions.push(p1.z);
  106853. // Normals
  106854. this._linesNormals.push(p1.x);
  106855. this._linesNormals.push(p1.y);
  106856. this._linesNormals.push(p1.z);
  106857. this._linesNormals.push(-1);
  106858. this._linesNormals.push(p1.x);
  106859. this._linesNormals.push(p1.y);
  106860. this._linesNormals.push(p1.z);
  106861. this._linesNormals.push(1);
  106862. this._linesNormals.push(p0.x);
  106863. this._linesNormals.push(p0.y);
  106864. this._linesNormals.push(p0.z);
  106865. this._linesNormals.push(-1);
  106866. this._linesNormals.push(p0.x);
  106867. this._linesNormals.push(p0.y);
  106868. this._linesNormals.push(p0.z);
  106869. this._linesNormals.push(1);
  106870. // Indices
  106871. this._linesIndices.push(offset);
  106872. this._linesIndices.push(offset + 1);
  106873. this._linesIndices.push(offset + 2);
  106874. this._linesIndices.push(offset);
  106875. this._linesIndices.push(offset + 2);
  106876. this._linesIndices.push(offset + 3);
  106877. }
  106878. };
  106879. /**
  106880. * Generates lines edges from adjacencjes
  106881. * @private
  106882. */
  106883. EdgesRenderer.prototype._generateEdgesLines = function () {
  106884. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106885. var indices = this._source.getIndices();
  106886. if (!indices || !positions) {
  106887. return;
  106888. }
  106889. // First let's find adjacencies
  106890. var adjacencies = new Array();
  106891. var faceNormals = new Array();
  106892. var index;
  106893. var faceAdjacencies;
  106894. // Prepare faces
  106895. for (index = 0; index < indices.length; index += 3) {
  106896. faceAdjacencies = new FaceAdjacencies();
  106897. var p0Index = indices[index];
  106898. var p1Index = indices[index + 1];
  106899. var p2Index = indices[index + 2];
  106900. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  106901. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  106902. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  106903. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  106904. faceNormal.normalize();
  106905. faceNormals.push(faceNormal);
  106906. adjacencies.push(faceAdjacencies);
  106907. }
  106908. // Scan
  106909. for (index = 0; index < adjacencies.length; index++) {
  106910. faceAdjacencies = adjacencies[index];
  106911. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  106912. var otherFaceAdjacencies = adjacencies[otherIndex];
  106913. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  106914. break;
  106915. }
  106916. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  106917. continue;
  106918. }
  106919. var otherP0 = indices[otherIndex * 3];
  106920. var otherP1 = indices[otherIndex * 3 + 1];
  106921. var otherP2 = indices[otherIndex * 3 + 2];
  106922. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  106923. var otherEdgeIndex = 0;
  106924. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  106925. continue;
  106926. }
  106927. switch (edgeIndex) {
  106928. case 0:
  106929. if (this._checkVerticesInsteadOfIndices) {
  106930. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106931. }
  106932. else {
  106933. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  106934. }
  106935. break;
  106936. case 1:
  106937. if (this._checkVerticesInsteadOfIndices) {
  106938. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106939. }
  106940. else {
  106941. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  106942. }
  106943. break;
  106944. case 2:
  106945. if (this._checkVerticesInsteadOfIndices) {
  106946. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106947. }
  106948. else {
  106949. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  106950. }
  106951. break;
  106952. }
  106953. if (otherEdgeIndex === -1) {
  106954. continue;
  106955. }
  106956. faceAdjacencies.edges[edgeIndex] = otherIndex;
  106957. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  106958. faceAdjacencies.edgesConnectedCount++;
  106959. otherFaceAdjacencies.edgesConnectedCount++;
  106960. if (faceAdjacencies.edgesConnectedCount === 3) {
  106961. break;
  106962. }
  106963. }
  106964. }
  106965. }
  106966. // Create lines
  106967. for (index = 0; index < adjacencies.length; index++) {
  106968. // 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
  106969. var current = adjacencies[index];
  106970. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  106971. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  106972. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  106973. }
  106974. // Merge into a single mesh
  106975. var engine = this._source.getScene().getEngine();
  106976. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  106977. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  106978. this._ib = engine.createIndexBuffer(this._linesIndices);
  106979. this._indicesCount = this._linesIndices.length;
  106980. };
  106981. /**
  106982. * Checks wether or not the edges renderer is ready to render.
  106983. * @return true if ready, otherwise false.
  106984. */
  106985. EdgesRenderer.prototype.isReady = function () {
  106986. return this._lineShader.isReady();
  106987. };
  106988. /**
  106989. * Renders the edges of the attached mesh,
  106990. */
  106991. EdgesRenderer.prototype.render = function () {
  106992. var scene = this._source.getScene();
  106993. if (!this.isReady() || !scene.activeCamera) {
  106994. return;
  106995. }
  106996. var engine = scene.getEngine();
  106997. this._lineShader._preBind();
  106998. if (this._source.edgesColor.a !== 1) {
  106999. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  107000. }
  107001. else {
  107002. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  107003. }
  107004. // VBOs
  107005. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  107006. scene.resetCachedMaterial();
  107007. this._lineShader.setColor4("color", this._source.edgesColor);
  107008. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  107009. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  107010. }
  107011. else {
  107012. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  107013. }
  107014. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  107015. this._lineShader.bind(this._source.getWorldMatrix());
  107016. // Draw order
  107017. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  107018. this._lineShader.unbind();
  107019. };
  107020. return EdgesRenderer;
  107021. }());
  107022. BABYLON.EdgesRenderer = EdgesRenderer;
  107023. })(BABYLON || (BABYLON = {}));
  107024. //# sourceMappingURL=babylon.edgesRenderer.js.map
  107025. var BABYLON;
  107026. (function (BABYLON) {
  107027. /**
  107028. * FaceAdjacencies Helper class to generate edges
  107029. */
  107030. var FaceAdjacencies = /** @class */ (function () {
  107031. function FaceAdjacencies() {
  107032. this.edges = new Array();
  107033. this.edgesConnectedCount = 0;
  107034. }
  107035. return FaceAdjacencies;
  107036. }());
  107037. /**
  107038. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  107039. */
  107040. var LineEdgesRenderer = /** @class */ (function (_super) {
  107041. __extends(LineEdgesRenderer, _super);
  107042. /**
  107043. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  107044. * @param source LineMesh used to generate edges
  107045. * @param epsilon not important (specified angle for edge detection)
  107046. * @param checkVerticesInsteadOfIndices not important for LineMesh
  107047. */
  107048. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  107049. if (epsilon === void 0) { epsilon = 0.95; }
  107050. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  107051. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  107052. _this._generateEdgesLines();
  107053. return _this;
  107054. }
  107055. /**
  107056. * Always create the edge since its a line so only important things are p0 and p1
  107057. * @param faceIndex not important for LineMesh
  107058. * @param edge not important for LineMesh
  107059. * @param faceNormals not important for LineMesh
  107060. * @param p0 beginnig of line
  107061. * @param p1 end of line
  107062. */
  107063. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  107064. var offset = this._linesPositions.length / 3;
  107065. var normal = p0.subtract(p1);
  107066. normal.normalize();
  107067. // Positions
  107068. this._linesPositions.push(p0.x);
  107069. this._linesPositions.push(p0.y);
  107070. this._linesPositions.push(p0.z);
  107071. this._linesPositions.push(p0.x);
  107072. this._linesPositions.push(p0.y);
  107073. this._linesPositions.push(p0.z);
  107074. this._linesPositions.push(p1.x);
  107075. this._linesPositions.push(p1.y);
  107076. this._linesPositions.push(p1.z);
  107077. this._linesPositions.push(p1.x);
  107078. this._linesPositions.push(p1.y);
  107079. this._linesPositions.push(p1.z);
  107080. // Normals
  107081. this._linesNormals.push(p1.x);
  107082. this._linesNormals.push(p1.y);
  107083. this._linesNormals.push(p1.z);
  107084. this._linesNormals.push(-1);
  107085. this._linesNormals.push(p1.x);
  107086. this._linesNormals.push(p1.y);
  107087. this._linesNormals.push(p1.z);
  107088. this._linesNormals.push(1);
  107089. this._linesNormals.push(p0.x);
  107090. this._linesNormals.push(p0.y);
  107091. this._linesNormals.push(p0.z);
  107092. this._linesNormals.push(-1);
  107093. this._linesNormals.push(p0.x);
  107094. this._linesNormals.push(p0.y);
  107095. this._linesNormals.push(p0.z);
  107096. this._linesNormals.push(1);
  107097. // Indices
  107098. this._linesIndices.push(offset);
  107099. this._linesIndices.push(offset + 1);
  107100. this._linesIndices.push(offset + 2);
  107101. this._linesIndices.push(offset);
  107102. this._linesIndices.push(offset + 2);
  107103. this._linesIndices.push(offset + 3);
  107104. };
  107105. /**
  107106. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  107107. */
  107108. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  107109. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  107110. var indices = this._source.getIndices();
  107111. if (!indices || !positions) {
  107112. return;
  107113. }
  107114. // First let's find adjacencies
  107115. var adjacencies = new Array();
  107116. var faceNormals = new Array();
  107117. var index;
  107118. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  107119. var currentAdjecancy = new FaceAdjacencies();
  107120. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  107121. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  107122. adjacencies.push(currentAdjecancy);
  107123. }
  107124. // Create lines
  107125. for (index = 0; index < adjacencies.length; index++) {
  107126. // 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
  107127. var current = adjacencies[index];
  107128. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  107129. }
  107130. // Merge into a single mesh
  107131. var engine = this._source.getScene().getEngine();
  107132. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  107133. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  107134. this._ib = engine.createIndexBuffer(this._linesIndices);
  107135. this._indicesCount = this._linesIndices.length;
  107136. };
  107137. return LineEdgesRenderer;
  107138. }(BABYLON.EdgesRenderer));
  107139. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  107140. })(BABYLON || (BABYLON = {}));
  107141. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  107142. var BABYLON;
  107143. (function (BABYLON) {
  107144. // Adds the parser to the scene parsers.
  107145. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  107146. if (parsedData.effectLayers) {
  107147. if (!container.effectLayers) {
  107148. container.effectLayers = new Array();
  107149. }
  107150. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  107151. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  107152. container.effectLayers.push(effectLayer);
  107153. }
  107154. }
  107155. });
  107156. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  107157. var index = this.effectLayers.indexOf(toRemove);
  107158. if (index !== -1) {
  107159. this.effectLayers.splice(index, 1);
  107160. }
  107161. return index;
  107162. };
  107163. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  107164. this.effectLayers.push(newEffectLayer);
  107165. };
  107166. /**
  107167. * Defines the layer scene component responsible to manage any effect layers
  107168. * in a given scene.
  107169. */
  107170. var EffectLayerSceneComponent = /** @class */ (function () {
  107171. /**
  107172. * Creates a new instance of the component for the given scene
  107173. * @param scene Defines the scene to register the component in
  107174. */
  107175. function EffectLayerSceneComponent(scene) {
  107176. /**
  107177. * The component name helpfull to identify the component in the list of scene components.
  107178. */
  107179. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  107180. this._renderEffects = false;
  107181. this._needStencil = false;
  107182. this._previousStencilState = false;
  107183. this.scene = scene;
  107184. this._engine = scene.getEngine();
  107185. scene.effectLayers = new Array();
  107186. }
  107187. /**
  107188. * Registers the component in a given scene
  107189. */
  107190. EffectLayerSceneComponent.prototype.register = function () {
  107191. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  107192. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  107193. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  107194. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  107195. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  107196. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  107197. };
  107198. /**
  107199. * Rebuilds the elements related to this component in case of
  107200. * context lost for instance.
  107201. */
  107202. EffectLayerSceneComponent.prototype.rebuild = function () {
  107203. var layers = this.scene.effectLayers;
  107204. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  107205. var effectLayer = layers_1[_i];
  107206. effectLayer._rebuild();
  107207. }
  107208. };
  107209. /**
  107210. * Serializes the component data to the specified json object
  107211. * @param serializationObject The object to serialize to
  107212. */
  107213. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  107214. // Effect layers
  107215. serializationObject.effectLayers = [];
  107216. var layers = this.scene.effectLayers;
  107217. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  107218. var effectLayer = layers_2[_i];
  107219. if (effectLayer.serialize) {
  107220. serializationObject.effectLayers.push(effectLayer.serialize());
  107221. }
  107222. }
  107223. };
  107224. /**
  107225. * Adds all the element from the container to the scene
  107226. * @param container the container holding the elements
  107227. */
  107228. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  107229. var _this = this;
  107230. if (!container.effectLayers) {
  107231. return;
  107232. }
  107233. container.effectLayers.forEach(function (o) {
  107234. _this.scene.addEffectLayer(o);
  107235. });
  107236. };
  107237. /**
  107238. * Removes all the elements in the container from the scene
  107239. * @param container contains the elements to remove
  107240. */
  107241. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  107242. var _this = this;
  107243. if (!container.effectLayers) {
  107244. return;
  107245. }
  107246. container.effectLayers.forEach(function (o) {
  107247. _this.scene.removeEffectLayer(o);
  107248. });
  107249. };
  107250. /**
  107251. * Disposes the component and the associated ressources.
  107252. */
  107253. EffectLayerSceneComponent.prototype.dispose = function () {
  107254. var layers = this.scene.effectLayers;
  107255. while (layers.length) {
  107256. layers[0].dispose();
  107257. }
  107258. };
  107259. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  107260. var layers = this.scene.effectLayers;
  107261. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  107262. var layer = layers_3[_i];
  107263. if (!layer.hasMesh(mesh)) {
  107264. continue;
  107265. }
  107266. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  107267. var subMesh = _b[_a];
  107268. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  107269. return false;
  107270. }
  107271. }
  107272. }
  107273. return true;
  107274. };
  107275. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  107276. this._renderEffects = false;
  107277. this._needStencil = false;
  107278. var layers = this.scene.effectLayers;
  107279. if (layers && layers.length > 0) {
  107280. this._previousStencilState = this._engine.getStencilBuffer();
  107281. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  107282. var effectLayer = layers_4[_i];
  107283. if (effectLayer.shouldRender() &&
  107284. (!effectLayer.camera ||
  107285. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  107286. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  107287. this._renderEffects = true;
  107288. this._needStencil = this._needStencil || effectLayer.needStencil();
  107289. var renderTarget = effectLayer._mainTexture;
  107290. if (renderTarget._shouldRender()) {
  107291. this.scene.incrementRenderId();
  107292. renderTarget.render(false, false);
  107293. }
  107294. }
  107295. }
  107296. this.scene.incrementRenderId();
  107297. }
  107298. };
  107299. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  107300. // Activate effect Layer stencil
  107301. if (this._needStencil) {
  107302. this._engine.setStencilBuffer(true);
  107303. }
  107304. };
  107305. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  107306. // Restore effect Layer stencil
  107307. if (this._needStencil) {
  107308. this._engine.setStencilBuffer(this._previousStencilState);
  107309. }
  107310. };
  107311. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  107312. if (this._renderEffects) {
  107313. this._engine.setDepthBuffer(false);
  107314. var layers = this.scene.effectLayers;
  107315. for (var i = 0; i < layers.length; i++) {
  107316. var effectLayer = layers[i];
  107317. if (effectLayer.renderingGroupId === renderingGroupId) {
  107318. if (effectLayer.shouldRender()) {
  107319. effectLayer.render();
  107320. }
  107321. }
  107322. }
  107323. this._engine.setDepthBuffer(true);
  107324. }
  107325. };
  107326. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  107327. if (this._renderEffects) {
  107328. this._draw(-1);
  107329. }
  107330. };
  107331. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  107332. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  107333. this._draw(index);
  107334. }
  107335. };
  107336. return EffectLayerSceneComponent;
  107337. }());
  107338. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  107339. })(BABYLON || (BABYLON = {}));
  107340. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  107341. var __assign = (this && this.__assign) || function () {
  107342. __assign = Object.assign || function(t) {
  107343. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107344. s = arguments[i];
  107345. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107346. t[p] = s[p];
  107347. }
  107348. return t;
  107349. };
  107350. return __assign.apply(this, arguments);
  107351. };
  107352. var BABYLON;
  107353. (function (BABYLON) {
  107354. /**
  107355. * The effect layer Helps adding post process effect blended with the main pass.
  107356. *
  107357. * This can be for instance use to generate glow or higlight effects on the scene.
  107358. *
  107359. * The effect layer class can not be used directly and is intented to inherited from to be
  107360. * customized per effects.
  107361. */
  107362. var EffectLayer = /** @class */ (function () {
  107363. /**
  107364. * Instantiates a new effect Layer and references it in the scene.
  107365. * @param name The name of the layer
  107366. * @param scene The scene to use the layer in
  107367. */
  107368. function EffectLayer(
  107369. /** The Friendly of the effect in the scene */
  107370. name, scene) {
  107371. this._vertexBuffers = {};
  107372. this._maxSize = 0;
  107373. this._mainTextureDesiredSize = { width: 0, height: 0 };
  107374. this._shouldRender = true;
  107375. this._postProcesses = [];
  107376. this._textures = [];
  107377. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  107378. /**
  107379. * The clear color of the texture used to generate the glow map.
  107380. */
  107381. this.neutralColor = new BABYLON.Color4();
  107382. /**
  107383. * Specifies wether the highlight layer is enabled or not.
  107384. */
  107385. this.isEnabled = true;
  107386. /**
  107387. * An event triggered when the effect layer has been disposed.
  107388. */
  107389. this.onDisposeObservable = new BABYLON.Observable();
  107390. /**
  107391. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  107392. */
  107393. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  107394. /**
  107395. * An event triggered when the generated texture is being merged in the scene.
  107396. */
  107397. this.onBeforeComposeObservable = new BABYLON.Observable();
  107398. /**
  107399. * An event triggered when the generated texture has been merged in the scene.
  107400. */
  107401. this.onAfterComposeObservable = new BABYLON.Observable();
  107402. /**
  107403. * An event triggered when the efffect layer changes its size.
  107404. */
  107405. this.onSizeChangedObservable = new BABYLON.Observable();
  107406. this.name = name;
  107407. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  107408. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  107409. if (!component) {
  107410. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  107411. this._scene._addComponent(component);
  107412. }
  107413. this._engine = this._scene.getEngine();
  107414. this._maxSize = this._engine.getCaps().maxTextureSize;
  107415. this._scene.effectLayers.push(this);
  107416. // Generate Buffers
  107417. this._generateIndexBuffer();
  107418. this._genrateVertexBuffer();
  107419. }
  107420. Object.defineProperty(EffectLayer.prototype, "camera", {
  107421. /**
  107422. * Gets the camera attached to the layer.
  107423. */
  107424. get: function () {
  107425. return this._effectLayerOptions.camera;
  107426. },
  107427. enumerable: true,
  107428. configurable: true
  107429. });
  107430. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  107431. /**
  107432. * Gets the rendering group id the layer should render in.
  107433. */
  107434. get: function () {
  107435. return this._effectLayerOptions.renderingGroupId;
  107436. },
  107437. enumerable: true,
  107438. configurable: true
  107439. });
  107440. /**
  107441. * Initializes the effect layer with the required options.
  107442. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  107443. */
  107444. EffectLayer.prototype._init = function (options) {
  107445. // Adapt options
  107446. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  107447. this._setMainTextureSize();
  107448. this._createMainTexture();
  107449. this._createTextureAndPostProcesses();
  107450. this._mergeEffect = this._createMergeEffect();
  107451. };
  107452. /**
  107453. * Generates the index buffer of the full screen quad blending to the main canvas.
  107454. */
  107455. EffectLayer.prototype._generateIndexBuffer = function () {
  107456. // Indices
  107457. var indices = [];
  107458. indices.push(0);
  107459. indices.push(1);
  107460. indices.push(2);
  107461. indices.push(0);
  107462. indices.push(2);
  107463. indices.push(3);
  107464. this._indexBuffer = this._engine.createIndexBuffer(indices);
  107465. };
  107466. /**
  107467. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  107468. */
  107469. EffectLayer.prototype._genrateVertexBuffer = function () {
  107470. // VBO
  107471. var vertices = [];
  107472. vertices.push(1, 1);
  107473. vertices.push(-1, 1);
  107474. vertices.push(-1, -1);
  107475. vertices.push(1, -1);
  107476. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  107477. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  107478. };
  107479. /**
  107480. * Sets the main texture desired size which is the closest power of two
  107481. * of the engine canvas size.
  107482. */
  107483. EffectLayer.prototype._setMainTextureSize = function () {
  107484. if (this._effectLayerOptions.mainTextureFixedSize) {
  107485. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  107486. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  107487. }
  107488. else {
  107489. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  107490. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  107491. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  107492. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  107493. }
  107494. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  107495. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  107496. };
  107497. /**
  107498. * Creates the main texture for the effect layer.
  107499. */
  107500. EffectLayer.prototype._createMainTexture = function () {
  107501. var _this = this;
  107502. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  107503. width: this._mainTextureDesiredSize.width,
  107504. height: this._mainTextureDesiredSize.height
  107505. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  107506. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  107507. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107508. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107509. this._mainTexture.anisotropicFilteringLevel = 1;
  107510. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  107511. this._mainTexture.renderParticles = false;
  107512. this._mainTexture.renderList = null;
  107513. this._mainTexture.ignoreCameraViewport = true;
  107514. // Custom render function
  107515. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  107516. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  107517. var index;
  107518. var engine = _this._scene.getEngine();
  107519. if (depthOnlySubMeshes.length) {
  107520. engine.setColorWrite(false);
  107521. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  107522. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  107523. }
  107524. engine.setColorWrite(true);
  107525. }
  107526. for (index = 0; index < opaqueSubMeshes.length; index++) {
  107527. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  107528. }
  107529. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  107530. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  107531. }
  107532. for (index = 0; index < transparentSubMeshes.length; index++) {
  107533. _this._renderSubMesh(transparentSubMeshes.data[index]);
  107534. }
  107535. };
  107536. this._mainTexture.onClearObservable.add(function (engine) {
  107537. engine.clear(_this.neutralColor, true, true, true);
  107538. });
  107539. };
  107540. /**
  107541. * Checks for the readiness of the element composing the layer.
  107542. * @param subMesh the mesh to check for
  107543. * @param useInstances specify wether or not to use instances to render the mesh
  107544. * @param emissiveTexture the associated emissive texture used to generate the glow
  107545. * @return true if ready otherwise, false
  107546. */
  107547. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  107548. var material = subMesh.getMaterial();
  107549. if (!material) {
  107550. return false;
  107551. }
  107552. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  107553. return false;
  107554. }
  107555. var defines = [];
  107556. var attribs = [BABYLON.VertexBuffer.PositionKind];
  107557. var mesh = subMesh.getMesh();
  107558. var uv1 = false;
  107559. var uv2 = false;
  107560. // Alpha test
  107561. if (material && material.needAlphaTesting()) {
  107562. var alphaTexture = material.getAlphaTestTexture();
  107563. if (alphaTexture) {
  107564. defines.push("#define ALPHATEST");
  107565. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  107566. alphaTexture.coordinatesIndex === 1) {
  107567. defines.push("#define DIFFUSEUV2");
  107568. uv2 = true;
  107569. }
  107570. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  107571. defines.push("#define DIFFUSEUV1");
  107572. uv1 = true;
  107573. }
  107574. }
  107575. }
  107576. // Emissive
  107577. if (emissiveTexture) {
  107578. defines.push("#define EMISSIVE");
  107579. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  107580. emissiveTexture.coordinatesIndex === 1) {
  107581. defines.push("#define EMISSIVEUV2");
  107582. uv2 = true;
  107583. }
  107584. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  107585. defines.push("#define EMISSIVEUV1");
  107586. uv1 = true;
  107587. }
  107588. }
  107589. if (uv1) {
  107590. attribs.push(BABYLON.VertexBuffer.UVKind);
  107591. defines.push("#define UV1");
  107592. }
  107593. if (uv2) {
  107594. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  107595. defines.push("#define UV2");
  107596. }
  107597. // Bones
  107598. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  107599. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  107600. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  107601. if (mesh.numBoneInfluencers > 4) {
  107602. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  107603. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  107604. }
  107605. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  107606. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  107607. }
  107608. else {
  107609. defines.push("#define NUM_BONE_INFLUENCERS 0");
  107610. }
  107611. // Morph targets
  107612. var manager = mesh.morphTargetManager;
  107613. var morphInfluencers = 0;
  107614. if (manager) {
  107615. if (manager.numInfluencers > 0) {
  107616. defines.push("#define MORPHTARGETS");
  107617. morphInfluencers = manager.numInfluencers;
  107618. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  107619. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  107620. }
  107621. }
  107622. // Instances
  107623. if (useInstances) {
  107624. defines.push("#define INSTANCES");
  107625. attribs.push("world0");
  107626. attribs.push("world1");
  107627. attribs.push("world2");
  107628. attribs.push("world3");
  107629. }
  107630. // Get correct effect
  107631. var join = defines.join("\n");
  107632. if (this._cachedDefines !== join) {
  107633. this._cachedDefines = join;
  107634. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  107635. }
  107636. return this._effectLayerMapGenerationEffect.isReady();
  107637. };
  107638. /**
  107639. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  107640. */
  107641. EffectLayer.prototype.render = function () {
  107642. var currentEffect = this._mergeEffect;
  107643. // Check
  107644. if (!currentEffect.isReady())
  107645. return;
  107646. for (var i = 0; i < this._postProcesses.length; i++) {
  107647. if (!this._postProcesses[i].isReady()) {
  107648. return;
  107649. }
  107650. }
  107651. var engine = this._scene.getEngine();
  107652. this.onBeforeComposeObservable.notifyObservers(this);
  107653. // Render
  107654. engine.enableEffect(currentEffect);
  107655. engine.setState(false);
  107656. // VBOs
  107657. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  107658. // Cache
  107659. var previousAlphaMode = engine.getAlphaMode();
  107660. // Go Blend.
  107661. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  107662. // Blends the map on the main canvas.
  107663. this._internalRender(currentEffect);
  107664. // Restore Alpha
  107665. engine.setAlphaMode(previousAlphaMode);
  107666. this.onAfterComposeObservable.notifyObservers(this);
  107667. // Handle size changes.
  107668. var size = this._mainTexture.getSize();
  107669. this._setMainTextureSize();
  107670. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  107671. // Recreate RTT and post processes on size change.
  107672. this.onSizeChangedObservable.notifyObservers(this);
  107673. this._disposeTextureAndPostProcesses();
  107674. this._createMainTexture();
  107675. this._createTextureAndPostProcesses();
  107676. }
  107677. };
  107678. /**
  107679. * Determine if a given mesh will be used in the current effect.
  107680. * @param mesh mesh to test
  107681. * @returns true if the mesh will be used
  107682. */
  107683. EffectLayer.prototype.hasMesh = function (mesh) {
  107684. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  107685. return true;
  107686. }
  107687. return false;
  107688. };
  107689. /**
  107690. * Returns true if the layer contains information to display, otherwise false.
  107691. * @returns true if the glow layer should be rendered
  107692. */
  107693. EffectLayer.prototype.shouldRender = function () {
  107694. return this.isEnabled && this._shouldRender;
  107695. };
  107696. /**
  107697. * Returns true if the mesh should render, otherwise false.
  107698. * @param mesh The mesh to render
  107699. * @returns true if it should render otherwise false
  107700. */
  107701. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  107702. return true;
  107703. };
  107704. /**
  107705. * Returns true if the mesh should render, otherwise false.
  107706. * @param mesh The mesh to render
  107707. * @returns true if it should render otherwise false
  107708. */
  107709. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  107710. return true;
  107711. };
  107712. /**
  107713. * Renders the submesh passed in parameter to the generation map.
  107714. */
  107715. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  107716. var _this = this;
  107717. if (!this.shouldRender()) {
  107718. return;
  107719. }
  107720. var material = subMesh.getMaterial();
  107721. var mesh = subMesh.getRenderingMesh();
  107722. var scene = this._scene;
  107723. var engine = scene.getEngine();
  107724. if (!material) {
  107725. return;
  107726. }
  107727. // Do not block in blend mode.
  107728. if (material.needAlphaBlendingForMesh(mesh)) {
  107729. return;
  107730. }
  107731. // Culling
  107732. engine.setState(material.backFaceCulling);
  107733. // Managing instances
  107734. var batch = mesh._getInstancesRenderList(subMesh._id);
  107735. if (batch.mustReturn) {
  107736. return;
  107737. }
  107738. // Early Exit per mesh
  107739. if (!this._shouldRenderMesh(mesh)) {
  107740. return;
  107741. }
  107742. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  107743. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  107744. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  107745. engine.enableEffect(this._effectLayerMapGenerationEffect);
  107746. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  107747. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  107748. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  107749. // Alpha test
  107750. if (material && material.needAlphaTesting()) {
  107751. var alphaTexture = material.getAlphaTestTexture();
  107752. if (alphaTexture) {
  107753. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  107754. var textureMatrix = alphaTexture.getTextureMatrix();
  107755. if (textureMatrix) {
  107756. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  107757. }
  107758. }
  107759. }
  107760. // Glow emissive only
  107761. if (this._emissiveTextureAndColor.texture) {
  107762. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  107763. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  107764. }
  107765. // Bones
  107766. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  107767. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  107768. }
  107769. // Morph targets
  107770. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  107771. // Draw
  107772. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  107773. }
  107774. else {
  107775. // Need to reset refresh rate of the main map
  107776. this._mainTexture.resetRefreshCounter();
  107777. }
  107778. };
  107779. /**
  107780. * Rebuild the required buffers.
  107781. * @hidden Internal use only.
  107782. */
  107783. EffectLayer.prototype._rebuild = function () {
  107784. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  107785. if (vb) {
  107786. vb._rebuild();
  107787. }
  107788. this._generateIndexBuffer();
  107789. };
  107790. /**
  107791. * Dispose only the render target textures and post process.
  107792. */
  107793. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  107794. this._mainTexture.dispose();
  107795. for (var i = 0; i < this._postProcesses.length; i++) {
  107796. if (this._postProcesses[i]) {
  107797. this._postProcesses[i].dispose();
  107798. }
  107799. }
  107800. this._postProcesses = [];
  107801. for (var i = 0; i < this._textures.length; i++) {
  107802. if (this._textures[i]) {
  107803. this._textures[i].dispose();
  107804. }
  107805. }
  107806. this._textures = [];
  107807. };
  107808. /**
  107809. * Dispose the highlight layer and free resources.
  107810. */
  107811. EffectLayer.prototype.dispose = function () {
  107812. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  107813. if (vertexBuffer) {
  107814. vertexBuffer.dispose();
  107815. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  107816. }
  107817. if (this._indexBuffer) {
  107818. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  107819. this._indexBuffer = null;
  107820. }
  107821. // Clean textures and post processes
  107822. this._disposeTextureAndPostProcesses();
  107823. // Remove from scene
  107824. var index = this._scene.effectLayers.indexOf(this, 0);
  107825. if (index > -1) {
  107826. this._scene.effectLayers.splice(index, 1);
  107827. }
  107828. // Callback
  107829. this.onDisposeObservable.notifyObservers(this);
  107830. this.onDisposeObservable.clear();
  107831. this.onBeforeRenderMainTextureObservable.clear();
  107832. this.onBeforeComposeObservable.clear();
  107833. this.onAfterComposeObservable.clear();
  107834. this.onSizeChangedObservable.clear();
  107835. };
  107836. /**
  107837. * Gets the class name of the effect layer
  107838. * @returns the string with the class name of the effect layer
  107839. */
  107840. EffectLayer.prototype.getClassName = function () {
  107841. return "EffectLayer";
  107842. };
  107843. /**
  107844. * Creates an effect layer from parsed effect layer data
  107845. * @param parsedEffectLayer defines effect layer data
  107846. * @param scene defines the current scene
  107847. * @param rootUrl defines the root URL containing the effect layer information
  107848. * @returns a parsed effect Layer
  107849. */
  107850. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  107851. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  107852. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  107853. };
  107854. __decorate([
  107855. BABYLON.serialize()
  107856. ], EffectLayer.prototype, "name", void 0);
  107857. __decorate([
  107858. BABYLON.serializeAsColor4()
  107859. ], EffectLayer.prototype, "neutralColor", void 0);
  107860. __decorate([
  107861. BABYLON.serialize()
  107862. ], EffectLayer.prototype, "isEnabled", void 0);
  107863. __decorate([
  107864. BABYLON.serializeAsCameraReference()
  107865. ], EffectLayer.prototype, "camera", null);
  107866. __decorate([
  107867. BABYLON.serialize()
  107868. ], EffectLayer.prototype, "renderingGroupId", null);
  107869. return EffectLayer;
  107870. }());
  107871. BABYLON.EffectLayer = EffectLayer;
  107872. })(BABYLON || (BABYLON = {}));
  107873. //# sourceMappingURL=babylon.effectLayer.js.map
  107874. var BABYLON;
  107875. (function (BABYLON) {
  107876. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  107877. for (var index = 0; index < this.effectLayers.length; index++) {
  107878. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  107879. return this.effectLayers[index];
  107880. }
  107881. }
  107882. return null;
  107883. };
  107884. /**
  107885. * Special Glow Blur post process only blurring the alpha channel
  107886. * It enforces keeping the most luminous color in the color channel.
  107887. */
  107888. var GlowBlurPostProcess = /** @class */ (function (_super) {
  107889. __extends(GlowBlurPostProcess, _super);
  107890. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  107891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  107892. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  107893. _this.direction = direction;
  107894. _this.kernel = kernel;
  107895. _this.onApplyObservable.add(function (effect) {
  107896. effect.setFloat2("screenSize", _this.width, _this.height);
  107897. effect.setVector2("direction", _this.direction);
  107898. effect.setFloat("blurWidth", _this.kernel);
  107899. });
  107900. return _this;
  107901. }
  107902. return GlowBlurPostProcess;
  107903. }(BABYLON.PostProcess));
  107904. /**
  107905. * The highlight layer Helps adding a glow effect around a mesh.
  107906. *
  107907. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  107908. * glowy meshes to your scene.
  107909. *
  107910. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  107911. */
  107912. var HighlightLayer = /** @class */ (function (_super) {
  107913. __extends(HighlightLayer, _super);
  107914. /**
  107915. * Instantiates a new highlight Layer and references it to the scene..
  107916. * @param name The name of the layer
  107917. * @param scene The scene to use the layer in
  107918. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  107919. */
  107920. function HighlightLayer(name, scene, options) {
  107921. var _this = _super.call(this, name, scene) || this;
  107922. _this.name = name;
  107923. /**
  107924. * Specifies whether or not the inner glow is ACTIVE in the layer.
  107925. */
  107926. _this.innerGlow = true;
  107927. /**
  107928. * Specifies whether or not the outer glow is ACTIVE in the layer.
  107929. */
  107930. _this.outerGlow = true;
  107931. /**
  107932. * An event triggered when the highlight layer is being blurred.
  107933. */
  107934. _this.onBeforeBlurObservable = new BABYLON.Observable();
  107935. /**
  107936. * An event triggered when the highlight layer has been blurred.
  107937. */
  107938. _this.onAfterBlurObservable = new BABYLON.Observable();
  107939. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  107940. _this._meshes = {};
  107941. _this._excludedMeshes = {};
  107942. _this.neutralColor = HighlightLayer.NeutralColor;
  107943. // Warn on stencil
  107944. if (!_this._engine.isStencilEnable) {
  107945. 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 }");
  107946. }
  107947. // Adapt options
  107948. _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);
  107949. // Initialize the layer
  107950. _this._init({
  107951. alphaBlendingMode: _this._options.alphaBlendingMode,
  107952. camera: _this._options.camera,
  107953. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  107954. mainTextureRatio: _this._options.mainTextureRatio,
  107955. renderingGroupId: _this._options.renderingGroupId
  107956. });
  107957. // Do not render as long as no meshes have been added
  107958. _this._shouldRender = false;
  107959. return _this;
  107960. }
  107961. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  107962. /**
  107963. * Gets the horizontal size of the blur.
  107964. */
  107965. get: function () {
  107966. return this._horizontalBlurPostprocess.kernel;
  107967. },
  107968. /**
  107969. * Specifies the horizontal size of the blur.
  107970. */
  107971. set: function (value) {
  107972. this._horizontalBlurPostprocess.kernel = value;
  107973. },
  107974. enumerable: true,
  107975. configurable: true
  107976. });
  107977. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  107978. /**
  107979. * Gets the vertical size of the blur.
  107980. */
  107981. get: function () {
  107982. return this._verticalBlurPostprocess.kernel;
  107983. },
  107984. /**
  107985. * Specifies the vertical size of the blur.
  107986. */
  107987. set: function (value) {
  107988. this._verticalBlurPostprocess.kernel = value;
  107989. },
  107990. enumerable: true,
  107991. configurable: true
  107992. });
  107993. /**
  107994. * Get the effect name of the layer.
  107995. * @return The effect name
  107996. */
  107997. HighlightLayer.prototype.getEffectName = function () {
  107998. return HighlightLayer.EffectName;
  107999. };
  108000. /**
  108001. * Create the merge effect. This is the shader use to blit the information back
  108002. * to the main canvas at the end of the scene rendering.
  108003. */
  108004. HighlightLayer.prototype._createMergeEffect = function () {
  108005. // Effect
  108006. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  108007. };
  108008. /**
  108009. * Creates the render target textures and post processes used in the highlight layer.
  108010. */
  108011. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  108012. var _this = this;
  108013. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  108014. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  108015. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  108016. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  108017. var textureType = 0;
  108018. if (this._engine.getCaps().textureHalfFloatRender) {
  108019. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  108020. }
  108021. else {
  108022. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  108023. }
  108024. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  108025. width: blurTextureWidth,
  108026. height: blurTextureHeight
  108027. }, this._scene, false, true, textureType);
  108028. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108029. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108030. this._blurTexture.anisotropicFilteringLevel = 16;
  108031. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  108032. this._blurTexture.renderParticles = false;
  108033. this._blurTexture.ignoreCameraViewport = true;
  108034. this._textures = [this._blurTexture];
  108035. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  108036. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  108037. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  108038. effect.setTexture("textureSampler", _this._mainTexture);
  108039. });
  108040. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  108041. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  108042. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  108043. });
  108044. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  108045. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  108046. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  108047. });
  108048. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  108049. }
  108050. else {
  108051. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  108052. width: blurTextureWidth,
  108053. height: blurTextureHeight
  108054. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108055. this._horizontalBlurPostprocess.width = blurTextureWidth;
  108056. this._horizontalBlurPostprocess.height = blurTextureHeight;
  108057. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  108058. effect.setTexture("textureSampler", _this._mainTexture);
  108059. });
  108060. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  108061. width: blurTextureWidth,
  108062. height: blurTextureHeight
  108063. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108064. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  108065. }
  108066. this._mainTexture.onAfterUnbindObservable.add(function () {
  108067. _this.onBeforeBlurObservable.notifyObservers(_this);
  108068. var internalTexture = _this._blurTexture.getInternalTexture();
  108069. if (internalTexture) {
  108070. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  108071. }
  108072. _this.onAfterBlurObservable.notifyObservers(_this);
  108073. });
  108074. // Prevent autoClear.
  108075. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  108076. };
  108077. /**
  108078. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  108079. */
  108080. HighlightLayer.prototype.needStencil = function () {
  108081. return true;
  108082. };
  108083. /**
  108084. * Checks for the readiness of the element composing the layer.
  108085. * @param subMesh the mesh to check for
  108086. * @param useInstances specify wether or not to use instances to render the mesh
  108087. * @param emissiveTexture the associated emissive texture used to generate the glow
  108088. * @return true if ready otherwise, false
  108089. */
  108090. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  108091. var material = subMesh.getMaterial();
  108092. var mesh = subMesh.getRenderingMesh();
  108093. if (!material || !mesh || !this._meshes) {
  108094. return false;
  108095. }
  108096. var emissiveTexture = null;
  108097. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  108098. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  108099. emissiveTexture = material.emissiveTexture;
  108100. }
  108101. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  108102. };
  108103. /**
  108104. * Implementation specific of rendering the generating effect on the main canvas.
  108105. * @param effect The effect used to render through
  108106. */
  108107. HighlightLayer.prototype._internalRender = function (effect) {
  108108. // Texture
  108109. effect.setTexture("textureSampler", this._blurTexture);
  108110. // Cache
  108111. var engine = this._engine;
  108112. var previousStencilBuffer = engine.getStencilBuffer();
  108113. var previousStencilFunction = engine.getStencilFunction();
  108114. var previousStencilMask = engine.getStencilMask();
  108115. var previousStencilOperationPass = engine.getStencilOperationPass();
  108116. var previousStencilOperationFail = engine.getStencilOperationFail();
  108117. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  108118. var previousStencilReference = engine.getStencilFunctionReference();
  108119. // Stencil operations
  108120. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  108121. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  108122. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  108123. // Draw order
  108124. engine.setStencilMask(0x00);
  108125. engine.setStencilBuffer(true);
  108126. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  108127. // 2 passes inner outer
  108128. if (this.outerGlow) {
  108129. effect.setFloat("offset", 0);
  108130. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  108131. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108132. }
  108133. if (this.innerGlow) {
  108134. effect.setFloat("offset", 1);
  108135. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  108136. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108137. }
  108138. // Restore Cache
  108139. engine.setStencilFunction(previousStencilFunction);
  108140. engine.setStencilMask(previousStencilMask);
  108141. engine.setStencilBuffer(previousStencilBuffer);
  108142. engine.setStencilOperationPass(previousStencilOperationPass);
  108143. engine.setStencilOperationFail(previousStencilOperationFail);
  108144. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  108145. engine.setStencilFunctionReference(previousStencilReference);
  108146. };
  108147. /**
  108148. * Returns true if the layer contains information to display, otherwise false.
  108149. */
  108150. HighlightLayer.prototype.shouldRender = function () {
  108151. if (_super.prototype.shouldRender.call(this)) {
  108152. return this._meshes ? true : false;
  108153. }
  108154. return false;
  108155. };
  108156. /**
  108157. * Returns true if the mesh should render, otherwise false.
  108158. * @param mesh The mesh to render
  108159. * @returns true if it should render otherwise false
  108160. */
  108161. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  108162. // Excluded Mesh
  108163. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  108164. return false;
  108165. }
  108166. ;
  108167. if (!_super.prototype.hasMesh.call(this, mesh)) {
  108168. return false;
  108169. }
  108170. return true;
  108171. };
  108172. /**
  108173. * Sets the required values for both the emissive texture and and the main color.
  108174. */
  108175. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  108176. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  108177. if (highlightLayerMesh) {
  108178. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  108179. }
  108180. else {
  108181. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  108182. }
  108183. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  108184. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  108185. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  108186. }
  108187. else {
  108188. this._emissiveTextureAndColor.texture = null;
  108189. }
  108190. };
  108191. /**
  108192. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  108193. * @param mesh The mesh to exclude from the highlight layer
  108194. */
  108195. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  108196. if (!this._excludedMeshes) {
  108197. return;
  108198. }
  108199. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  108200. if (!meshExcluded) {
  108201. this._excludedMeshes[mesh.uniqueId] = {
  108202. mesh: mesh,
  108203. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  108204. mesh.getEngine().setStencilBuffer(false);
  108205. }),
  108206. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  108207. mesh.getEngine().setStencilBuffer(true);
  108208. }),
  108209. };
  108210. }
  108211. };
  108212. /**
  108213. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  108214. * @param mesh The mesh to highlight
  108215. */
  108216. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  108217. if (!this._excludedMeshes) {
  108218. return;
  108219. }
  108220. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  108221. if (meshExcluded) {
  108222. if (meshExcluded.beforeRender) {
  108223. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  108224. }
  108225. if (meshExcluded.afterRender) {
  108226. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  108227. }
  108228. }
  108229. this._excludedMeshes[mesh.uniqueId] = null;
  108230. };
  108231. /**
  108232. * Determine if a given mesh will be highlighted by the current HighlightLayer
  108233. * @param mesh mesh to test
  108234. * @returns true if the mesh will be highlighted by the current HighlightLayer
  108235. */
  108236. HighlightLayer.prototype.hasMesh = function (mesh) {
  108237. if (!this._meshes) {
  108238. return false;
  108239. }
  108240. if (!_super.prototype.hasMesh.call(this, mesh)) {
  108241. return false;
  108242. }
  108243. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  108244. };
  108245. /**
  108246. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  108247. * @param mesh The mesh to highlight
  108248. * @param color The color of the highlight
  108249. * @param glowEmissiveOnly Extract the glow from the emissive texture
  108250. */
  108251. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  108252. var _this = this;
  108253. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  108254. if (!this._meshes) {
  108255. return;
  108256. }
  108257. var meshHighlight = this._meshes[mesh.uniqueId];
  108258. if (meshHighlight) {
  108259. meshHighlight.color = color;
  108260. }
  108261. else {
  108262. this._meshes[mesh.uniqueId] = {
  108263. mesh: mesh,
  108264. color: color,
  108265. // Lambda required for capture due to Observable this context
  108266. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  108267. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  108268. _this._defaultStencilReference(mesh);
  108269. }
  108270. else {
  108271. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  108272. }
  108273. }),
  108274. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  108275. glowEmissiveOnly: glowEmissiveOnly
  108276. };
  108277. mesh.onDisposeObservable.add(function () {
  108278. _this._disposeMesh(mesh);
  108279. });
  108280. }
  108281. this._shouldRender = true;
  108282. };
  108283. /**
  108284. * Remove a mesh from the highlight layer in order to make it stop glowing.
  108285. * @param mesh The mesh to highlight
  108286. */
  108287. HighlightLayer.prototype.removeMesh = function (mesh) {
  108288. if (!this._meshes) {
  108289. return;
  108290. }
  108291. var meshHighlight = this._meshes[mesh.uniqueId];
  108292. if (meshHighlight) {
  108293. if (meshHighlight.observerHighlight) {
  108294. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  108295. }
  108296. if (meshHighlight.observerDefault) {
  108297. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  108298. }
  108299. delete this._meshes[mesh.uniqueId];
  108300. }
  108301. this._shouldRender = false;
  108302. for (var meshHighlightToCheck in this._meshes) {
  108303. if (this._meshes[meshHighlightToCheck]) {
  108304. this._shouldRender = true;
  108305. break;
  108306. }
  108307. }
  108308. };
  108309. /**
  108310. * Force the stencil to the normal expected value for none glowing parts
  108311. */
  108312. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  108313. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  108314. };
  108315. /**
  108316. * Free any resources and references associated to a mesh.
  108317. * Internal use
  108318. * @param mesh The mesh to free.
  108319. * @hidden
  108320. */
  108321. HighlightLayer.prototype._disposeMesh = function (mesh) {
  108322. this.removeMesh(mesh);
  108323. this.removeExcludedMesh(mesh);
  108324. };
  108325. /**
  108326. * Dispose the highlight layer and free resources.
  108327. */
  108328. HighlightLayer.prototype.dispose = function () {
  108329. if (this._meshes) {
  108330. // Clean mesh references
  108331. for (var id in this._meshes) {
  108332. var meshHighlight = this._meshes[id];
  108333. if (meshHighlight && meshHighlight.mesh) {
  108334. if (meshHighlight.observerHighlight) {
  108335. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  108336. }
  108337. if (meshHighlight.observerDefault) {
  108338. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  108339. }
  108340. }
  108341. }
  108342. this._meshes = null;
  108343. }
  108344. if (this._excludedMeshes) {
  108345. for (var id in this._excludedMeshes) {
  108346. var meshHighlight = this._excludedMeshes[id];
  108347. if (meshHighlight) {
  108348. if (meshHighlight.beforeRender) {
  108349. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  108350. }
  108351. if (meshHighlight.afterRender) {
  108352. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  108353. }
  108354. }
  108355. }
  108356. this._excludedMeshes = null;
  108357. }
  108358. _super.prototype.dispose.call(this);
  108359. };
  108360. /**
  108361. * Gets the class name of the effect layer
  108362. * @returns the string with the class name of the effect layer
  108363. */
  108364. HighlightLayer.prototype.getClassName = function () {
  108365. return "HighlightLayer";
  108366. };
  108367. /**
  108368. * Serializes this Highlight layer
  108369. * @returns a serialized Highlight layer object
  108370. */
  108371. HighlightLayer.prototype.serialize = function () {
  108372. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108373. serializationObject.customType = "BABYLON.HighlightLayer";
  108374. // Highlighted meshes
  108375. serializationObject.meshes = [];
  108376. if (this._meshes) {
  108377. for (var m in this._meshes) {
  108378. var mesh = this._meshes[m];
  108379. if (mesh) {
  108380. serializationObject.meshes.push({
  108381. glowEmissiveOnly: mesh.glowEmissiveOnly,
  108382. color: mesh.color.asArray(),
  108383. meshId: mesh.mesh.id
  108384. });
  108385. }
  108386. }
  108387. }
  108388. // Excluded meshes
  108389. serializationObject.excludedMeshes = [];
  108390. if (this._excludedMeshes) {
  108391. for (var e in this._excludedMeshes) {
  108392. var excludedMesh = this._excludedMeshes[e];
  108393. if (excludedMesh) {
  108394. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  108395. }
  108396. }
  108397. }
  108398. return serializationObject;
  108399. };
  108400. /**
  108401. * Creates a Highlight layer from parsed Highlight layer data
  108402. * @param parsedHightlightLayer defines the Highlight layer data
  108403. * @param scene defines the current scene
  108404. * @param rootUrl defines the root URL containing the Highlight layer information
  108405. * @returns a parsed Highlight layer
  108406. */
  108407. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  108408. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  108409. var index;
  108410. // Excluded meshes
  108411. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  108412. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  108413. if (mesh) {
  108414. hl.addExcludedMesh(mesh);
  108415. }
  108416. }
  108417. // Included meshes
  108418. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  108419. var highlightedMesh = parsedHightlightLayer.meshes[index];
  108420. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  108421. if (mesh) {
  108422. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  108423. }
  108424. }
  108425. return hl;
  108426. };
  108427. /**
  108428. * Effect Name of the highlight layer.
  108429. */
  108430. HighlightLayer.EffectName = "HighlightLayer";
  108431. /**
  108432. * The neutral color used during the preparation of the glow effect.
  108433. * This is black by default as the blend operation is a blend operation.
  108434. */
  108435. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  108436. /**
  108437. * Stencil value used for glowing meshes.
  108438. */
  108439. HighlightLayer.GlowingMeshStencilReference = 0x02;
  108440. /**
  108441. * Stencil value used for the other meshes in the scene.
  108442. */
  108443. HighlightLayer.NormalMeshStencilReference = 0x01;
  108444. __decorate([
  108445. BABYLON.serialize()
  108446. ], HighlightLayer.prototype, "innerGlow", void 0);
  108447. __decorate([
  108448. BABYLON.serialize()
  108449. ], HighlightLayer.prototype, "outerGlow", void 0);
  108450. __decorate([
  108451. BABYLON.serialize()
  108452. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  108453. __decorate([
  108454. BABYLON.serialize()
  108455. ], HighlightLayer.prototype, "blurVerticalSize", null);
  108456. __decorate([
  108457. BABYLON.serialize("options")
  108458. ], HighlightLayer.prototype, "_options", void 0);
  108459. return HighlightLayer;
  108460. }(BABYLON.EffectLayer));
  108461. BABYLON.HighlightLayer = HighlightLayer;
  108462. })(BABYLON || (BABYLON = {}));
  108463. //# sourceMappingURL=babylon.highlightLayer.js.map
  108464. var BABYLON;
  108465. (function (BABYLON) {
  108466. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  108467. for (var index = 0; index < this.effectLayers.length; index++) {
  108468. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  108469. return this.effectLayers[index];
  108470. }
  108471. }
  108472. return null;
  108473. };
  108474. /**
  108475. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  108476. *
  108477. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  108478. * glowy meshes to your scene.
  108479. *
  108480. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  108481. */
  108482. var GlowLayer = /** @class */ (function (_super) {
  108483. __extends(GlowLayer, _super);
  108484. /**
  108485. * Instantiates a new glow Layer and references it to the scene.
  108486. * @param name The name of the layer
  108487. * @param scene The scene to use the layer in
  108488. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  108489. */
  108490. function GlowLayer(name, scene, options) {
  108491. var _this = _super.call(this, name, scene) || this;
  108492. _this._intensity = 1.0;
  108493. _this._includedOnlyMeshes = [];
  108494. _this._excludedMeshes = [];
  108495. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  108496. // Adapt options
  108497. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  108498. // Initialize the layer
  108499. _this._init({
  108500. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  108501. camera: _this._options.camera,
  108502. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  108503. mainTextureRatio: _this._options.mainTextureRatio,
  108504. renderingGroupId: _this._options.renderingGroupId
  108505. });
  108506. return _this;
  108507. }
  108508. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  108509. /**
  108510. * Gets the kernel size of the blur.
  108511. */
  108512. get: function () {
  108513. return this._horizontalBlurPostprocess1.kernel;
  108514. },
  108515. /**
  108516. * Sets the kernel size of the blur.
  108517. */
  108518. set: function (value) {
  108519. this._horizontalBlurPostprocess1.kernel = value;
  108520. this._verticalBlurPostprocess1.kernel = value;
  108521. this._horizontalBlurPostprocess2.kernel = value;
  108522. this._verticalBlurPostprocess2.kernel = value;
  108523. },
  108524. enumerable: true,
  108525. configurable: true
  108526. });
  108527. Object.defineProperty(GlowLayer.prototype, "intensity", {
  108528. /**
  108529. * Gets the glow intensity.
  108530. */
  108531. get: function () {
  108532. return this._intensity;
  108533. },
  108534. /**
  108535. * Sets the glow intensity.
  108536. */
  108537. set: function (value) {
  108538. this._intensity = value;
  108539. },
  108540. enumerable: true,
  108541. configurable: true
  108542. });
  108543. /**
  108544. * Get the effect name of the layer.
  108545. * @return The effect name
  108546. */
  108547. GlowLayer.prototype.getEffectName = function () {
  108548. return GlowLayer.EffectName;
  108549. };
  108550. /**
  108551. * Create the merge effect. This is the shader use to blit the information back
  108552. * to the main canvas at the end of the scene rendering.
  108553. */
  108554. GlowLayer.prototype._createMergeEffect = function () {
  108555. // Effect
  108556. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  108557. };
  108558. /**
  108559. * Creates the render target textures and post processes used in the glow layer.
  108560. */
  108561. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  108562. var _this = this;
  108563. var blurTextureWidth = this._mainTextureDesiredSize.width;
  108564. var blurTextureHeight = this._mainTextureDesiredSize.height;
  108565. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  108566. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  108567. var textureType = 0;
  108568. if (this._engine.getCaps().textureHalfFloatRender) {
  108569. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  108570. }
  108571. else {
  108572. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  108573. }
  108574. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  108575. width: blurTextureWidth,
  108576. height: blurTextureHeight
  108577. }, this._scene, false, true, textureType);
  108578. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108579. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108580. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108581. this._blurTexture1.renderParticles = false;
  108582. this._blurTexture1.ignoreCameraViewport = true;
  108583. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  108584. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  108585. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  108586. width: blurTextureWidth2,
  108587. height: blurTextureHeight2
  108588. }, this._scene, false, true, textureType);
  108589. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108590. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108591. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108592. this._blurTexture2.renderParticles = false;
  108593. this._blurTexture2.ignoreCameraViewport = true;
  108594. this._textures = [this._blurTexture1, this._blurTexture2];
  108595. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  108596. width: blurTextureWidth,
  108597. height: blurTextureHeight
  108598. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108599. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  108600. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  108601. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  108602. effect.setTexture("textureSampler", _this._mainTexture);
  108603. });
  108604. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  108605. width: blurTextureWidth,
  108606. height: blurTextureHeight
  108607. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108608. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  108609. width: blurTextureWidth2,
  108610. height: blurTextureHeight2
  108611. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108612. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  108613. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  108614. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  108615. effect.setTexture("textureSampler", _this._blurTexture1);
  108616. });
  108617. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  108618. width: blurTextureWidth2,
  108619. height: blurTextureHeight2
  108620. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108621. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  108622. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  108623. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  108624. this._mainTexture.samples = this._options.mainTextureSamples;
  108625. this._mainTexture.onAfterUnbindObservable.add(function () {
  108626. var internalTexture = _this._blurTexture1.getInternalTexture();
  108627. if (internalTexture) {
  108628. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  108629. internalTexture = _this._blurTexture2.getInternalTexture();
  108630. if (internalTexture) {
  108631. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  108632. }
  108633. }
  108634. });
  108635. // Prevent autoClear.
  108636. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  108637. };
  108638. /**
  108639. * Checks for the readiness of the element composing the layer.
  108640. * @param subMesh the mesh to check for
  108641. * @param useInstances specify wether or not to use instances to render the mesh
  108642. * @param emissiveTexture the associated emissive texture used to generate the glow
  108643. * @return true if ready otherwise, false
  108644. */
  108645. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  108646. var material = subMesh.getMaterial();
  108647. var mesh = subMesh.getRenderingMesh();
  108648. if (!material || !mesh) {
  108649. return false;
  108650. }
  108651. var emissiveTexture = material.emissiveTexture;
  108652. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  108653. };
  108654. /**
  108655. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  108656. */
  108657. GlowLayer.prototype.needStencil = function () {
  108658. return false;
  108659. };
  108660. /**
  108661. * Implementation specific of rendering the generating effect on the main canvas.
  108662. * @param effect The effect used to render through
  108663. */
  108664. GlowLayer.prototype._internalRender = function (effect) {
  108665. // Texture
  108666. effect.setTexture("textureSampler", this._blurTexture1);
  108667. effect.setTexture("textureSampler2", this._blurTexture2);
  108668. effect.setFloat("offset", this._intensity);
  108669. // Cache
  108670. var engine = this._engine;
  108671. var previousStencilBuffer = engine.getStencilBuffer();
  108672. // Draw order
  108673. engine.setStencilBuffer(false);
  108674. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108675. // Draw order
  108676. engine.setStencilBuffer(previousStencilBuffer);
  108677. };
  108678. /**
  108679. * Sets the required values for both the emissive texture and and the main color.
  108680. */
  108681. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  108682. var textureLevel = 1.0;
  108683. if (this.customEmissiveTextureSelector) {
  108684. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  108685. }
  108686. else {
  108687. if (material) {
  108688. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  108689. if (this._emissiveTextureAndColor.texture) {
  108690. textureLevel = this._emissiveTextureAndColor.texture.level;
  108691. }
  108692. }
  108693. else {
  108694. this._emissiveTextureAndColor.texture = null;
  108695. }
  108696. }
  108697. if (this.customEmissiveColorSelector) {
  108698. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  108699. }
  108700. else {
  108701. if (material.emissiveColor) {
  108702. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  108703. }
  108704. else {
  108705. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  108706. }
  108707. }
  108708. };
  108709. /**
  108710. * Returns true if the mesh should render, otherwise false.
  108711. * @param mesh The mesh to render
  108712. * @returns true if it should render otherwise false
  108713. */
  108714. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  108715. return this.hasMesh(mesh);
  108716. };
  108717. /**
  108718. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  108719. * @param mesh The mesh to exclude from the glow layer
  108720. */
  108721. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  108722. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  108723. this._excludedMeshes.push(mesh.uniqueId);
  108724. }
  108725. };
  108726. /**
  108727. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  108728. * @param mesh The mesh to remove
  108729. */
  108730. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  108731. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  108732. if (index !== -1) {
  108733. this._excludedMeshes.splice(index, 1);
  108734. }
  108735. };
  108736. /**
  108737. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  108738. * @param mesh The mesh to include in the glow layer
  108739. */
  108740. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  108741. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  108742. this._includedOnlyMeshes.push(mesh.uniqueId);
  108743. }
  108744. };
  108745. /**
  108746. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  108747. * @param mesh The mesh to remove
  108748. */
  108749. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  108750. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  108751. if (index !== -1) {
  108752. this._includedOnlyMeshes.splice(index, 1);
  108753. }
  108754. };
  108755. /**
  108756. * Determine if a given mesh will be used in the glow layer
  108757. * @param mesh The mesh to test
  108758. * @returns true if the mesh will be highlighted by the current glow layer
  108759. */
  108760. GlowLayer.prototype.hasMesh = function (mesh) {
  108761. if (!_super.prototype.hasMesh.call(this, mesh)) {
  108762. return false;
  108763. }
  108764. // Included Mesh
  108765. if (this._includedOnlyMeshes.length) {
  108766. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  108767. }
  108768. ;
  108769. // Excluded Mesh
  108770. if (this._excludedMeshes.length) {
  108771. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  108772. }
  108773. ;
  108774. return true;
  108775. };
  108776. /**
  108777. * Free any resources and references associated to a mesh.
  108778. * Internal use
  108779. * @param mesh The mesh to free.
  108780. * @hidden
  108781. */
  108782. GlowLayer.prototype._disposeMesh = function (mesh) {
  108783. this.removeIncludedOnlyMesh(mesh);
  108784. this.removeExcludedMesh(mesh);
  108785. };
  108786. /**
  108787. * Gets the class name of the effect layer
  108788. * @returns the string with the class name of the effect layer
  108789. */
  108790. GlowLayer.prototype.getClassName = function () {
  108791. return "GlowLayer";
  108792. };
  108793. /**
  108794. * Serializes this glow layer
  108795. * @returns a serialized glow layer object
  108796. */
  108797. GlowLayer.prototype.serialize = function () {
  108798. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108799. serializationObject.customType = "BABYLON.GlowLayer";
  108800. var index;
  108801. // Included meshes
  108802. serializationObject.includedMeshes = [];
  108803. if (this._includedOnlyMeshes.length) {
  108804. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  108805. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  108806. if (mesh) {
  108807. serializationObject.includedMeshes.push(mesh.id);
  108808. }
  108809. }
  108810. }
  108811. // Excluded meshes
  108812. serializationObject.excludedMeshes = [];
  108813. if (this._excludedMeshes.length) {
  108814. for (index = 0; index < this._excludedMeshes.length; index++) {
  108815. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  108816. if (mesh) {
  108817. serializationObject.excludedMeshes.push(mesh.id);
  108818. }
  108819. }
  108820. }
  108821. return serializationObject;
  108822. };
  108823. /**
  108824. * Creates a Glow Layer from parsed glow layer data
  108825. * @param parsedGlowLayer defines glow layer data
  108826. * @param scene defines the current scene
  108827. * @param rootUrl defines the root URL containing the glow layer information
  108828. * @returns a parsed Glow Layer
  108829. */
  108830. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  108831. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  108832. var index;
  108833. // Excluded meshes
  108834. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  108835. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  108836. if (mesh) {
  108837. gl.addExcludedMesh(mesh);
  108838. }
  108839. }
  108840. // Included meshes
  108841. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  108842. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  108843. if (mesh) {
  108844. gl.addIncludedOnlyMesh(mesh);
  108845. }
  108846. }
  108847. return gl;
  108848. };
  108849. /**
  108850. * Effect Name of the layer.
  108851. */
  108852. GlowLayer.EffectName = "GlowLayer";
  108853. /**
  108854. * The default blur kernel size used for the glow.
  108855. */
  108856. GlowLayer.DefaultBlurKernelSize = 32;
  108857. /**
  108858. * The default texture size ratio used for the glow.
  108859. */
  108860. GlowLayer.DefaultTextureRatio = 0.5;
  108861. __decorate([
  108862. BABYLON.serialize()
  108863. ], GlowLayer.prototype, "blurKernelSize", null);
  108864. __decorate([
  108865. BABYLON.serialize()
  108866. ], GlowLayer.prototype, "intensity", null);
  108867. __decorate([
  108868. BABYLON.serialize("options")
  108869. ], GlowLayer.prototype, "_options", void 0);
  108870. return GlowLayer;
  108871. }(BABYLON.EffectLayer));
  108872. BABYLON.GlowLayer = GlowLayer;
  108873. })(BABYLON || (BABYLON = {}));
  108874. //# sourceMappingURL=babylon.glowLayer.js.map
  108875. var BABYLON;
  108876. (function (BABYLON) {
  108877. /**
  108878. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  108879. */
  108880. var AssetTaskState;
  108881. (function (AssetTaskState) {
  108882. /**
  108883. * Initialization
  108884. */
  108885. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  108886. /**
  108887. * Running
  108888. */
  108889. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  108890. /**
  108891. * Done
  108892. */
  108893. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  108894. /**
  108895. * Error
  108896. */
  108897. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  108898. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  108899. /**
  108900. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  108901. */
  108902. var AbstractAssetTask = /** @class */ (function () {
  108903. /**
  108904. * Creates a new {BABYLON.AssetsManager}
  108905. * @param name defines the name of the task
  108906. */
  108907. function AbstractAssetTask(
  108908. /**
  108909. * Task name
  108910. */ name) {
  108911. this.name = name;
  108912. this._isCompleted = false;
  108913. this._taskState = AssetTaskState.INIT;
  108914. }
  108915. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  108916. /**
  108917. * Get if the task is completed
  108918. */
  108919. get: function () {
  108920. return this._isCompleted;
  108921. },
  108922. enumerable: true,
  108923. configurable: true
  108924. });
  108925. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  108926. /**
  108927. * Gets the current state of the task
  108928. */
  108929. get: function () {
  108930. return this._taskState;
  108931. },
  108932. enumerable: true,
  108933. configurable: true
  108934. });
  108935. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  108936. /**
  108937. * Gets the current error object (if task is in error)
  108938. */
  108939. get: function () {
  108940. return this._errorObject;
  108941. },
  108942. enumerable: true,
  108943. configurable: true
  108944. });
  108945. /**
  108946. * Internal only
  108947. * @hidden
  108948. */
  108949. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  108950. if (this._errorObject) {
  108951. return;
  108952. }
  108953. this._errorObject = {
  108954. message: message,
  108955. exception: exception
  108956. };
  108957. };
  108958. /**
  108959. * Execute the current task
  108960. * @param scene defines the scene where you want your assets to be loaded
  108961. * @param onSuccess is a callback called when the task is successfully executed
  108962. * @param onError is a callback called if an error occurs
  108963. */
  108964. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  108965. var _this = this;
  108966. this._taskState = AssetTaskState.RUNNING;
  108967. this.runTask(scene, function () {
  108968. _this.onDoneCallback(onSuccess, onError);
  108969. }, function (msg, exception) {
  108970. _this.onErrorCallback(onError, msg, exception);
  108971. });
  108972. };
  108973. /**
  108974. * Execute the current task
  108975. * @param scene defines the scene where you want your assets to be loaded
  108976. * @param onSuccess is a callback called when the task is successfully executed
  108977. * @param onError is a callback called if an error occurs
  108978. */
  108979. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108980. throw new Error("runTask is not implemented");
  108981. };
  108982. /**
  108983. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  108984. * This can be used with failed tasks that have the reason for failure fixed.
  108985. */
  108986. AbstractAssetTask.prototype.reset = function () {
  108987. this._taskState = AssetTaskState.INIT;
  108988. };
  108989. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  108990. this._taskState = AssetTaskState.ERROR;
  108991. this._errorObject = {
  108992. message: message,
  108993. exception: exception
  108994. };
  108995. if (this.onError) {
  108996. this.onError(this, message, exception);
  108997. }
  108998. onError();
  108999. };
  109000. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  109001. try {
  109002. this._taskState = AssetTaskState.DONE;
  109003. this._isCompleted = true;
  109004. if (this.onSuccess) {
  109005. this.onSuccess(this);
  109006. }
  109007. onSuccess();
  109008. }
  109009. catch (e) {
  109010. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  109011. }
  109012. };
  109013. return AbstractAssetTask;
  109014. }());
  109015. BABYLON.AbstractAssetTask = AbstractAssetTask;
  109016. /**
  109017. * Class used to share progress information about assets loading
  109018. */
  109019. var AssetsProgressEvent = /** @class */ (function () {
  109020. /**
  109021. * Creates a {BABYLON.AssetsProgressEvent}
  109022. * @param remainingCount defines the number of remaining tasks to process
  109023. * @param totalCount defines the total number of tasks
  109024. * @param task defines the task that was just processed
  109025. */
  109026. function AssetsProgressEvent(remainingCount, totalCount, task) {
  109027. this.remainingCount = remainingCount;
  109028. this.totalCount = totalCount;
  109029. this.task = task;
  109030. }
  109031. return AssetsProgressEvent;
  109032. }());
  109033. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  109034. /**
  109035. * Define a task used by {BABYLON.AssetsManager} to load meshes
  109036. */
  109037. var MeshAssetTask = /** @class */ (function (_super) {
  109038. __extends(MeshAssetTask, _super);
  109039. /**
  109040. * Creates a new {BABYLON.MeshAssetTask}
  109041. * @param name defines the name of the task
  109042. * @param meshesNames defines the list of mesh's names you want to load
  109043. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  109044. * @param sceneFilename defines the filename of the scene to load from
  109045. */
  109046. function MeshAssetTask(
  109047. /**
  109048. * Defines the name of the task
  109049. */
  109050. name,
  109051. /**
  109052. * Defines the list of mesh's names you want to load
  109053. */
  109054. meshesNames,
  109055. /**
  109056. * Defines the root url to use as a base to load your meshes and associated resources
  109057. */
  109058. rootUrl,
  109059. /**
  109060. * Defines the filename of the scene to load from
  109061. */
  109062. sceneFilename) {
  109063. var _this = _super.call(this, name) || this;
  109064. _this.name = name;
  109065. _this.meshesNames = meshesNames;
  109066. _this.rootUrl = rootUrl;
  109067. _this.sceneFilename = sceneFilename;
  109068. return _this;
  109069. }
  109070. /**
  109071. * Execute the current task
  109072. * @param scene defines the scene where you want your assets to be loaded
  109073. * @param onSuccess is a callback called when the task is successfully executed
  109074. * @param onError is a callback called if an error occurs
  109075. */
  109076. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109077. var _this = this;
  109078. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  109079. _this.loadedMeshes = meshes;
  109080. _this.loadedParticleSystems = particleSystems;
  109081. _this.loadedSkeletons = skeletons;
  109082. onSuccess();
  109083. }, null, function (scene, message, exception) {
  109084. onError(message, exception);
  109085. });
  109086. };
  109087. return MeshAssetTask;
  109088. }(AbstractAssetTask));
  109089. BABYLON.MeshAssetTask = MeshAssetTask;
  109090. /**
  109091. * Define a task used by {BABYLON.AssetsManager} to load text content
  109092. */
  109093. var TextFileAssetTask = /** @class */ (function (_super) {
  109094. __extends(TextFileAssetTask, _super);
  109095. /**
  109096. * Creates a new TextFileAssetTask object
  109097. * @param name defines the name of the task
  109098. * @param url defines the location of the file to load
  109099. */
  109100. function TextFileAssetTask(
  109101. /**
  109102. * Defines the name of the task
  109103. */
  109104. name,
  109105. /**
  109106. * Defines the location of the file to load
  109107. */
  109108. url) {
  109109. var _this = _super.call(this, name) || this;
  109110. _this.name = name;
  109111. _this.url = url;
  109112. return _this;
  109113. }
  109114. /**
  109115. * Execute the current task
  109116. * @param scene defines the scene where you want your assets to be loaded
  109117. * @param onSuccess is a callback called when the task is successfully executed
  109118. * @param onError is a callback called if an error occurs
  109119. */
  109120. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109121. var _this = this;
  109122. scene._loadFile(this.url, function (data) {
  109123. _this.text = data;
  109124. onSuccess();
  109125. }, undefined, false, false, function (request, exception) {
  109126. if (request) {
  109127. onError(request.status + " " + request.statusText, exception);
  109128. }
  109129. });
  109130. };
  109131. return TextFileAssetTask;
  109132. }(AbstractAssetTask));
  109133. BABYLON.TextFileAssetTask = TextFileAssetTask;
  109134. /**
  109135. * Define a task used by {BABYLON.AssetsManager} to load binary data
  109136. */
  109137. var BinaryFileAssetTask = /** @class */ (function (_super) {
  109138. __extends(BinaryFileAssetTask, _super);
  109139. /**
  109140. * Creates a new BinaryFileAssetTask object
  109141. * @param name defines the name of the new task
  109142. * @param url defines the location of the file to load
  109143. */
  109144. function BinaryFileAssetTask(
  109145. /**
  109146. * Defines the name of the task
  109147. */
  109148. name,
  109149. /**
  109150. * Defines the location of the file to load
  109151. */
  109152. url) {
  109153. var _this = _super.call(this, name) || this;
  109154. _this.name = name;
  109155. _this.url = url;
  109156. return _this;
  109157. }
  109158. /**
  109159. * Execute the current task
  109160. * @param scene defines the scene where you want your assets to be loaded
  109161. * @param onSuccess is a callback called when the task is successfully executed
  109162. * @param onError is a callback called if an error occurs
  109163. */
  109164. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109165. var _this = this;
  109166. scene._loadFile(this.url, function (data) {
  109167. _this.data = data;
  109168. onSuccess();
  109169. }, undefined, true, true, function (request, exception) {
  109170. if (request) {
  109171. onError(request.status + " " + request.statusText, exception);
  109172. }
  109173. });
  109174. };
  109175. return BinaryFileAssetTask;
  109176. }(AbstractAssetTask));
  109177. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  109178. /**
  109179. * Define a task used by {BABYLON.AssetsManager} to load images
  109180. */
  109181. var ImageAssetTask = /** @class */ (function (_super) {
  109182. __extends(ImageAssetTask, _super);
  109183. /**
  109184. * Creates a new ImageAssetTask
  109185. * @param name defines the name of the task
  109186. * @param url defines the location of the image to load
  109187. */
  109188. function ImageAssetTask(
  109189. /**
  109190. * Defines the name of the task
  109191. */
  109192. name,
  109193. /**
  109194. * Defines the location of the image to load
  109195. */
  109196. url) {
  109197. var _this = _super.call(this, name) || this;
  109198. _this.name = name;
  109199. _this.url = url;
  109200. return _this;
  109201. }
  109202. /**
  109203. * Execute the current task
  109204. * @param scene defines the scene where you want your assets to be loaded
  109205. * @param onSuccess is a callback called when the task is successfully executed
  109206. * @param onError is a callback called if an error occurs
  109207. */
  109208. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109209. var _this = this;
  109210. var img = new Image();
  109211. BABYLON.Tools.SetCorsBehavior(this.url, img);
  109212. img.onload = function () {
  109213. _this.image = img;
  109214. onSuccess();
  109215. };
  109216. img.onerror = function (err) {
  109217. onError("Error loading image", err);
  109218. };
  109219. img.src = this.url;
  109220. };
  109221. return ImageAssetTask;
  109222. }(AbstractAssetTask));
  109223. BABYLON.ImageAssetTask = ImageAssetTask;
  109224. /**
  109225. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  109226. */
  109227. var TextureAssetTask = /** @class */ (function (_super) {
  109228. __extends(TextureAssetTask, _super);
  109229. /**
  109230. * Creates a new TextureAssetTask object
  109231. * @param name defines the name of the task
  109232. * @param url defines the location of the file to load
  109233. * @param noMipmap defines if mipmap should not be generated (default is false)
  109234. * @param invertY defines if texture must be inverted on Y axis (default is false)
  109235. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  109236. */
  109237. function TextureAssetTask(
  109238. /**
  109239. * Defines the name of the task
  109240. */
  109241. name,
  109242. /**
  109243. * Defines the location of the file to load
  109244. */
  109245. url,
  109246. /**
  109247. * Defines if mipmap should not be generated (default is false)
  109248. */
  109249. noMipmap,
  109250. /**
  109251. * Defines if texture must be inverted on Y axis (default is false)
  109252. */
  109253. invertY,
  109254. /**
  109255. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  109256. */
  109257. samplingMode) {
  109258. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109259. var _this = _super.call(this, name) || this;
  109260. _this.name = name;
  109261. _this.url = url;
  109262. _this.noMipmap = noMipmap;
  109263. _this.invertY = invertY;
  109264. _this.samplingMode = samplingMode;
  109265. return _this;
  109266. }
  109267. /**
  109268. * Execute the current task
  109269. * @param scene defines the scene where you want your assets to be loaded
  109270. * @param onSuccess is a callback called when the task is successfully executed
  109271. * @param onError is a callback called if an error occurs
  109272. */
  109273. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109274. var onload = function () {
  109275. onSuccess();
  109276. };
  109277. var onerror = function (message, exception) {
  109278. onError(message, exception);
  109279. };
  109280. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  109281. };
  109282. return TextureAssetTask;
  109283. }(AbstractAssetTask));
  109284. BABYLON.TextureAssetTask = TextureAssetTask;
  109285. /**
  109286. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  109287. */
  109288. var CubeTextureAssetTask = /** @class */ (function (_super) {
  109289. __extends(CubeTextureAssetTask, _super);
  109290. /**
  109291. * Creates a new CubeTextureAssetTask
  109292. * @param name defines the name of the task
  109293. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  109294. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  109295. * @param noMipmap defines if mipmaps should not be generated (default is false)
  109296. * @param files defines the explicit list of files (undefined by default)
  109297. */
  109298. function CubeTextureAssetTask(
  109299. /**
  109300. * Defines the name of the task
  109301. */
  109302. name,
  109303. /**
  109304. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  109305. */
  109306. url,
  109307. /**
  109308. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  109309. */
  109310. extensions,
  109311. /**
  109312. * Defines if mipmaps should not be generated (default is false)
  109313. */
  109314. noMipmap,
  109315. /**
  109316. * Defines the explicit list of files (undefined by default)
  109317. */
  109318. files) {
  109319. var _this = _super.call(this, name) || this;
  109320. _this.name = name;
  109321. _this.url = url;
  109322. _this.extensions = extensions;
  109323. _this.noMipmap = noMipmap;
  109324. _this.files = files;
  109325. return _this;
  109326. }
  109327. /**
  109328. * Execute the current task
  109329. * @param scene defines the scene where you want your assets to be loaded
  109330. * @param onSuccess is a callback called when the task is successfully executed
  109331. * @param onError is a callback called if an error occurs
  109332. */
  109333. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109334. var onload = function () {
  109335. onSuccess();
  109336. };
  109337. var onerror = function (message, exception) {
  109338. onError(message, exception);
  109339. };
  109340. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  109341. };
  109342. return CubeTextureAssetTask;
  109343. }(AbstractAssetTask));
  109344. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  109345. /**
  109346. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  109347. */
  109348. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  109349. __extends(HDRCubeTextureAssetTask, _super);
  109350. /**
  109351. * Creates a new HDRCubeTextureAssetTask object
  109352. * @param name defines the name of the task
  109353. * @param url defines the location of the file to load
  109354. * @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.
  109355. * @param noMipmap defines if mipmaps should not be generated (default is false)
  109356. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  109357. * @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)
  109358. * @param reserved Internal use only
  109359. */
  109360. function HDRCubeTextureAssetTask(
  109361. /**
  109362. * Defines the name of the task
  109363. */
  109364. name,
  109365. /**
  109366. * Defines the location of the file to load
  109367. */
  109368. url,
  109369. /**
  109370. * Defines the desired size (the more it increases the longer the generation will be)
  109371. */
  109372. size,
  109373. /**
  109374. * Defines if mipmaps should not be generated (default is false)
  109375. */
  109376. noMipmap,
  109377. /**
  109378. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  109379. */
  109380. generateHarmonics,
  109381. /**
  109382. * 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)
  109383. */
  109384. gammaSpace,
  109385. /**
  109386. * Internal Use Only
  109387. */
  109388. reserved) {
  109389. if (noMipmap === void 0) { noMipmap = false; }
  109390. if (generateHarmonics === void 0) { generateHarmonics = true; }
  109391. if (gammaSpace === void 0) { gammaSpace = false; }
  109392. if (reserved === void 0) { reserved = false; }
  109393. var _this = _super.call(this, name) || this;
  109394. _this.name = name;
  109395. _this.url = url;
  109396. _this.size = size;
  109397. _this.noMipmap = noMipmap;
  109398. _this.generateHarmonics = generateHarmonics;
  109399. _this.gammaSpace = gammaSpace;
  109400. _this.reserved = reserved;
  109401. return _this;
  109402. }
  109403. /**
  109404. * Execute the current task
  109405. * @param scene defines the scene where you want your assets to be loaded
  109406. * @param onSuccess is a callback called when the task is successfully executed
  109407. * @param onError is a callback called if an error occurs
  109408. */
  109409. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  109410. var onload = function () {
  109411. onSuccess();
  109412. };
  109413. var onerror = function (message, exception) {
  109414. onError(message, exception);
  109415. };
  109416. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  109417. };
  109418. return HDRCubeTextureAssetTask;
  109419. }(AbstractAssetTask));
  109420. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  109421. /**
  109422. * This class can be used to easily import assets into a scene
  109423. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  109424. */
  109425. var AssetsManager = /** @class */ (function () {
  109426. /**
  109427. * Creates a new AssetsManager
  109428. * @param scene defines the scene to work on
  109429. */
  109430. function AssetsManager(scene) {
  109431. this._isLoading = false;
  109432. this._tasks = new Array();
  109433. this._waitingTasksCount = 0;
  109434. this._totalTasksCount = 0;
  109435. /**
  109436. * Observable called when all tasks are processed
  109437. */
  109438. this.onTaskSuccessObservable = new BABYLON.Observable();
  109439. /**
  109440. * Observable called when a task had an error
  109441. */
  109442. this.onTaskErrorObservable = new BABYLON.Observable();
  109443. /**
  109444. * Observable called when a task is successful
  109445. */
  109446. this.onTasksDoneObservable = new BABYLON.Observable();
  109447. /**
  109448. * Observable called when a task is done (whatever the result is)
  109449. */
  109450. this.onProgressObservable = new BABYLON.Observable();
  109451. /**
  109452. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  109453. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  109454. */
  109455. this.useDefaultLoadingScreen = true;
  109456. this._scene = scene;
  109457. }
  109458. /**
  109459. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  109460. * @param taskName defines the name of the new task
  109461. * @param meshesNames defines the name of meshes to load
  109462. * @param rootUrl defines the root url to use to locate files
  109463. * @param sceneFilename defines the filename of the scene file
  109464. * @returns a new {BABYLON.MeshAssetTask} object
  109465. */
  109466. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  109467. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  109468. this._tasks.push(task);
  109469. return task;
  109470. };
  109471. /**
  109472. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  109473. * @param taskName defines the name of the new task
  109474. * @param url defines the url of the file to load
  109475. * @returns a new {BABYLON.TextFileAssetTask} object
  109476. */
  109477. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  109478. var task = new TextFileAssetTask(taskName, url);
  109479. this._tasks.push(task);
  109480. return task;
  109481. };
  109482. /**
  109483. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  109484. * @param taskName defines the name of the new task
  109485. * @param url defines the url of the file to load
  109486. * @returns a new {BABYLON.BinaryFileAssetTask} object
  109487. */
  109488. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  109489. var task = new BinaryFileAssetTask(taskName, url);
  109490. this._tasks.push(task);
  109491. return task;
  109492. };
  109493. /**
  109494. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  109495. * @param taskName defines the name of the new task
  109496. * @param url defines the url of the file to load
  109497. * @returns a new {BABYLON.ImageAssetTask} object
  109498. */
  109499. AssetsManager.prototype.addImageTask = function (taskName, url) {
  109500. var task = new ImageAssetTask(taskName, url);
  109501. this._tasks.push(task);
  109502. return task;
  109503. };
  109504. /**
  109505. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  109506. * @param taskName defines the name of the new task
  109507. * @param url defines the url of the file to load
  109508. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  109509. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  109510. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  109511. * @returns a new {BABYLON.TextureAssetTask} object
  109512. */
  109513. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  109514. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109515. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  109516. this._tasks.push(task);
  109517. return task;
  109518. };
  109519. /**
  109520. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  109521. * @param taskName defines the name of the new task
  109522. * @param url defines the url of the file to load
  109523. * @param extensions defines the extension to use to load the cube map (can be null)
  109524. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  109525. * @param files defines the list of files to load (can be null)
  109526. * @returns a new {BABYLON.CubeTextureAssetTask} object
  109527. */
  109528. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  109529. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  109530. this._tasks.push(task);
  109531. return task;
  109532. };
  109533. /**
  109534. *
  109535. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  109536. * @param taskName defines the name of the new task
  109537. * @param url defines the url of the file to load
  109538. * @param size defines the size you want for the cubemap (can be null)
  109539. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  109540. * @param generateHarmonics defines if you want to automatically generate (true by default)
  109541. * @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)
  109542. * @param reserved Internal use only
  109543. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  109544. */
  109545. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  109546. if (noMipmap === void 0) { noMipmap = false; }
  109547. if (generateHarmonics === void 0) { generateHarmonics = true; }
  109548. if (gammaSpace === void 0) { gammaSpace = false; }
  109549. if (reserved === void 0) { reserved = false; }
  109550. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  109551. this._tasks.push(task);
  109552. return task;
  109553. };
  109554. /**
  109555. * Remove a task from the assets manager.
  109556. * @param task the task to remove
  109557. */
  109558. AssetsManager.prototype.removeTask = function (task) {
  109559. var index = this._tasks.indexOf(task);
  109560. if (index > -1) {
  109561. this._tasks.splice(index, 1);
  109562. }
  109563. };
  109564. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  109565. this._waitingTasksCount--;
  109566. try {
  109567. if (this.onProgress) {
  109568. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  109569. }
  109570. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  109571. }
  109572. catch (e) {
  109573. BABYLON.Tools.Error("Error running progress callbacks.");
  109574. console.log(e);
  109575. }
  109576. if (this._waitingTasksCount === 0) {
  109577. try {
  109578. if (this.onFinish) {
  109579. this.onFinish(this._tasks);
  109580. }
  109581. // Let's remove successfull tasks
  109582. var currentTasks = this._tasks.slice();
  109583. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  109584. var task = currentTasks_1[_i];
  109585. if (task.taskState === AssetTaskState.DONE) {
  109586. var index = this._tasks.indexOf(task);
  109587. if (index > -1) {
  109588. this._tasks.splice(index, 1);
  109589. }
  109590. }
  109591. }
  109592. this.onTasksDoneObservable.notifyObservers(this._tasks);
  109593. }
  109594. catch (e) {
  109595. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  109596. console.log(e);
  109597. }
  109598. this._isLoading = false;
  109599. this._scene.getEngine().hideLoadingUI();
  109600. }
  109601. };
  109602. AssetsManager.prototype._runTask = function (task) {
  109603. var _this = this;
  109604. var done = function () {
  109605. try {
  109606. if (_this.onTaskSuccess) {
  109607. _this.onTaskSuccess(task);
  109608. }
  109609. _this.onTaskSuccessObservable.notifyObservers(task);
  109610. _this._decreaseWaitingTasksCount(task);
  109611. }
  109612. catch (e) {
  109613. error("Error executing task success callbacks", e);
  109614. }
  109615. };
  109616. var error = function (message, exception) {
  109617. task._setErrorObject(message, exception);
  109618. if (_this.onTaskError) {
  109619. _this.onTaskError(task);
  109620. }
  109621. _this.onTaskErrorObservable.notifyObservers(task);
  109622. _this._decreaseWaitingTasksCount(task);
  109623. };
  109624. task.run(this._scene, done, error);
  109625. };
  109626. /**
  109627. * Reset the {BABYLON.AssetsManager} and remove all tasks
  109628. * @return the current instance of the {BABYLON.AssetsManager}
  109629. */
  109630. AssetsManager.prototype.reset = function () {
  109631. this._isLoading = false;
  109632. this._tasks = new Array();
  109633. return this;
  109634. };
  109635. /**
  109636. * Start the loading process
  109637. * @return the current instance of the {BABYLON.AssetsManager}
  109638. */
  109639. AssetsManager.prototype.load = function () {
  109640. if (this._isLoading) {
  109641. return this;
  109642. }
  109643. this._isLoading = true;
  109644. this._waitingTasksCount = this._tasks.length;
  109645. this._totalTasksCount = this._tasks.length;
  109646. if (this._waitingTasksCount === 0) {
  109647. this._isLoading = false;
  109648. if (this.onFinish) {
  109649. this.onFinish(this._tasks);
  109650. }
  109651. this.onTasksDoneObservable.notifyObservers(this._tasks);
  109652. return this;
  109653. }
  109654. if (this.useDefaultLoadingScreen) {
  109655. this._scene.getEngine().displayLoadingUI();
  109656. }
  109657. for (var index = 0; index < this._tasks.length; index++) {
  109658. var task = this._tasks[index];
  109659. if (task.taskState === AssetTaskState.INIT) {
  109660. this._runTask(task);
  109661. }
  109662. }
  109663. return this;
  109664. };
  109665. return AssetsManager;
  109666. }());
  109667. BABYLON.AssetsManager = AssetsManager;
  109668. })(BABYLON || (BABYLON = {}));
  109669. //# sourceMappingURL=babylon.assetsManager.js.map
  109670. var BABYLON;
  109671. (function (BABYLON) {
  109672. var serializedGeometries = [];
  109673. var serializeGeometry = function (geometry, serializationGeometries) {
  109674. if (serializedGeometries[geometry.id]) {
  109675. return;
  109676. }
  109677. if (geometry.doNotSerialize) {
  109678. return;
  109679. }
  109680. if (geometry instanceof BABYLON.BoxGeometry) {
  109681. serializationGeometries.boxes.push(geometry.serialize());
  109682. }
  109683. else if (geometry instanceof BABYLON.SphereGeometry) {
  109684. serializationGeometries.spheres.push(geometry.serialize());
  109685. }
  109686. else if (geometry instanceof BABYLON.CylinderGeometry) {
  109687. serializationGeometries.cylinders.push(geometry.serialize());
  109688. }
  109689. else if (geometry instanceof BABYLON.TorusGeometry) {
  109690. serializationGeometries.toruses.push(geometry.serialize());
  109691. }
  109692. else if (geometry instanceof BABYLON.GroundGeometry) {
  109693. serializationGeometries.grounds.push(geometry.serialize());
  109694. }
  109695. else if (geometry instanceof BABYLON.Plane) {
  109696. serializationGeometries.planes.push(geometry.serialize());
  109697. }
  109698. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  109699. serializationGeometries.torusKnots.push(geometry.serialize());
  109700. }
  109701. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  109702. throw new Error("Unknown primitive type");
  109703. }
  109704. else {
  109705. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  109706. }
  109707. serializedGeometries[geometry.id] = true;
  109708. };
  109709. var serializeMesh = function (mesh, serializationScene) {
  109710. var serializationObject = {};
  109711. // Geometry
  109712. var geometry = mesh._geometry;
  109713. if (geometry) {
  109714. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  109715. // 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
  109716. serializeGeometry(geometry, serializationScene.geometries);
  109717. }
  109718. }
  109719. // Custom
  109720. if (mesh.serialize) {
  109721. mesh.serialize(serializationObject);
  109722. }
  109723. return serializationObject;
  109724. };
  109725. var finalizeSingleMesh = function (mesh, serializationObject) {
  109726. //only works if the mesh is already loaded
  109727. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  109728. //serialize material
  109729. if (mesh.material) {
  109730. if (mesh.material instanceof BABYLON.MultiMaterial) {
  109731. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  109732. serializationObject.materials = serializationObject.materials || [];
  109733. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  109734. serializationObject.multiMaterials.push(mesh.material.serialize());
  109735. var _loop_1 = function (submaterial) {
  109736. if (submaterial) {
  109737. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  109738. serializationObject.materials.push(submaterial.serialize());
  109739. }
  109740. }
  109741. };
  109742. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  109743. var submaterial = _a[_i];
  109744. _loop_1(submaterial);
  109745. }
  109746. }
  109747. }
  109748. else {
  109749. serializationObject.materials = serializationObject.materials || [];
  109750. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  109751. serializationObject.materials.push(mesh.material.serialize());
  109752. }
  109753. }
  109754. }
  109755. //serialize geometry
  109756. var geometry = mesh._geometry;
  109757. if (geometry) {
  109758. if (!serializationObject.geometries) {
  109759. serializationObject.geometries = {};
  109760. serializationObject.geometries.boxes = [];
  109761. serializationObject.geometries.spheres = [];
  109762. serializationObject.geometries.cylinders = [];
  109763. serializationObject.geometries.toruses = [];
  109764. serializationObject.geometries.grounds = [];
  109765. serializationObject.geometries.planes = [];
  109766. serializationObject.geometries.torusKnots = [];
  109767. serializationObject.geometries.vertexData = [];
  109768. }
  109769. serializeGeometry(geometry, serializationObject.geometries);
  109770. }
  109771. // Skeletons
  109772. if (mesh.skeleton) {
  109773. serializationObject.skeletons = serializationObject.skeletons || [];
  109774. serializationObject.skeletons.push(mesh.skeleton.serialize());
  109775. }
  109776. //serialize the actual mesh
  109777. serializationObject.meshes = serializationObject.meshes || [];
  109778. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  109779. }
  109780. };
  109781. /**
  109782. * Class used to serialize a scene into a string
  109783. */
  109784. var SceneSerializer = /** @class */ (function () {
  109785. function SceneSerializer() {
  109786. }
  109787. /**
  109788. * Clear cache used by a previous serialization
  109789. */
  109790. SceneSerializer.ClearCache = function () {
  109791. serializedGeometries = [];
  109792. };
  109793. /**
  109794. * Serialize a scene into a JSON compatible object
  109795. * @param scene defines the scene to serialize
  109796. * @returns a JSON compatible object
  109797. */
  109798. SceneSerializer.Serialize = function (scene) {
  109799. var serializationObject = {};
  109800. SceneSerializer.ClearCache();
  109801. // Scene
  109802. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  109803. serializationObject.autoClear = scene.autoClear;
  109804. serializationObject.clearColor = scene.clearColor.asArray();
  109805. serializationObject.ambientColor = scene.ambientColor.asArray();
  109806. serializationObject.gravity = scene.gravity.asArray();
  109807. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  109808. serializationObject.workerCollisions = scene.workerCollisions;
  109809. // Fog
  109810. if (scene.fogMode && scene.fogMode !== 0) {
  109811. serializationObject.fogMode = scene.fogMode;
  109812. serializationObject.fogColor = scene.fogColor.asArray();
  109813. serializationObject.fogStart = scene.fogStart;
  109814. serializationObject.fogEnd = scene.fogEnd;
  109815. serializationObject.fogDensity = scene.fogDensity;
  109816. }
  109817. //Physics
  109818. if (scene.isPhysicsEnabled()) {
  109819. var physicEngine = scene.getPhysicsEngine();
  109820. if (physicEngine) {
  109821. serializationObject.physicsEnabled = true;
  109822. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  109823. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  109824. }
  109825. }
  109826. // Metadata
  109827. if (scene.metadata) {
  109828. serializationObject.metadata = scene.metadata;
  109829. }
  109830. // Morph targets
  109831. serializationObject.morphTargetManagers = [];
  109832. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  109833. var abstractMesh = _a[_i];
  109834. var manager = abstractMesh.morphTargetManager;
  109835. if (manager) {
  109836. serializationObject.morphTargetManagers.push(manager.serialize());
  109837. }
  109838. }
  109839. // Lights
  109840. serializationObject.lights = [];
  109841. var index;
  109842. var light;
  109843. for (index = 0; index < scene.lights.length; index++) {
  109844. light = scene.lights[index];
  109845. if (!light.doNotSerialize) {
  109846. serializationObject.lights.push(light.serialize());
  109847. }
  109848. }
  109849. // Cameras
  109850. serializationObject.cameras = [];
  109851. for (index = 0; index < scene.cameras.length; index++) {
  109852. var camera = scene.cameras[index];
  109853. if (!camera.doNotSerialize) {
  109854. serializationObject.cameras.push(camera.serialize());
  109855. }
  109856. }
  109857. if (scene.activeCamera) {
  109858. serializationObject.activeCameraID = scene.activeCamera.id;
  109859. }
  109860. // Animations
  109861. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  109862. // Materials
  109863. serializationObject.materials = [];
  109864. serializationObject.multiMaterials = [];
  109865. var material;
  109866. for (index = 0; index < scene.materials.length; index++) {
  109867. material = scene.materials[index];
  109868. if (!material.doNotSerialize) {
  109869. serializationObject.materials.push(material.serialize());
  109870. }
  109871. }
  109872. // MultiMaterials
  109873. serializationObject.multiMaterials = [];
  109874. for (index = 0; index < scene.multiMaterials.length; index++) {
  109875. var multiMaterial = scene.multiMaterials[index];
  109876. serializationObject.multiMaterials.push(multiMaterial.serialize());
  109877. }
  109878. // Environment texture
  109879. if (scene.environmentTexture) {
  109880. serializationObject.environmentTexture = scene.environmentTexture.name;
  109881. }
  109882. // Skeletons
  109883. serializationObject.skeletons = [];
  109884. for (index = 0; index < scene.skeletons.length; index++) {
  109885. var skeleton = scene.skeletons[index];
  109886. if (!skeleton.doNotSerialize) {
  109887. serializationObject.skeletons.push(skeleton.serialize());
  109888. }
  109889. }
  109890. // Transform nodes
  109891. serializationObject.transformNodes = [];
  109892. for (index = 0; index < scene.transformNodes.length; index++) {
  109893. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  109894. }
  109895. // Geometries
  109896. serializationObject.geometries = {};
  109897. serializationObject.geometries.boxes = [];
  109898. serializationObject.geometries.spheres = [];
  109899. serializationObject.geometries.cylinders = [];
  109900. serializationObject.geometries.toruses = [];
  109901. serializationObject.geometries.grounds = [];
  109902. serializationObject.geometries.planes = [];
  109903. serializationObject.geometries.torusKnots = [];
  109904. serializationObject.geometries.vertexData = [];
  109905. serializedGeometries = [];
  109906. var geometries = scene.getGeometries();
  109907. for (index = 0; index < geometries.length; index++) {
  109908. var geometry = geometries[index];
  109909. if (geometry.isReady()) {
  109910. serializeGeometry(geometry, serializationObject.geometries);
  109911. }
  109912. }
  109913. // Meshes
  109914. serializationObject.meshes = [];
  109915. for (index = 0; index < scene.meshes.length; index++) {
  109916. var abstractMesh = scene.meshes[index];
  109917. if (abstractMesh instanceof BABYLON.Mesh) {
  109918. var mesh = abstractMesh;
  109919. if (!mesh.doNotSerialize) {
  109920. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  109921. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  109922. }
  109923. }
  109924. }
  109925. }
  109926. // Particles Systems
  109927. serializationObject.particleSystems = [];
  109928. for (index = 0; index < scene.particleSystems.length; index++) {
  109929. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  109930. }
  109931. // Action Manager
  109932. if (scene.actionManager) {
  109933. serializationObject.actions = scene.actionManager.serialize("scene");
  109934. }
  109935. // Components
  109936. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  109937. var component = _c[_b];
  109938. component.serialize(serializationObject);
  109939. }
  109940. return serializationObject;
  109941. };
  109942. /**
  109943. * Serialize a mesh into a JSON compatible object
  109944. * @param toSerialize defines the mesh to serialize
  109945. * @param withParents defines if parents must be serialized as well
  109946. * @param withChildren defines if children must be serialized as well
  109947. * @returns a JSON compatible object
  109948. */
  109949. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  109950. if (withParents === void 0) { withParents = false; }
  109951. if (withChildren === void 0) { withChildren = false; }
  109952. var serializationObject = {};
  109953. SceneSerializer.ClearCache();
  109954. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  109955. if (withParents || withChildren) {
  109956. //deliberate for loop! not for each, appended should be processed as well.
  109957. for (var i = 0; i < toSerialize.length; ++i) {
  109958. if (withChildren) {
  109959. toSerialize[i].getDescendants().forEach(function (node) {
  109960. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  109961. toSerialize.push(node);
  109962. }
  109963. });
  109964. }
  109965. //make sure the array doesn't contain the object already
  109966. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  109967. toSerialize.push(toSerialize[i].parent);
  109968. }
  109969. }
  109970. }
  109971. toSerialize.forEach(function (mesh) {
  109972. finalizeSingleMesh(mesh, serializationObject);
  109973. });
  109974. return serializationObject;
  109975. };
  109976. return SceneSerializer;
  109977. }());
  109978. BABYLON.SceneSerializer = SceneSerializer;
  109979. })(BABYLON || (BABYLON = {}));
  109980. //# sourceMappingURL=babylon.sceneSerializer.js.map
  109981. var BABYLON;
  109982. (function (BABYLON) {
  109983. /**
  109984. * Class used to generate realtime reflection / refraction cube textures
  109985. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  109986. */
  109987. var ReflectionProbe = /** @class */ (function () {
  109988. /**
  109989. * Creates a new reflection probe
  109990. * @param name defines the name of the probe
  109991. * @param size defines the texture resolution (for each face)
  109992. * @param scene defines the hosting scene
  109993. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  109994. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  109995. */
  109996. function ReflectionProbe(
  109997. /** defines the name of the probe */
  109998. name, size, scene, generateMipMaps, useFloat) {
  109999. if (generateMipMaps === void 0) { generateMipMaps = true; }
  110000. if (useFloat === void 0) { useFloat = false; }
  110001. var _this = this;
  110002. this.name = name;
  110003. this._viewMatrix = BABYLON.Matrix.Identity();
  110004. this._target = BABYLON.Vector3.Zero();
  110005. this._add = BABYLON.Vector3.Zero();
  110006. this._invertYAxis = false;
  110007. /** Gets or sets probe position (center of the cube map) */
  110008. this.position = BABYLON.Vector3.Zero();
  110009. this._scene = scene;
  110010. // Create the scene field if not exist.
  110011. if (!this._scene.reflectionProbes) {
  110012. this._scene.reflectionProbes = new Array();
  110013. }
  110014. this._scene.reflectionProbes.push(this);
  110015. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  110016. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  110017. switch (faceIndex) {
  110018. case 0:
  110019. _this._add.copyFromFloats(1, 0, 0);
  110020. break;
  110021. case 1:
  110022. _this._add.copyFromFloats(-1, 0, 0);
  110023. break;
  110024. case 2:
  110025. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  110026. break;
  110027. case 3:
  110028. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  110029. break;
  110030. case 4:
  110031. _this._add.copyFromFloats(0, 0, 1);
  110032. break;
  110033. case 5:
  110034. _this._add.copyFromFloats(0, 0, -1);
  110035. break;
  110036. }
  110037. if (_this._attachedMesh) {
  110038. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  110039. }
  110040. _this.position.addToRef(_this._add, _this._target);
  110041. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  110042. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  110043. scene._forcedViewPosition = _this.position;
  110044. });
  110045. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  110046. scene._forcedViewPosition = null;
  110047. scene.updateTransformMatrix(true);
  110048. });
  110049. if (scene.activeCamera) {
  110050. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  110051. }
  110052. }
  110053. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  110054. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  110055. get: function () {
  110056. return this._renderTargetTexture.samples;
  110057. },
  110058. set: function (value) {
  110059. this._renderTargetTexture.samples = value;
  110060. },
  110061. enumerable: true,
  110062. configurable: true
  110063. });
  110064. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  110065. /** Gets or sets the refresh rate to use (on every frame by default) */
  110066. get: function () {
  110067. return this._renderTargetTexture.refreshRate;
  110068. },
  110069. set: function (value) {
  110070. this._renderTargetTexture.refreshRate = value;
  110071. },
  110072. enumerable: true,
  110073. configurable: true
  110074. });
  110075. /**
  110076. * Gets the hosting scene
  110077. * @returns a Scene
  110078. */
  110079. ReflectionProbe.prototype.getScene = function () {
  110080. return this._scene;
  110081. };
  110082. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  110083. /** Gets the internal CubeTexture used to render to */
  110084. get: function () {
  110085. return this._renderTargetTexture;
  110086. },
  110087. enumerable: true,
  110088. configurable: true
  110089. });
  110090. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  110091. /** Gets the list of meshes to render */
  110092. get: function () {
  110093. return this._renderTargetTexture.renderList;
  110094. },
  110095. enumerable: true,
  110096. configurable: true
  110097. });
  110098. /**
  110099. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  110100. * @param mesh defines the mesh to attach to
  110101. */
  110102. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  110103. this._attachedMesh = mesh;
  110104. };
  110105. /**
  110106. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  110107. * @param renderingGroupId The rendering group id corresponding to its index
  110108. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  110109. */
  110110. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  110111. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  110112. };
  110113. /**
  110114. * Clean all associated resources
  110115. */
  110116. ReflectionProbe.prototype.dispose = function () {
  110117. var index = this._scene.reflectionProbes.indexOf(this);
  110118. if (index !== -1) {
  110119. // Remove from the scene if found
  110120. this._scene.reflectionProbes.splice(index, 1);
  110121. }
  110122. if (this._renderTargetTexture) {
  110123. this._renderTargetTexture.dispose();
  110124. this._renderTargetTexture = null;
  110125. }
  110126. };
  110127. return ReflectionProbe;
  110128. }());
  110129. BABYLON.ReflectionProbe = ReflectionProbe;
  110130. })(BABYLON || (BABYLON = {}));
  110131. //# sourceMappingURL=babylon.reflectionProbe.js.map
  110132. var BABYLON;
  110133. (function (BABYLON) {
  110134. /**
  110135. * Defines the layer scene component responsible to manage any layers
  110136. * in a given scene.
  110137. */
  110138. var LayerSceneComponent = /** @class */ (function () {
  110139. /**
  110140. * Creates a new instance of the component for the given scene
  110141. * @param scene Defines the scene to register the component in
  110142. */
  110143. function LayerSceneComponent(scene) {
  110144. /**
  110145. * The component name helpfull to identify the component in the list of scene components.
  110146. */
  110147. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  110148. this.scene = scene;
  110149. this._engine = scene.getEngine();
  110150. scene.layers = new Array();
  110151. }
  110152. /**
  110153. * Registers the component in a given scene
  110154. */
  110155. LayerSceneComponent.prototype.register = function () {
  110156. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  110157. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  110158. };
  110159. /**
  110160. * Rebuilds the elements related to this component in case of
  110161. * context lost for instance.
  110162. */
  110163. LayerSceneComponent.prototype.rebuild = function () {
  110164. var layers = this.scene.layers;
  110165. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  110166. var layer = layers_1[_i];
  110167. layer._rebuild();
  110168. }
  110169. };
  110170. /**
  110171. * Disposes the component and the associated ressources.
  110172. */
  110173. LayerSceneComponent.prototype.dispose = function () {
  110174. var layers = this.scene.layers;
  110175. while (layers.length) {
  110176. layers[0].dispose();
  110177. }
  110178. };
  110179. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  110180. var layers = this.scene.layers;
  110181. if (layers.length) {
  110182. this._engine.setDepthBuffer(false);
  110183. var cameraLayerMask = camera.layerMask;
  110184. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  110185. var layer = layers_2[_i];
  110186. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  110187. layer.render();
  110188. }
  110189. }
  110190. this._engine.setDepthBuffer(true);
  110191. }
  110192. };
  110193. LayerSceneComponent.prototype._drawBackground = function (camera) {
  110194. this._draw(camera, true);
  110195. };
  110196. LayerSceneComponent.prototype._drawForeground = function (camera) {
  110197. this._draw(camera, false);
  110198. };
  110199. return LayerSceneComponent;
  110200. }());
  110201. BABYLON.LayerSceneComponent = LayerSceneComponent;
  110202. })(BABYLON || (BABYLON = {}));
  110203. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  110204. var BABYLON;
  110205. (function (BABYLON) {
  110206. /**
  110207. * This represents a full screen 2d layer.
  110208. * This can be usefull to display a picture in the background of your scene for instance.
  110209. * @see https://www.babylonjs-playground.com/#08A2BS#1
  110210. */
  110211. var Layer = /** @class */ (function () {
  110212. /**
  110213. * Instantiates a new layer.
  110214. * This represents a full screen 2d layer.
  110215. * This can be usefull to display a picture in the background of your scene for instance.
  110216. * @see https://www.babylonjs-playground.com/#08A2BS#1
  110217. * @param name Define the name of the layer in the scene
  110218. * @param imgUrl Define the url of the texture to display in the layer
  110219. * @param scene Define the scene the layer belongs to
  110220. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  110221. * @param color Defines a color for the layer
  110222. */
  110223. function Layer(
  110224. /**
  110225. * Define the name of the layer.
  110226. */
  110227. name, imgUrl, scene, isBackground, color) {
  110228. this.name = name;
  110229. /**
  110230. * Define the scale of the layer in order to zoom in out of the texture.
  110231. */
  110232. this.scale = new BABYLON.Vector2(1, 1);
  110233. /**
  110234. * Define an offset for the layer in order to shift the texture.
  110235. */
  110236. this.offset = new BABYLON.Vector2(0, 0);
  110237. /**
  110238. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  110239. */
  110240. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  110241. /**
  110242. * Define a mask to restrict the layer to only some of the scene cameras.
  110243. */
  110244. this.layerMask = 0x0FFFFFFF;
  110245. this._vertexBuffers = {};
  110246. /**
  110247. * An event triggered when the layer is disposed.
  110248. */
  110249. this.onDisposeObservable = new BABYLON.Observable();
  110250. /**
  110251. * An event triggered before rendering the scene
  110252. */
  110253. this.onBeforeRenderObservable = new BABYLON.Observable();
  110254. /**
  110255. * An event triggered after rendering the scene
  110256. */
  110257. this.onAfterRenderObservable = new BABYLON.Observable();
  110258. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  110259. this.isBackground = isBackground === undefined ? true : isBackground;
  110260. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  110261. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  110262. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  110263. if (!layerComponent) {
  110264. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  110265. this._scene._addComponent(layerComponent);
  110266. }
  110267. this._scene.layers.push(this);
  110268. var engine = this._scene.getEngine();
  110269. // VBO
  110270. var vertices = [];
  110271. vertices.push(1, 1);
  110272. vertices.push(-1, 1);
  110273. vertices.push(-1, -1);
  110274. vertices.push(1, -1);
  110275. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  110276. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  110277. this._createIndexBuffer();
  110278. // Effects
  110279. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  110280. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  110281. }
  110282. Object.defineProperty(Layer.prototype, "onDispose", {
  110283. /**
  110284. * Back compatibility with callback before the onDisposeObservable existed.
  110285. * The set callback will be triggered when the layer has been disposed.
  110286. */
  110287. set: function (callback) {
  110288. if (this._onDisposeObserver) {
  110289. this.onDisposeObservable.remove(this._onDisposeObserver);
  110290. }
  110291. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  110292. },
  110293. enumerable: true,
  110294. configurable: true
  110295. });
  110296. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  110297. /**
  110298. * Back compatibility with callback before the onBeforeRenderObservable existed.
  110299. * The set callback will be triggered just before rendering the layer.
  110300. */
  110301. set: function (callback) {
  110302. if (this._onBeforeRenderObserver) {
  110303. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  110304. }
  110305. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  110306. },
  110307. enumerable: true,
  110308. configurable: true
  110309. });
  110310. Object.defineProperty(Layer.prototype, "onAfterRender", {
  110311. /**
  110312. * Back compatibility with callback before the onAfterRenderObservable existed.
  110313. * The set callback will be triggered just after rendering the layer.
  110314. */
  110315. set: function (callback) {
  110316. if (this._onAfterRenderObserver) {
  110317. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  110318. }
  110319. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  110320. },
  110321. enumerable: true,
  110322. configurable: true
  110323. });
  110324. Layer.prototype._createIndexBuffer = function () {
  110325. var engine = this._scene.getEngine();
  110326. // Indices
  110327. var indices = [];
  110328. indices.push(0);
  110329. indices.push(1);
  110330. indices.push(2);
  110331. indices.push(0);
  110332. indices.push(2);
  110333. indices.push(3);
  110334. this._indexBuffer = engine.createIndexBuffer(indices);
  110335. };
  110336. /** @hidden */
  110337. Layer.prototype._rebuild = function () {
  110338. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  110339. if (vb) {
  110340. vb._rebuild();
  110341. }
  110342. this._createIndexBuffer();
  110343. };
  110344. /**
  110345. * Renders the layer in the scene.
  110346. */
  110347. Layer.prototype.render = function () {
  110348. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  110349. // Check
  110350. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  110351. return;
  110352. var engine = this._scene.getEngine();
  110353. this.onBeforeRenderObservable.notifyObservers(this);
  110354. // Render
  110355. engine.enableEffect(currentEffect);
  110356. engine.setState(false);
  110357. // Texture
  110358. currentEffect.setTexture("textureSampler", this.texture);
  110359. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  110360. // Color
  110361. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  110362. // Scale / offset
  110363. currentEffect.setVector2("offset", this.offset);
  110364. currentEffect.setVector2("scale", this.scale);
  110365. // VBOs
  110366. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  110367. // Draw order
  110368. if (!this.alphaTest) {
  110369. engine.setAlphaMode(this.alphaBlendingMode);
  110370. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110371. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  110372. }
  110373. else {
  110374. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110375. }
  110376. this.onAfterRenderObservable.notifyObservers(this);
  110377. };
  110378. /**
  110379. * Disposes and releases the associated ressources.
  110380. */
  110381. Layer.prototype.dispose = function () {
  110382. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  110383. if (vertexBuffer) {
  110384. vertexBuffer.dispose();
  110385. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  110386. }
  110387. if (this._indexBuffer) {
  110388. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  110389. this._indexBuffer = null;
  110390. }
  110391. if (this.texture) {
  110392. this.texture.dispose();
  110393. this.texture = null;
  110394. }
  110395. // Remove from scene
  110396. var index = this._scene.layers.indexOf(this);
  110397. this._scene.layers.splice(index, 1);
  110398. // Callback
  110399. this.onDisposeObservable.notifyObservers(this);
  110400. this.onDisposeObservable.clear();
  110401. this.onAfterRenderObservable.clear();
  110402. this.onBeforeRenderObservable.clear();
  110403. };
  110404. return Layer;
  110405. }());
  110406. BABYLON.Layer = Layer;
  110407. })(BABYLON || (BABYLON = {}));
  110408. //# sourceMappingURL=babylon.layer.js.map
  110409. var BABYLON;
  110410. (function (BABYLON) {
  110411. /**
  110412. * Class used to host texture specific utilities
  110413. */
  110414. var TextureTools = /** @class */ (function () {
  110415. function TextureTools() {
  110416. }
  110417. /**
  110418. * Uses the GPU to create a copy texture rescaled at a given size
  110419. * @param texture Texture to copy from
  110420. * @param width defines the desired width
  110421. * @param height defines the desired height
  110422. * @param useBilinearMode defines if bilinear mode has to be used
  110423. * @return the generated texture
  110424. */
  110425. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  110426. if (useBilinearMode === void 0) { useBilinearMode = true; }
  110427. var scene = texture.getScene();
  110428. var engine = scene.getEngine();
  110429. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  110430. rtt.wrapU = texture.wrapU;
  110431. rtt.wrapV = texture.wrapV;
  110432. rtt.uOffset = texture.uOffset;
  110433. rtt.vOffset = texture.vOffset;
  110434. rtt.uScale = texture.uScale;
  110435. rtt.vScale = texture.vScale;
  110436. rtt.uAng = texture.uAng;
  110437. rtt.vAng = texture.vAng;
  110438. rtt.wAng = texture.wAng;
  110439. rtt.coordinatesIndex = texture.coordinatesIndex;
  110440. rtt.level = texture.level;
  110441. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  110442. rtt._texture.isReady = false;
  110443. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110444. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110445. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  110446. passPostProcess.getEffect().executeWhenCompiled(function () {
  110447. passPostProcess.onApply = function (effect) {
  110448. effect.setTexture("textureSampler", texture);
  110449. };
  110450. var internalTexture = rtt.getInternalTexture();
  110451. if (internalTexture) {
  110452. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  110453. engine.unBindFramebuffer(internalTexture);
  110454. rtt.disposeFramebufferObjects();
  110455. passPostProcess.dispose();
  110456. internalTexture.isReady = true;
  110457. }
  110458. });
  110459. return rtt;
  110460. };
  110461. /**
  110462. * Gets an environment BRDF texture for a given scene
  110463. * @param scene defines the hosting scene
  110464. * @returns the environment BRDF texture
  110465. */
  110466. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  110467. if (!scene._environmentBRDFTexture) {
  110468. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110469. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110470. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110471. scene._environmentBRDFTexture = texture;
  110472. }
  110473. return scene._environmentBRDFTexture;
  110474. };
  110475. 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=";
  110476. return TextureTools;
  110477. }());
  110478. BABYLON.TextureTools = TextureTools;
  110479. })(BABYLON || (BABYLON = {}));
  110480. //# sourceMappingURL=babylon.textureTools.js.map
  110481. var BABYLON;
  110482. (function (BABYLON) {
  110483. /**
  110484. * 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.
  110485. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  110486. */
  110487. var FramingBehavior = /** @class */ (function () {
  110488. function FramingBehavior() {
  110489. this._mode = FramingBehavior.FitFrustumSidesMode;
  110490. this._radiusScale = 1.0;
  110491. this._positionScale = 0.5;
  110492. this._defaultElevation = 0.3;
  110493. this._elevationReturnTime = 1500;
  110494. this._elevationReturnWaitTime = 1000;
  110495. this._zoomStopsAnimation = false;
  110496. this._framingTime = 1500;
  110497. /**
  110498. * Define if the behavior should automatically change the configured
  110499. * camera limits and sensibilities.
  110500. */
  110501. this.autoCorrectCameraLimitsAndSensibility = true;
  110502. this._isPointerDown = false;
  110503. this._lastInteractionTime = -Infinity;
  110504. // Framing control
  110505. this._animatables = new Array();
  110506. this._betaIsAnimating = false;
  110507. }
  110508. Object.defineProperty(FramingBehavior.prototype, "name", {
  110509. /**
  110510. * Gets the name of the behavior.
  110511. */
  110512. get: function () {
  110513. return "Framing";
  110514. },
  110515. enumerable: true,
  110516. configurable: true
  110517. });
  110518. Object.defineProperty(FramingBehavior.prototype, "mode", {
  110519. /**
  110520. * Gets current mode used by the behavior.
  110521. */
  110522. get: function () {
  110523. return this._mode;
  110524. },
  110525. /**
  110526. * Sets the current mode used by the behavior
  110527. */
  110528. set: function (mode) {
  110529. this._mode = mode;
  110530. },
  110531. enumerable: true,
  110532. configurable: true
  110533. });
  110534. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  110535. /**
  110536. * Gets the scale applied to the radius
  110537. */
  110538. get: function () {
  110539. return this._radiusScale;
  110540. },
  110541. /**
  110542. * Sets the scale applied to the radius (1 by default)
  110543. */
  110544. set: function (radius) {
  110545. this._radiusScale = radius;
  110546. },
  110547. enumerable: true,
  110548. configurable: true
  110549. });
  110550. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  110551. /**
  110552. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  110553. */
  110554. get: function () {
  110555. return this._positionScale;
  110556. },
  110557. /**
  110558. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  110559. */
  110560. set: function (scale) {
  110561. this._positionScale = scale;
  110562. },
  110563. enumerable: true,
  110564. configurable: true
  110565. });
  110566. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  110567. /**
  110568. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  110569. * behaviour is triggered, in radians.
  110570. */
  110571. get: function () {
  110572. return this._defaultElevation;
  110573. },
  110574. /**
  110575. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  110576. * behaviour is triggered, in radians.
  110577. */
  110578. set: function (elevation) {
  110579. this._defaultElevation = elevation;
  110580. },
  110581. enumerable: true,
  110582. configurable: true
  110583. });
  110584. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  110585. /**
  110586. * Gets the time (in milliseconds) taken to return to the default beta position.
  110587. * Negative value indicates camera should not return to default.
  110588. */
  110589. get: function () {
  110590. return this._elevationReturnTime;
  110591. },
  110592. /**
  110593. * Sets the time (in milliseconds) taken to return to the default beta position.
  110594. * Negative value indicates camera should not return to default.
  110595. */
  110596. set: function (speed) {
  110597. this._elevationReturnTime = speed;
  110598. },
  110599. enumerable: true,
  110600. configurable: true
  110601. });
  110602. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  110603. /**
  110604. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  110605. */
  110606. get: function () {
  110607. return this._elevationReturnWaitTime;
  110608. },
  110609. /**
  110610. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  110611. */
  110612. set: function (time) {
  110613. this._elevationReturnWaitTime = time;
  110614. },
  110615. enumerable: true,
  110616. configurable: true
  110617. });
  110618. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  110619. /**
  110620. * Gets the flag that indicates if user zooming should stop animation.
  110621. */
  110622. get: function () {
  110623. return this._zoomStopsAnimation;
  110624. },
  110625. /**
  110626. * Sets the flag that indicates if user zooming should stop animation.
  110627. */
  110628. set: function (flag) {
  110629. this._zoomStopsAnimation = flag;
  110630. },
  110631. enumerable: true,
  110632. configurable: true
  110633. });
  110634. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  110635. /**
  110636. * Gets the transition time when framing the mesh, in milliseconds
  110637. */
  110638. get: function () {
  110639. return this._framingTime;
  110640. },
  110641. /**
  110642. * Sets the transition time when framing the mesh, in milliseconds
  110643. */
  110644. set: function (time) {
  110645. this._framingTime = time;
  110646. },
  110647. enumerable: true,
  110648. configurable: true
  110649. });
  110650. /**
  110651. * Initializes the behavior.
  110652. */
  110653. FramingBehavior.prototype.init = function () {
  110654. // Do notihng
  110655. };
  110656. /**
  110657. * Attaches the behavior to its arc rotate camera.
  110658. * @param camera Defines the camera to attach the behavior to
  110659. */
  110660. FramingBehavior.prototype.attach = function (camera) {
  110661. var _this = this;
  110662. this._attachedCamera = camera;
  110663. var scene = this._attachedCamera.getScene();
  110664. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  110665. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  110666. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  110667. _this._isPointerDown = true;
  110668. return;
  110669. }
  110670. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  110671. _this._isPointerDown = false;
  110672. }
  110673. });
  110674. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  110675. if (mesh) {
  110676. _this.zoomOnMesh(mesh);
  110677. }
  110678. });
  110679. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  110680. // Stop the animation if there is user interaction and the animation should stop for this interaction
  110681. _this._applyUserInteraction();
  110682. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  110683. // back to the default position after a given timeout
  110684. _this._maintainCameraAboveGround();
  110685. });
  110686. };
  110687. /**
  110688. * Detaches the behavior from its current arc rotate camera.
  110689. */
  110690. FramingBehavior.prototype.detach = function () {
  110691. if (!this._attachedCamera) {
  110692. return;
  110693. }
  110694. var scene = this._attachedCamera.getScene();
  110695. if (this._onPrePointerObservableObserver) {
  110696. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  110697. }
  110698. if (this._onAfterCheckInputsObserver) {
  110699. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  110700. }
  110701. if (this._onMeshTargetChangedObserver) {
  110702. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  110703. }
  110704. this._attachedCamera = null;
  110705. };
  110706. /**
  110707. * Targets the given mesh and updates zoom level accordingly.
  110708. * @param mesh The mesh to target.
  110709. * @param radius Optional. If a cached radius position already exists, overrides default.
  110710. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  110711. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110712. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110713. */
  110714. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  110715. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110716. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110717. mesh.computeWorldMatrix(true);
  110718. var boundingBox = mesh.getBoundingInfo().boundingBox;
  110719. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  110720. };
  110721. /**
  110722. * Targets the given mesh with its children and updates zoom level accordingly.
  110723. * @param mesh The mesh to target.
  110724. * @param radius Optional. If a cached radius position already exists, overrides default.
  110725. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  110726. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110727. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110728. */
  110729. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  110730. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110731. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110732. mesh.computeWorldMatrix(true);
  110733. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  110734. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  110735. };
  110736. /**
  110737. * Targets the given meshes with their children and updates zoom level accordingly.
  110738. * @param meshes The mesh to target.
  110739. * @param radius Optional. If a cached radius position already exists, overrides default.
  110740. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  110741. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110742. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110743. */
  110744. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  110745. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110746. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110747. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  110748. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  110749. for (var i = 0; i < meshes.length; i++) {
  110750. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  110751. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  110752. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  110753. }
  110754. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  110755. };
  110756. /**
  110757. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  110758. * @param minimumWorld Determines the smaller position of the bounding box extend
  110759. * @param maximumWorld Determines the bigger position of the bounding box extend
  110760. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110761. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110762. */
  110763. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  110764. var _this = this;
  110765. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110766. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110767. var zoomTarget;
  110768. if (!this._attachedCamera) {
  110769. return;
  110770. }
  110771. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  110772. var bottom = minimumWorld.y;
  110773. var top = maximumWorld.y;
  110774. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  110775. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  110776. if (focusOnOriginXZ) {
  110777. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  110778. }
  110779. else {
  110780. var centerWorld = minimumWorld.add(radiusWorld);
  110781. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  110782. }
  110783. if (!this._vectorTransition) {
  110784. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  110785. }
  110786. this._betaIsAnimating = true;
  110787. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  110788. if (animatable) {
  110789. this._animatables.push(animatable);
  110790. }
  110791. // sets the radius and lower radius bounds
  110792. // Small delta ensures camera is not always at lower zoom limit.
  110793. var radius = 0;
  110794. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  110795. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  110796. if (this.autoCorrectCameraLimitsAndSensibility) {
  110797. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  110798. }
  110799. radius = position;
  110800. }
  110801. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  110802. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  110803. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  110804. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  110805. }
  110806. }
  110807. // Set sensibilities
  110808. if (this.autoCorrectCameraLimitsAndSensibility) {
  110809. var extend = maximumWorld.subtract(minimumWorld).length();
  110810. this._attachedCamera.panningSensibility = 5000 / extend;
  110811. this._attachedCamera.wheelPrecision = 100 / radius;
  110812. }
  110813. // transition to new radius
  110814. if (!this._radiusTransition) {
  110815. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  110816. }
  110817. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  110818. _this.stopAllAnimations();
  110819. if (onAnimationEnd) {
  110820. onAnimationEnd();
  110821. }
  110822. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  110823. _this._attachedCamera.storeState();
  110824. }
  110825. });
  110826. if (animatable) {
  110827. this._animatables.push(animatable);
  110828. }
  110829. };
  110830. /**
  110831. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  110832. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  110833. * frustum width.
  110834. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  110835. * to fully enclose the mesh in the viewing frustum.
  110836. */
  110837. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  110838. var size = maximumWorld.subtract(minimumWorld);
  110839. var boxVectorGlobalDiagonal = size.length();
  110840. var frustumSlope = this._getFrustumSlope();
  110841. // Formula for setting distance
  110842. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  110843. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  110844. // Horizon distance
  110845. var radius = radiusWithoutFraming * this._radiusScale;
  110846. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  110847. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  110848. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  110849. var camera = this._attachedCamera;
  110850. if (!camera) {
  110851. return 0;
  110852. }
  110853. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  110854. // Don't exceed the requested limit
  110855. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  110856. }
  110857. // Don't exceed the upper radius limit
  110858. if (camera.upperRadiusLimit) {
  110859. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  110860. }
  110861. return distance;
  110862. };
  110863. /**
  110864. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  110865. * is automatically returned to its default position (expected to be above ground plane).
  110866. */
  110867. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  110868. var _this = this;
  110869. if (this._elevationReturnTime < 0) {
  110870. return;
  110871. }
  110872. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  110873. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  110874. var limitBeta = Math.PI * 0.5;
  110875. // Bring the camera back up if below the ground plane
  110876. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  110877. this._betaIsAnimating = true;
  110878. //Transition to new position
  110879. this.stopAllAnimations();
  110880. if (!this._betaTransition) {
  110881. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  110882. }
  110883. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  110884. _this._clearAnimationLocks();
  110885. _this.stopAllAnimations();
  110886. });
  110887. if (animatabe) {
  110888. this._animatables.push(animatabe);
  110889. }
  110890. }
  110891. };
  110892. /**
  110893. * Returns the frustum slope based on the canvas ratio and camera FOV
  110894. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  110895. */
  110896. FramingBehavior.prototype._getFrustumSlope = function () {
  110897. // Calculate the viewport ratio
  110898. // Aspect Ratio is Height/Width.
  110899. var camera = this._attachedCamera;
  110900. if (!camera) {
  110901. return BABYLON.Vector2.Zero();
  110902. }
  110903. var engine = camera.getScene().getEngine();
  110904. var aspectRatio = engine.getAspectRatio(camera);
  110905. // Camera FOV is the vertical field of view (top-bottom) in radians.
  110906. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  110907. var frustumSlopeY = Math.tan(camera.fov / 2);
  110908. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  110909. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  110910. // along the forward vector.
  110911. var frustumSlopeX = frustumSlopeY * aspectRatio;
  110912. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  110913. };
  110914. /**
  110915. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  110916. */
  110917. FramingBehavior.prototype._clearAnimationLocks = function () {
  110918. this._betaIsAnimating = false;
  110919. };
  110920. /**
  110921. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  110922. */
  110923. FramingBehavior.prototype._applyUserInteraction = function () {
  110924. if (this.isUserIsMoving) {
  110925. this._lastInteractionTime = BABYLON.Tools.Now;
  110926. this.stopAllAnimations();
  110927. this._clearAnimationLocks();
  110928. }
  110929. };
  110930. /**
  110931. * Stops and removes all animations that have been applied to the camera
  110932. */
  110933. FramingBehavior.prototype.stopAllAnimations = function () {
  110934. if (this._attachedCamera) {
  110935. this._attachedCamera.animations = [];
  110936. }
  110937. while (this._animatables.length) {
  110938. if (this._animatables[0]) {
  110939. this._animatables[0].onAnimationEnd = null;
  110940. this._animatables[0].stop();
  110941. }
  110942. this._animatables.shift();
  110943. }
  110944. };
  110945. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  110946. /**
  110947. * Gets a value indicating if the user is moving the camera
  110948. */
  110949. get: function () {
  110950. if (!this._attachedCamera) {
  110951. return false;
  110952. }
  110953. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  110954. this._attachedCamera.inertialBetaOffset !== 0 ||
  110955. this._attachedCamera.inertialRadiusOffset !== 0 ||
  110956. this._attachedCamera.inertialPanningX !== 0 ||
  110957. this._attachedCamera.inertialPanningY !== 0 ||
  110958. this._isPointerDown;
  110959. },
  110960. enumerable: true,
  110961. configurable: true
  110962. });
  110963. /**
  110964. * The easing function used by animations
  110965. */
  110966. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  110967. /**
  110968. * The easing mode used by animations
  110969. */
  110970. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  110971. // Statics
  110972. /**
  110973. * The camera can move all the way towards the mesh.
  110974. */
  110975. FramingBehavior.IgnoreBoundsSizeMode = 0;
  110976. /**
  110977. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  110978. */
  110979. FramingBehavior.FitFrustumSidesMode = 1;
  110980. return FramingBehavior;
  110981. }());
  110982. BABYLON.FramingBehavior = FramingBehavior;
  110983. })(BABYLON || (BABYLON = {}));
  110984. //# sourceMappingURL=babylon.framingBehavior.js.map
  110985. var BABYLON;
  110986. (function (BABYLON) {
  110987. /**
  110988. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  110989. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  110990. */
  110991. var BouncingBehavior = /** @class */ (function () {
  110992. function BouncingBehavior() {
  110993. /**
  110994. * The duration of the animation, in milliseconds
  110995. */
  110996. this.transitionDuration = 450;
  110997. /**
  110998. * Length of the distance animated by the transition when lower radius is reached
  110999. */
  111000. this.lowerRadiusTransitionRange = 2;
  111001. /**
  111002. * Length of the distance animated by the transition when upper radius is reached
  111003. */
  111004. this.upperRadiusTransitionRange = -2;
  111005. this._autoTransitionRange = false;
  111006. // Animations
  111007. this._radiusIsAnimating = false;
  111008. this._radiusBounceTransition = null;
  111009. this._animatables = new Array();
  111010. }
  111011. Object.defineProperty(BouncingBehavior.prototype, "name", {
  111012. /**
  111013. * Gets the name of the behavior.
  111014. */
  111015. get: function () {
  111016. return "Bouncing";
  111017. },
  111018. enumerable: true,
  111019. configurable: true
  111020. });
  111021. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  111022. /**
  111023. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  111024. */
  111025. get: function () {
  111026. return this._autoTransitionRange;
  111027. },
  111028. /**
  111029. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  111030. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  111031. */
  111032. set: function (value) {
  111033. var _this = this;
  111034. if (this._autoTransitionRange === value) {
  111035. return;
  111036. }
  111037. this._autoTransitionRange = value;
  111038. var camera = this._attachedCamera;
  111039. if (!camera) {
  111040. return;
  111041. }
  111042. if (value) {
  111043. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  111044. if (!mesh) {
  111045. return;
  111046. }
  111047. mesh.computeWorldMatrix(true);
  111048. var diagonal = mesh.getBoundingInfo().diagonalLength;
  111049. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  111050. _this.upperRadiusTransitionRange = diagonal * 0.05;
  111051. });
  111052. }
  111053. else if (this._onMeshTargetChangedObserver) {
  111054. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  111055. }
  111056. },
  111057. enumerable: true,
  111058. configurable: true
  111059. });
  111060. /**
  111061. * Initializes the behavior.
  111062. */
  111063. BouncingBehavior.prototype.init = function () {
  111064. // Do notihng
  111065. };
  111066. /**
  111067. * Attaches the behavior to its arc rotate camera.
  111068. * @param camera Defines the camera to attach the behavior to
  111069. */
  111070. BouncingBehavior.prototype.attach = function (camera) {
  111071. var _this = this;
  111072. this._attachedCamera = camera;
  111073. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  111074. if (!_this._attachedCamera) {
  111075. return;
  111076. }
  111077. // Add the bounce animation to the lower radius limit
  111078. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  111079. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  111080. }
  111081. // Add the bounce animation to the upper radius limit
  111082. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  111083. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  111084. }
  111085. });
  111086. };
  111087. /**
  111088. * Detaches the behavior from its current arc rotate camera.
  111089. */
  111090. BouncingBehavior.prototype.detach = function () {
  111091. if (!this._attachedCamera) {
  111092. return;
  111093. }
  111094. if (this._onAfterCheckInputsObserver) {
  111095. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  111096. }
  111097. if (this._onMeshTargetChangedObserver) {
  111098. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  111099. }
  111100. this._attachedCamera = null;
  111101. };
  111102. /**
  111103. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  111104. * @param radiusLimit The limit to check against.
  111105. * @return Bool to indicate if at limit.
  111106. */
  111107. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  111108. if (!this._attachedCamera) {
  111109. return false;
  111110. }
  111111. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  111112. return true;
  111113. }
  111114. return false;
  111115. };
  111116. /**
  111117. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  111118. * @param radiusDelta The delta by which to animate to. Can be negative.
  111119. */
  111120. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  111121. var _this = this;
  111122. if (!this._attachedCamera) {
  111123. return;
  111124. }
  111125. if (!this._radiusBounceTransition) {
  111126. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  111127. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  111128. }
  111129. // Prevent zoom until bounce has completed
  111130. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  111131. this._attachedCamera.wheelPrecision = Infinity;
  111132. this._attachedCamera.inertialRadiusOffset = 0;
  111133. // Animate to the radius limit
  111134. this.stopAllAnimations();
  111135. this._radiusIsAnimating = true;
  111136. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  111137. if (animatable) {
  111138. this._animatables.push(animatable);
  111139. }
  111140. };
  111141. /**
  111142. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  111143. */
  111144. BouncingBehavior.prototype._clearAnimationLocks = function () {
  111145. this._radiusIsAnimating = false;
  111146. if (this._attachedCamera) {
  111147. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  111148. }
  111149. };
  111150. /**
  111151. * Stops and removes all animations that have been applied to the camera
  111152. */
  111153. BouncingBehavior.prototype.stopAllAnimations = function () {
  111154. if (this._attachedCamera) {
  111155. this._attachedCamera.animations = [];
  111156. }
  111157. while (this._animatables.length) {
  111158. this._animatables[0].onAnimationEnd = null;
  111159. this._animatables[0].stop();
  111160. this._animatables.shift();
  111161. }
  111162. };
  111163. /**
  111164. * The easing function used by animations
  111165. */
  111166. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  111167. /**
  111168. * The easing mode used by animations
  111169. */
  111170. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  111171. return BouncingBehavior;
  111172. }());
  111173. BABYLON.BouncingBehavior = BouncingBehavior;
  111174. })(BABYLON || (BABYLON = {}));
  111175. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  111176. var BABYLON;
  111177. (function (BABYLON) {
  111178. /**
  111179. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  111180. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  111181. */
  111182. var AutoRotationBehavior = /** @class */ (function () {
  111183. function AutoRotationBehavior() {
  111184. this._zoomStopsAnimation = false;
  111185. this._idleRotationSpeed = 0.05;
  111186. this._idleRotationWaitTime = 2000;
  111187. this._idleRotationSpinupTime = 2000;
  111188. this._isPointerDown = false;
  111189. this._lastFrameTime = null;
  111190. this._lastInteractionTime = -Infinity;
  111191. this._cameraRotationSpeed = 0;
  111192. this._lastFrameRadius = 0;
  111193. }
  111194. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  111195. /**
  111196. * Gets the name of the behavior.
  111197. */
  111198. get: function () {
  111199. return "AutoRotation";
  111200. },
  111201. enumerable: true,
  111202. configurable: true
  111203. });
  111204. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  111205. /**
  111206. * Gets the flag that indicates if user zooming should stop animation.
  111207. */
  111208. get: function () {
  111209. return this._zoomStopsAnimation;
  111210. },
  111211. /**
  111212. * Sets the flag that indicates if user zooming should stop animation.
  111213. */
  111214. set: function (flag) {
  111215. this._zoomStopsAnimation = flag;
  111216. },
  111217. enumerable: true,
  111218. configurable: true
  111219. });
  111220. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  111221. /**
  111222. * Gets the default speed at which the camera rotates around the model.
  111223. */
  111224. get: function () {
  111225. return this._idleRotationSpeed;
  111226. },
  111227. /**
  111228. * Sets the default speed at which the camera rotates around the model.
  111229. */
  111230. set: function (speed) {
  111231. this._idleRotationSpeed = speed;
  111232. },
  111233. enumerable: true,
  111234. configurable: true
  111235. });
  111236. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  111237. /**
  111238. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  111239. */
  111240. get: function () {
  111241. return this._idleRotationWaitTime;
  111242. },
  111243. /**
  111244. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  111245. */
  111246. set: function (time) {
  111247. this._idleRotationWaitTime = time;
  111248. },
  111249. enumerable: true,
  111250. configurable: true
  111251. });
  111252. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  111253. /**
  111254. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  111255. */
  111256. get: function () {
  111257. return this._idleRotationSpinupTime;
  111258. },
  111259. /**
  111260. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  111261. */
  111262. set: function (time) {
  111263. this._idleRotationSpinupTime = time;
  111264. },
  111265. enumerable: true,
  111266. configurable: true
  111267. });
  111268. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  111269. /**
  111270. * Gets a value indicating if the camera is currently rotating because of this behavior
  111271. */
  111272. get: function () {
  111273. return Math.abs(this._cameraRotationSpeed) > 0;
  111274. },
  111275. enumerable: true,
  111276. configurable: true
  111277. });
  111278. /**
  111279. * Initializes the behavior.
  111280. */
  111281. AutoRotationBehavior.prototype.init = function () {
  111282. // Do notihng
  111283. };
  111284. /**
  111285. * Attaches the behavior to its arc rotate camera.
  111286. * @param camera Defines the camera to attach the behavior to
  111287. */
  111288. AutoRotationBehavior.prototype.attach = function (camera) {
  111289. var _this = this;
  111290. this._attachedCamera = camera;
  111291. var scene = this._attachedCamera.getScene();
  111292. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  111293. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  111294. _this._isPointerDown = true;
  111295. return;
  111296. }
  111297. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  111298. _this._isPointerDown = false;
  111299. }
  111300. });
  111301. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  111302. var now = BABYLON.Tools.Now;
  111303. var dt = 0;
  111304. if (_this._lastFrameTime != null) {
  111305. dt = now - _this._lastFrameTime;
  111306. }
  111307. _this._lastFrameTime = now;
  111308. // Stop the animation if there is user interaction and the animation should stop for this interaction
  111309. _this._applyUserInteraction();
  111310. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  111311. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  111312. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  111313. // Step camera rotation by rotation speed
  111314. if (_this._attachedCamera) {
  111315. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  111316. }
  111317. });
  111318. };
  111319. /**
  111320. * Detaches the behavior from its current arc rotate camera.
  111321. */
  111322. AutoRotationBehavior.prototype.detach = function () {
  111323. if (!this._attachedCamera) {
  111324. return;
  111325. }
  111326. var scene = this._attachedCamera.getScene();
  111327. if (this._onPrePointerObservableObserver) {
  111328. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  111329. }
  111330. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  111331. this._attachedCamera = null;
  111332. };
  111333. /**
  111334. * Returns true if user is scrolling.
  111335. * @return true if user is scrolling.
  111336. */
  111337. AutoRotationBehavior.prototype._userIsZooming = function () {
  111338. if (!this._attachedCamera) {
  111339. return false;
  111340. }
  111341. return this._attachedCamera.inertialRadiusOffset !== 0;
  111342. };
  111343. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  111344. if (!this._attachedCamera) {
  111345. return false;
  111346. }
  111347. var zoomHasHitLimit = false;
  111348. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  111349. zoomHasHitLimit = true;
  111350. }
  111351. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  111352. this._lastFrameRadius = this._attachedCamera.radius;
  111353. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  111354. };
  111355. /**
  111356. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  111357. */
  111358. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  111359. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  111360. this._lastInteractionTime = BABYLON.Tools.Now;
  111361. }
  111362. };
  111363. // Tools
  111364. AutoRotationBehavior.prototype._userIsMoving = function () {
  111365. if (!this._attachedCamera) {
  111366. return false;
  111367. }
  111368. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  111369. this._attachedCamera.inertialBetaOffset !== 0 ||
  111370. this._attachedCamera.inertialRadiusOffset !== 0 ||
  111371. this._attachedCamera.inertialPanningX !== 0 ||
  111372. this._attachedCamera.inertialPanningY !== 0 ||
  111373. this._isPointerDown;
  111374. };
  111375. return AutoRotationBehavior;
  111376. }());
  111377. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  111378. })(BABYLON || (BABYLON = {}));
  111379. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  111380. var BABYLON;
  111381. (function (BABYLON) {
  111382. var NullEngineOptions = /** @class */ (function () {
  111383. function NullEngineOptions() {
  111384. this.renderWidth = 512;
  111385. this.renderHeight = 256;
  111386. this.textureSize = 512;
  111387. this.deterministicLockstep = false;
  111388. this.lockstepMaxSteps = 4;
  111389. }
  111390. return NullEngineOptions;
  111391. }());
  111392. BABYLON.NullEngineOptions = NullEngineOptions;
  111393. /**
  111394. * The null engine class provides support for headless version of babylon.js.
  111395. * This can be used in server side scenario or for testing purposes
  111396. */
  111397. var NullEngine = /** @class */ (function (_super) {
  111398. __extends(NullEngine, _super);
  111399. function NullEngine(options) {
  111400. if (options === void 0) { options = new NullEngineOptions(); }
  111401. var _this = _super.call(this, null) || this;
  111402. if (options.deterministicLockstep === undefined) {
  111403. options.deterministicLockstep = false;
  111404. }
  111405. if (options.lockstepMaxSteps === undefined) {
  111406. options.lockstepMaxSteps = 4;
  111407. }
  111408. _this._options = options;
  111409. // Init caps
  111410. // We consider we are on a webgl1 capable device
  111411. _this._caps = new BABYLON.EngineCapabilities();
  111412. _this._caps.maxTexturesImageUnits = 16;
  111413. _this._caps.maxVertexTextureImageUnits = 16;
  111414. _this._caps.maxTextureSize = 512;
  111415. _this._caps.maxCubemapTextureSize = 512;
  111416. _this._caps.maxRenderTextureSize = 512;
  111417. _this._caps.maxVertexAttribs = 16;
  111418. _this._caps.maxVaryingVectors = 16;
  111419. _this._caps.maxFragmentUniformVectors = 16;
  111420. _this._caps.maxVertexUniformVectors = 16;
  111421. // Extensions
  111422. _this._caps.standardDerivatives = false;
  111423. _this._caps.astc = null;
  111424. _this._caps.s3tc = null;
  111425. _this._caps.pvrtc = null;
  111426. _this._caps.etc1 = null;
  111427. _this._caps.etc2 = null;
  111428. _this._caps.textureAnisotropicFilterExtension = null;
  111429. _this._caps.maxAnisotropy = 0;
  111430. _this._caps.uintIndices = false;
  111431. _this._caps.fragmentDepthSupported = false;
  111432. _this._caps.highPrecisionShaderSupported = true;
  111433. _this._caps.colorBufferFloat = false;
  111434. _this._caps.textureFloat = false;
  111435. _this._caps.textureFloatLinearFiltering = false;
  111436. _this._caps.textureFloatRender = false;
  111437. _this._caps.textureHalfFloat = false;
  111438. _this._caps.textureHalfFloatLinearFiltering = false;
  111439. _this._caps.textureHalfFloatRender = false;
  111440. _this._caps.textureLOD = false;
  111441. _this._caps.drawBuffersExtension = false;
  111442. _this._caps.depthTextureExtension = false;
  111443. _this._caps.vertexArrayObject = false;
  111444. _this._caps.instancedArrays = false;
  111445. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  111446. // Wrappers
  111447. if (typeof URL === "undefined") {
  111448. URL = {
  111449. createObjectURL: function () { },
  111450. revokeObjectURL: function () { }
  111451. };
  111452. }
  111453. if (typeof Blob === "undefined") {
  111454. Blob = function () { };
  111455. }
  111456. return _this;
  111457. }
  111458. NullEngine.prototype.isDeterministicLockStep = function () {
  111459. return this._options.deterministicLockstep;
  111460. };
  111461. NullEngine.prototype.getLockstepMaxSteps = function () {
  111462. return this._options.lockstepMaxSteps;
  111463. };
  111464. NullEngine.prototype.getHardwareScalingLevel = function () {
  111465. return 1.0;
  111466. };
  111467. NullEngine.prototype.createVertexBuffer = function (vertices) {
  111468. return {
  111469. capacity: 0,
  111470. references: 1,
  111471. is32Bits: false
  111472. };
  111473. };
  111474. NullEngine.prototype.createIndexBuffer = function (indices) {
  111475. return {
  111476. capacity: 0,
  111477. references: 1,
  111478. is32Bits: false
  111479. };
  111480. };
  111481. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  111482. if (stencil === void 0) { stencil = false; }
  111483. };
  111484. NullEngine.prototype.getRenderWidth = function (useScreen) {
  111485. if (useScreen === void 0) { useScreen = false; }
  111486. if (!useScreen && this._currentRenderTarget) {
  111487. return this._currentRenderTarget.width;
  111488. }
  111489. return this._options.renderWidth;
  111490. };
  111491. NullEngine.prototype.getRenderHeight = function (useScreen) {
  111492. if (useScreen === void 0) { useScreen = false; }
  111493. if (!useScreen && this._currentRenderTarget) {
  111494. return this._currentRenderTarget.height;
  111495. }
  111496. return this._options.renderHeight;
  111497. };
  111498. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  111499. this._cachedViewport = viewport;
  111500. };
  111501. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  111502. return {
  111503. transformFeedback: null,
  111504. __SPECTOR_rebuildProgram: null
  111505. };
  111506. };
  111507. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  111508. return [];
  111509. };
  111510. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  111511. return [];
  111512. };
  111513. NullEngine.prototype.bindSamplers = function (effect) {
  111514. this._currentEffect = null;
  111515. };
  111516. NullEngine.prototype.enableEffect = function (effect) {
  111517. this._currentEffect = effect;
  111518. if (effect.onBind) {
  111519. effect.onBind(effect);
  111520. }
  111521. if (effect._onBindObservable) {
  111522. effect._onBindObservable.notifyObservers(effect);
  111523. }
  111524. };
  111525. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  111526. if (zOffset === void 0) { zOffset = 0; }
  111527. if (reverseSide === void 0) { reverseSide = false; }
  111528. };
  111529. NullEngine.prototype.setIntArray = function (uniform, array) {
  111530. };
  111531. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  111532. };
  111533. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  111534. };
  111535. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  111536. };
  111537. NullEngine.prototype.setFloatArray = function (uniform, array) {
  111538. };
  111539. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  111540. };
  111541. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  111542. };
  111543. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  111544. };
  111545. NullEngine.prototype.setArray = function (uniform, array) {
  111546. };
  111547. NullEngine.prototype.setArray2 = function (uniform, array) {
  111548. };
  111549. NullEngine.prototype.setArray3 = function (uniform, array) {
  111550. };
  111551. NullEngine.prototype.setArray4 = function (uniform, array) {
  111552. };
  111553. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  111554. };
  111555. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  111556. };
  111557. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  111558. };
  111559. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  111560. };
  111561. NullEngine.prototype.setFloat = function (uniform, value) {
  111562. };
  111563. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  111564. };
  111565. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  111566. };
  111567. NullEngine.prototype.setBool = function (uniform, bool) {
  111568. };
  111569. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  111570. };
  111571. NullEngine.prototype.setColor3 = function (uniform, color3) {
  111572. };
  111573. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  111574. };
  111575. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  111576. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  111577. if (this._alphaMode === mode) {
  111578. return;
  111579. }
  111580. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  111581. if (!noDepthWriteChange) {
  111582. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  111583. }
  111584. this._alphaMode = mode;
  111585. };
  111586. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  111587. };
  111588. NullEngine.prototype.wipeCaches = function (bruteForce) {
  111589. if (this.preventCacheWipeBetweenFrames) {
  111590. return;
  111591. }
  111592. this.resetTextureCache();
  111593. this._currentEffect = null;
  111594. if (bruteForce) {
  111595. this._currentProgram = null;
  111596. this._stencilState.reset();
  111597. this._depthCullingState.reset();
  111598. this._alphaState.reset();
  111599. }
  111600. this._cachedVertexBuffers = null;
  111601. this._cachedIndexBuffer = null;
  111602. this._cachedEffectForVertexBuffers = null;
  111603. };
  111604. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  111605. };
  111606. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  111607. };
  111608. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  111609. };
  111610. /** @hidden */
  111611. NullEngine.prototype._createTexture = function () {
  111612. return {};
  111613. };
  111614. /** @hidden */
  111615. NullEngine.prototype._releaseTexture = function (texture) {
  111616. };
  111617. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  111618. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  111619. if (onLoad === void 0) { onLoad = null; }
  111620. if (onError === void 0) { onError = null; }
  111621. if (buffer === void 0) { buffer = null; }
  111622. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  111623. var url = String(urlArg);
  111624. texture.url = url;
  111625. texture.generateMipMaps = !noMipmap;
  111626. texture.samplingMode = samplingMode;
  111627. texture.invertY = invertY;
  111628. texture.baseWidth = this._options.textureSize;
  111629. texture.baseHeight = this._options.textureSize;
  111630. texture.width = this._options.textureSize;
  111631. texture.height = this._options.textureSize;
  111632. if (format) {
  111633. texture.format = format;
  111634. }
  111635. texture.isReady = true;
  111636. if (onLoad) {
  111637. onLoad();
  111638. }
  111639. this._internalTexturesCache.push(texture);
  111640. return texture;
  111641. };
  111642. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  111643. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  111644. if (options !== undefined && typeof options === "object") {
  111645. fullOptions.generateMipMaps = options.generateMipMaps;
  111646. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  111647. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  111648. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  111649. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  111650. }
  111651. else {
  111652. fullOptions.generateMipMaps = options;
  111653. fullOptions.generateDepthBuffer = true;
  111654. fullOptions.generateStencilBuffer = false;
  111655. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  111656. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  111657. }
  111658. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  111659. var width = size.width || size;
  111660. var height = size.height || size;
  111661. texture._depthStencilBuffer = {};
  111662. texture._framebuffer = {};
  111663. texture.baseWidth = width;
  111664. texture.baseHeight = height;
  111665. texture.width = width;
  111666. texture.height = height;
  111667. texture.isReady = true;
  111668. texture.samples = 1;
  111669. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  111670. texture.samplingMode = fullOptions.samplingMode;
  111671. texture.type = fullOptions.type;
  111672. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  111673. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  111674. this._internalTexturesCache.push(texture);
  111675. return texture;
  111676. };
  111677. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  111678. texture.samplingMode = samplingMode;
  111679. };
  111680. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  111681. if (this._currentRenderTarget) {
  111682. this.unBindFramebuffer(this._currentRenderTarget);
  111683. }
  111684. this._currentRenderTarget = texture;
  111685. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  111686. if (this._cachedViewport && !forceFullscreenViewport) {
  111687. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  111688. }
  111689. };
  111690. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  111691. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  111692. this._currentRenderTarget = null;
  111693. if (onBeforeUnbind) {
  111694. if (texture._MSAAFramebuffer) {
  111695. this._currentFramebuffer = texture._framebuffer;
  111696. }
  111697. onBeforeUnbind();
  111698. }
  111699. this._currentFramebuffer = null;
  111700. };
  111701. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  111702. var vbo = {
  111703. capacity: 1,
  111704. references: 1,
  111705. is32Bits: false
  111706. };
  111707. return vbo;
  111708. };
  111709. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  111710. if (premulAlpha === void 0) { premulAlpha = false; }
  111711. };
  111712. /**
  111713. * @hidden
  111714. * Get the current error code of the webGL context
  111715. * @returns the error code
  111716. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  111717. */
  111718. NullEngine.prototype.getError = function () {
  111719. return 0;
  111720. };
  111721. /** @hidden */
  111722. NullEngine.prototype._getUnpackAlignement = function () {
  111723. return 1;
  111724. };
  111725. /** @hidden */
  111726. NullEngine.prototype._unpackFlipY = function (value) {
  111727. };
  111728. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  111729. if (offset === void 0) { offset = 0; }
  111730. };
  111731. /**
  111732. * Updates a dynamic vertex buffer.
  111733. * @param vertexBuffer the vertex buffer to update
  111734. * @param data the data used to update the vertex buffer
  111735. * @param byteOffset the byte offset of the data (optional)
  111736. * @param byteLength the byte length of the data (optional)
  111737. */
  111738. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  111739. };
  111740. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  111741. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  111742. this._boundTexturesCache[this._activeChannel] = texture;
  111743. return true;
  111744. }
  111745. return false;
  111746. };
  111747. /** @hidden */
  111748. NullEngine.prototype._bindTexture = function (channel, texture) {
  111749. if (channel < 0) {
  111750. return;
  111751. }
  111752. this._bindTextureDirectly(0, texture);
  111753. };
  111754. /** @hidden */
  111755. NullEngine.prototype._releaseBuffer = function (buffer) {
  111756. buffer.references--;
  111757. if (buffer.references === 0) {
  111758. return true;
  111759. }
  111760. return false;
  111761. };
  111762. NullEngine.prototype.releaseEffects = function () {
  111763. };
  111764. NullEngine.prototype.displayLoadingUI = function () {
  111765. };
  111766. NullEngine.prototype.hideLoadingUI = function () {
  111767. };
  111768. /** @hidden */
  111769. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  111770. if (faceIndex === void 0) { faceIndex = 0; }
  111771. if (lod === void 0) { lod = 0; }
  111772. };
  111773. /** @hidden */
  111774. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  111775. if (faceIndex === void 0) { faceIndex = 0; }
  111776. if (lod === void 0) { lod = 0; }
  111777. };
  111778. /** @hidden */
  111779. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  111780. if (faceIndex === void 0) { faceIndex = 0; }
  111781. if (lod === void 0) { lod = 0; }
  111782. };
  111783. /** @hidden */
  111784. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  111785. if (faceIndex === void 0) { faceIndex = 0; }
  111786. if (lod === void 0) { lod = 0; }
  111787. };
  111788. return NullEngine;
  111789. }(BABYLON.Engine));
  111790. BABYLON.NullEngine = NullEngine;
  111791. })(BABYLON || (BABYLON = {}));
  111792. //# sourceMappingURL=babylon.nullEngine.js.map
  111793. var BABYLON;
  111794. (function (BABYLON) {
  111795. /**
  111796. * This class can be used to get instrumentation data from a Babylon engine
  111797. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  111798. */
  111799. var EngineInstrumentation = /** @class */ (function () {
  111800. /**
  111801. * Instantiates a new engine instrumentation.
  111802. * This class can be used to get instrumentation data from a Babylon engine
  111803. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  111804. * @param engine Defines the engine to instrument
  111805. */
  111806. function EngineInstrumentation(
  111807. /**
  111808. * Define the instrumented engine.
  111809. */
  111810. engine) {
  111811. this.engine = engine;
  111812. this._captureGPUFrameTime = false;
  111813. this._gpuFrameTime = new BABYLON.PerfCounter();
  111814. this._captureShaderCompilationTime = false;
  111815. this._shaderCompilationTime = new BABYLON.PerfCounter();
  111816. // Observers
  111817. this._onBeginFrameObserver = null;
  111818. this._onEndFrameObserver = null;
  111819. this._onBeforeShaderCompilationObserver = null;
  111820. this._onAfterShaderCompilationObserver = null;
  111821. }
  111822. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  111823. // Properties
  111824. /**
  111825. * Gets the perf counter used for GPU frame time
  111826. */
  111827. get: function () {
  111828. return this._gpuFrameTime;
  111829. },
  111830. enumerable: true,
  111831. configurable: true
  111832. });
  111833. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  111834. /**
  111835. * Gets the GPU frame time capture status
  111836. */
  111837. get: function () {
  111838. return this._captureGPUFrameTime;
  111839. },
  111840. /**
  111841. * Enable or disable the GPU frame time capture
  111842. */
  111843. set: function (value) {
  111844. var _this = this;
  111845. if (value === this._captureGPUFrameTime) {
  111846. return;
  111847. }
  111848. this._captureGPUFrameTime = value;
  111849. if (value) {
  111850. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  111851. if (!_this._gpuFrameTimeToken) {
  111852. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  111853. }
  111854. });
  111855. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  111856. if (!_this._gpuFrameTimeToken) {
  111857. return;
  111858. }
  111859. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  111860. if (time > -1) {
  111861. _this._gpuFrameTimeToken = null;
  111862. _this._gpuFrameTime.fetchNewFrame();
  111863. _this._gpuFrameTime.addCount(time, true);
  111864. }
  111865. });
  111866. }
  111867. else {
  111868. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  111869. this._onBeginFrameObserver = null;
  111870. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  111871. this._onEndFrameObserver = null;
  111872. }
  111873. },
  111874. enumerable: true,
  111875. configurable: true
  111876. });
  111877. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  111878. /**
  111879. * Gets the perf counter used for shader compilation time
  111880. */
  111881. get: function () {
  111882. return this._shaderCompilationTime;
  111883. },
  111884. enumerable: true,
  111885. configurable: true
  111886. });
  111887. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  111888. /**
  111889. * Gets the shader compilation time capture status
  111890. */
  111891. get: function () {
  111892. return this._captureShaderCompilationTime;
  111893. },
  111894. /**
  111895. * Enable or disable the shader compilation time capture
  111896. */
  111897. set: function (value) {
  111898. var _this = this;
  111899. if (value === this._captureShaderCompilationTime) {
  111900. return;
  111901. }
  111902. this._captureShaderCompilationTime = value;
  111903. if (value) {
  111904. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  111905. _this._shaderCompilationTime.fetchNewFrame();
  111906. _this._shaderCompilationTime.beginMonitoring();
  111907. });
  111908. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  111909. _this._shaderCompilationTime.endMonitoring();
  111910. });
  111911. }
  111912. else {
  111913. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  111914. this._onBeforeShaderCompilationObserver = null;
  111915. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  111916. this._onAfterShaderCompilationObserver = null;
  111917. }
  111918. },
  111919. enumerable: true,
  111920. configurable: true
  111921. });
  111922. /**
  111923. * Dispose and release associated resources.
  111924. */
  111925. EngineInstrumentation.prototype.dispose = function () {
  111926. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  111927. this._onBeginFrameObserver = null;
  111928. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  111929. this._onEndFrameObserver = null;
  111930. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  111931. this._onBeforeShaderCompilationObserver = null;
  111932. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  111933. this._onAfterShaderCompilationObserver = null;
  111934. this.engine = null;
  111935. };
  111936. return EngineInstrumentation;
  111937. }());
  111938. BABYLON.EngineInstrumentation = EngineInstrumentation;
  111939. })(BABYLON || (BABYLON = {}));
  111940. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  111941. var BABYLON;
  111942. (function (BABYLON) {
  111943. /**
  111944. * This class can be used to get instrumentation data from a Babylon engine
  111945. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  111946. */
  111947. var SceneInstrumentation = /** @class */ (function () {
  111948. /**
  111949. * Instantiates a new scene instrumentation.
  111950. * This class can be used to get instrumentation data from a Babylon engine
  111951. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  111952. * @param scene Defines the scene to instrument
  111953. */
  111954. function SceneInstrumentation(
  111955. /**
  111956. * Defines the scene to instrument
  111957. */
  111958. scene) {
  111959. var _this = this;
  111960. this.scene = scene;
  111961. this._captureActiveMeshesEvaluationTime = false;
  111962. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  111963. this._captureRenderTargetsRenderTime = false;
  111964. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  111965. this._captureFrameTime = false;
  111966. this._frameTime = new BABYLON.PerfCounter();
  111967. this._captureRenderTime = false;
  111968. this._renderTime = new BABYLON.PerfCounter();
  111969. this._captureInterFrameTime = false;
  111970. this._interFrameTime = new BABYLON.PerfCounter();
  111971. this._captureParticlesRenderTime = false;
  111972. this._particlesRenderTime = new BABYLON.PerfCounter();
  111973. this._captureSpritesRenderTime = false;
  111974. this._spritesRenderTime = new BABYLON.PerfCounter();
  111975. this._capturePhysicsTime = false;
  111976. this._physicsTime = new BABYLON.PerfCounter();
  111977. this._captureAnimationsTime = false;
  111978. this._animationsTime = new BABYLON.PerfCounter();
  111979. this._captureCameraRenderTime = false;
  111980. this._cameraRenderTime = new BABYLON.PerfCounter();
  111981. // Observers
  111982. this._onBeforeActiveMeshesEvaluationObserver = null;
  111983. this._onAfterActiveMeshesEvaluationObserver = null;
  111984. this._onBeforeRenderTargetsRenderObserver = null;
  111985. this._onAfterRenderTargetsRenderObserver = null;
  111986. this._onAfterRenderObserver = null;
  111987. this._onBeforeDrawPhaseObserver = null;
  111988. this._onAfterDrawPhaseObserver = null;
  111989. this._onBeforeAnimationsObserver = null;
  111990. this._onBeforeParticlesRenderingObserver = null;
  111991. this._onAfterParticlesRenderingObserver = null;
  111992. this._onBeforeSpritesRenderingObserver = null;
  111993. this._onAfterSpritesRenderingObserver = null;
  111994. this._onBeforePhysicsObserver = null;
  111995. this._onAfterPhysicsObserver = null;
  111996. this._onAfterAnimationsObserver = null;
  111997. this._onBeforeCameraRenderObserver = null;
  111998. this._onAfterCameraRenderObserver = null;
  111999. // Before render
  112000. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  112001. if (_this._captureActiveMeshesEvaluationTime) {
  112002. _this._activeMeshesEvaluationTime.fetchNewFrame();
  112003. }
  112004. if (_this._captureRenderTargetsRenderTime) {
  112005. _this._renderTargetsRenderTime.fetchNewFrame();
  112006. }
  112007. if (_this._captureFrameTime) {
  112008. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  112009. _this._frameTime.beginMonitoring();
  112010. }
  112011. if (_this._captureInterFrameTime) {
  112012. _this._interFrameTime.endMonitoring();
  112013. }
  112014. if (_this._captureParticlesRenderTime) {
  112015. _this._particlesRenderTime.fetchNewFrame();
  112016. }
  112017. if (_this._captureSpritesRenderTime) {
  112018. _this._spritesRenderTime.fetchNewFrame();
  112019. }
  112020. if (_this._captureAnimationsTime) {
  112021. _this._animationsTime.beginMonitoring();
  112022. }
  112023. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  112024. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  112025. });
  112026. // After render
  112027. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  112028. if (_this._captureFrameTime) {
  112029. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  112030. _this._frameTime.endMonitoring();
  112031. }
  112032. if (_this._captureRenderTime) {
  112033. _this._renderTime.endMonitoring(false);
  112034. }
  112035. if (_this._captureInterFrameTime) {
  112036. _this._interFrameTime.beginMonitoring();
  112037. }
  112038. });
  112039. }
  112040. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  112041. // Properties
  112042. /**
  112043. * Gets the perf counter used for active meshes evaluation time
  112044. */
  112045. get: function () {
  112046. return this._activeMeshesEvaluationTime;
  112047. },
  112048. enumerable: true,
  112049. configurable: true
  112050. });
  112051. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  112052. /**
  112053. * Gets the active meshes evaluation time capture status
  112054. */
  112055. get: function () {
  112056. return this._captureActiveMeshesEvaluationTime;
  112057. },
  112058. /**
  112059. * Enable or disable the active meshes evaluation time capture
  112060. */
  112061. set: function (value) {
  112062. var _this = this;
  112063. if (value === this._captureActiveMeshesEvaluationTime) {
  112064. return;
  112065. }
  112066. this._captureActiveMeshesEvaluationTime = value;
  112067. if (value) {
  112068. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  112069. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  112070. _this._activeMeshesEvaluationTime.beginMonitoring();
  112071. });
  112072. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  112073. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  112074. _this._activeMeshesEvaluationTime.endMonitoring();
  112075. });
  112076. }
  112077. else {
  112078. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  112079. this._onBeforeActiveMeshesEvaluationObserver = null;
  112080. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  112081. this._onAfterActiveMeshesEvaluationObserver = null;
  112082. }
  112083. },
  112084. enumerable: true,
  112085. configurable: true
  112086. });
  112087. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  112088. /**
  112089. * Gets the perf counter used for render targets render time
  112090. */
  112091. get: function () {
  112092. return this._renderTargetsRenderTime;
  112093. },
  112094. enumerable: true,
  112095. configurable: true
  112096. });
  112097. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  112098. /**
  112099. * Gets the render targets render time capture status
  112100. */
  112101. get: function () {
  112102. return this._captureRenderTargetsRenderTime;
  112103. },
  112104. /**
  112105. * Enable or disable the render targets render time capture
  112106. */
  112107. set: function (value) {
  112108. var _this = this;
  112109. if (value === this._captureRenderTargetsRenderTime) {
  112110. return;
  112111. }
  112112. this._captureRenderTargetsRenderTime = value;
  112113. if (value) {
  112114. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  112115. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  112116. _this._renderTargetsRenderTime.beginMonitoring();
  112117. });
  112118. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  112119. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  112120. _this._renderTargetsRenderTime.endMonitoring(false);
  112121. });
  112122. }
  112123. else {
  112124. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  112125. this._onBeforeRenderTargetsRenderObserver = null;
  112126. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  112127. this._onAfterRenderTargetsRenderObserver = null;
  112128. }
  112129. },
  112130. enumerable: true,
  112131. configurable: true
  112132. });
  112133. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  112134. /**
  112135. * Gets the perf counter used for particles render time
  112136. */
  112137. get: function () {
  112138. return this._particlesRenderTime;
  112139. },
  112140. enumerable: true,
  112141. configurable: true
  112142. });
  112143. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  112144. /**
  112145. * Gets the particles render time capture status
  112146. */
  112147. get: function () {
  112148. return this._captureParticlesRenderTime;
  112149. },
  112150. /**
  112151. * Enable or disable the particles render time capture
  112152. */
  112153. set: function (value) {
  112154. var _this = this;
  112155. if (value === this._captureParticlesRenderTime) {
  112156. return;
  112157. }
  112158. this._captureParticlesRenderTime = value;
  112159. if (value) {
  112160. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  112161. BABYLON.Tools.StartPerformanceCounter("Particles");
  112162. _this._particlesRenderTime.beginMonitoring();
  112163. });
  112164. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  112165. BABYLON.Tools.EndPerformanceCounter("Particles");
  112166. _this._particlesRenderTime.endMonitoring(false);
  112167. });
  112168. }
  112169. else {
  112170. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  112171. this._onBeforeParticlesRenderingObserver = null;
  112172. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  112173. this._onAfterParticlesRenderingObserver = null;
  112174. }
  112175. },
  112176. enumerable: true,
  112177. configurable: true
  112178. });
  112179. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  112180. /**
  112181. * Gets the perf counter used for sprites render time
  112182. */
  112183. get: function () {
  112184. return this._spritesRenderTime;
  112185. },
  112186. enumerable: true,
  112187. configurable: true
  112188. });
  112189. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  112190. /**
  112191. * Gets the sprites render time capture status
  112192. */
  112193. get: function () {
  112194. return this._captureSpritesRenderTime;
  112195. },
  112196. /**
  112197. * Enable or disable the sprites render time capture
  112198. */
  112199. set: function (value) {
  112200. var _this = this;
  112201. if (value === this._captureSpritesRenderTime) {
  112202. return;
  112203. }
  112204. this._captureSpritesRenderTime = value;
  112205. if (!this.scene.spriteManagers) {
  112206. return;
  112207. }
  112208. if (value) {
  112209. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  112210. BABYLON.Tools.StartPerformanceCounter("Sprites");
  112211. _this._spritesRenderTime.beginMonitoring();
  112212. });
  112213. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  112214. BABYLON.Tools.EndPerformanceCounter("Sprites");
  112215. _this._spritesRenderTime.endMonitoring(false);
  112216. });
  112217. }
  112218. else {
  112219. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  112220. this._onBeforeSpritesRenderingObserver = null;
  112221. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  112222. this._onAfterSpritesRenderingObserver = null;
  112223. }
  112224. },
  112225. enumerable: true,
  112226. configurable: true
  112227. });
  112228. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  112229. /**
  112230. * Gets the perf counter used for physics time
  112231. */
  112232. get: function () {
  112233. return this._physicsTime;
  112234. },
  112235. enumerable: true,
  112236. configurable: true
  112237. });
  112238. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  112239. /**
  112240. * Gets the physics time capture status
  112241. */
  112242. get: function () {
  112243. return this._capturePhysicsTime;
  112244. },
  112245. /**
  112246. * Enable or disable the physics time capture
  112247. */
  112248. set: function (value) {
  112249. var _this = this;
  112250. if (value === this._capturePhysicsTime) {
  112251. return;
  112252. }
  112253. if (!this.scene.onBeforePhysicsObservable) {
  112254. return;
  112255. }
  112256. this._capturePhysicsTime = value;
  112257. if (value) {
  112258. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  112259. BABYLON.Tools.StartPerformanceCounter("Physics");
  112260. _this._physicsTime.beginMonitoring();
  112261. });
  112262. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  112263. BABYLON.Tools.EndPerformanceCounter("Physics");
  112264. _this._physicsTime.endMonitoring();
  112265. });
  112266. }
  112267. else {
  112268. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  112269. this._onBeforePhysicsObserver = null;
  112270. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  112271. this._onAfterPhysicsObserver = null;
  112272. }
  112273. },
  112274. enumerable: true,
  112275. configurable: true
  112276. });
  112277. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  112278. /**
  112279. * Gets the perf counter used for animations time
  112280. */
  112281. get: function () {
  112282. return this._animationsTime;
  112283. },
  112284. enumerable: true,
  112285. configurable: true
  112286. });
  112287. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  112288. /**
  112289. * Gets the animations time capture status
  112290. */
  112291. get: function () {
  112292. return this._captureAnimationsTime;
  112293. },
  112294. /**
  112295. * Enable or disable the animations time capture
  112296. */
  112297. set: function (value) {
  112298. var _this = this;
  112299. if (value === this._captureAnimationsTime) {
  112300. return;
  112301. }
  112302. this._captureAnimationsTime = value;
  112303. if (value) {
  112304. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  112305. _this._animationsTime.endMonitoring();
  112306. });
  112307. }
  112308. else {
  112309. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  112310. this._onAfterAnimationsObserver = null;
  112311. }
  112312. },
  112313. enumerable: true,
  112314. configurable: true
  112315. });
  112316. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  112317. /**
  112318. * Gets the perf counter used for frame time capture
  112319. */
  112320. get: function () {
  112321. return this._frameTime;
  112322. },
  112323. enumerable: true,
  112324. configurable: true
  112325. });
  112326. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  112327. /**
  112328. * Gets the frame time capture status
  112329. */
  112330. get: function () {
  112331. return this._captureFrameTime;
  112332. },
  112333. /**
  112334. * Enable or disable the frame time capture
  112335. */
  112336. set: function (value) {
  112337. this._captureFrameTime = value;
  112338. },
  112339. enumerable: true,
  112340. configurable: true
  112341. });
  112342. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  112343. /**
  112344. * Gets the perf counter used for inter-frames time capture
  112345. */
  112346. get: function () {
  112347. return this._interFrameTime;
  112348. },
  112349. enumerable: true,
  112350. configurable: true
  112351. });
  112352. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  112353. /**
  112354. * Gets the inter-frames time capture status
  112355. */
  112356. get: function () {
  112357. return this._captureInterFrameTime;
  112358. },
  112359. /**
  112360. * Enable or disable the inter-frames time capture
  112361. */
  112362. set: function (value) {
  112363. this._captureInterFrameTime = value;
  112364. },
  112365. enumerable: true,
  112366. configurable: true
  112367. });
  112368. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  112369. /**
  112370. * Gets the perf counter used for render time capture
  112371. */
  112372. get: function () {
  112373. return this._renderTime;
  112374. },
  112375. enumerable: true,
  112376. configurable: true
  112377. });
  112378. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  112379. /**
  112380. * Gets the render time capture status
  112381. */
  112382. get: function () {
  112383. return this._captureRenderTime;
  112384. },
  112385. /**
  112386. * Enable or disable the render time capture
  112387. */
  112388. set: function (value) {
  112389. var _this = this;
  112390. if (value === this._captureRenderTime) {
  112391. return;
  112392. }
  112393. this._captureRenderTime = value;
  112394. if (value) {
  112395. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  112396. _this._renderTime.beginMonitoring();
  112397. BABYLON.Tools.StartPerformanceCounter("Main render");
  112398. });
  112399. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  112400. _this._renderTime.endMonitoring(false);
  112401. BABYLON.Tools.EndPerformanceCounter("Main render");
  112402. });
  112403. }
  112404. else {
  112405. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  112406. this._onBeforeDrawPhaseObserver = null;
  112407. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  112408. this._onAfterDrawPhaseObserver = null;
  112409. }
  112410. },
  112411. enumerable: true,
  112412. configurable: true
  112413. });
  112414. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  112415. /**
  112416. * Gets the perf counter used for camera render time capture
  112417. */
  112418. get: function () {
  112419. return this._cameraRenderTime;
  112420. },
  112421. enumerable: true,
  112422. configurable: true
  112423. });
  112424. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  112425. /**
  112426. * Gets the camera render time capture status
  112427. */
  112428. get: function () {
  112429. return this._captureCameraRenderTime;
  112430. },
  112431. /**
  112432. * Enable or disable the camera render time capture
  112433. */
  112434. set: function (value) {
  112435. var _this = this;
  112436. if (value === this._captureCameraRenderTime) {
  112437. return;
  112438. }
  112439. this._captureCameraRenderTime = value;
  112440. if (value) {
  112441. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  112442. _this._cameraRenderTime.beginMonitoring();
  112443. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  112444. });
  112445. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  112446. _this._cameraRenderTime.endMonitoring(false);
  112447. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  112448. });
  112449. }
  112450. else {
  112451. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  112452. this._onBeforeCameraRenderObserver = null;
  112453. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  112454. this._onAfterCameraRenderObserver = null;
  112455. }
  112456. },
  112457. enumerable: true,
  112458. configurable: true
  112459. });
  112460. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  112461. /**
  112462. * Gets the perf counter used for draw calls
  112463. */
  112464. get: function () {
  112465. return this.scene.getEngine()._drawCalls;
  112466. },
  112467. enumerable: true,
  112468. configurable: true
  112469. });
  112470. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  112471. /**
  112472. * Gets the perf counter used for texture collisions
  112473. */
  112474. get: function () {
  112475. return this.scene.getEngine()._textureCollisions;
  112476. },
  112477. enumerable: true,
  112478. configurable: true
  112479. });
  112480. /**
  112481. * Dispose and release associated resources.
  112482. */
  112483. SceneInstrumentation.prototype.dispose = function () {
  112484. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  112485. this._onAfterRenderObserver = null;
  112486. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  112487. this._onBeforeActiveMeshesEvaluationObserver = null;
  112488. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  112489. this._onAfterActiveMeshesEvaluationObserver = null;
  112490. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  112491. this._onBeforeRenderTargetsRenderObserver = null;
  112492. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  112493. this._onAfterRenderTargetsRenderObserver = null;
  112494. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  112495. this._onBeforeAnimationsObserver = null;
  112496. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  112497. this._onBeforeParticlesRenderingObserver = null;
  112498. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  112499. this._onAfterParticlesRenderingObserver = null;
  112500. if (this._onBeforeSpritesRenderingObserver) {
  112501. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  112502. this._onBeforeSpritesRenderingObserver = null;
  112503. }
  112504. if (this._onAfterSpritesRenderingObserver) {
  112505. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  112506. this._onAfterSpritesRenderingObserver = null;
  112507. }
  112508. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  112509. this._onBeforeDrawPhaseObserver = null;
  112510. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  112511. this._onAfterDrawPhaseObserver = null;
  112512. if (this._onBeforePhysicsObserver) {
  112513. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  112514. this._onBeforePhysicsObserver = null;
  112515. }
  112516. if (this._onAfterPhysicsObserver) {
  112517. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  112518. this._onAfterPhysicsObserver = null;
  112519. }
  112520. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  112521. this._onAfterAnimationsObserver = null;
  112522. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  112523. this._onBeforeCameraRenderObserver = null;
  112524. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  112525. this._onAfterCameraRenderObserver = null;
  112526. this.scene = null;
  112527. };
  112528. return SceneInstrumentation;
  112529. }());
  112530. BABYLON.SceneInstrumentation = SceneInstrumentation;
  112531. })(BABYLON || (BABYLON = {}));
  112532. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  112533. var BABYLON;
  112534. (function (BABYLON) {
  112535. /**
  112536. * @hidden
  112537. **/
  112538. var _TimeToken = /** @class */ (function () {
  112539. function _TimeToken() {
  112540. this._timeElapsedQueryEnded = false;
  112541. }
  112542. return _TimeToken;
  112543. }());
  112544. BABYLON._TimeToken = _TimeToken;
  112545. })(BABYLON || (BABYLON = {}));
  112546. //# sourceMappingURL=babylon.timeToken.js.map
  112547. var BABYLON;
  112548. (function (BABYLON) {
  112549. /**
  112550. * Background material defines definition.
  112551. * @hidden Mainly internal Use
  112552. */
  112553. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  112554. __extends(BackgroundMaterialDefines, _super);
  112555. /**
  112556. * Constructor of the defines.
  112557. */
  112558. function BackgroundMaterialDefines() {
  112559. var _this = _super.call(this) || this;
  112560. /**
  112561. * True if the diffuse texture is in use.
  112562. */
  112563. _this.DIFFUSE = false;
  112564. /**
  112565. * The direct UV channel to use.
  112566. */
  112567. _this.DIFFUSEDIRECTUV = 0;
  112568. /**
  112569. * True if the diffuse texture is in gamma space.
  112570. */
  112571. _this.GAMMADIFFUSE = false;
  112572. /**
  112573. * True if the diffuse texture has opacity in the alpha channel.
  112574. */
  112575. _this.DIFFUSEHASALPHA = false;
  112576. /**
  112577. * True if you want the material to fade to transparent at grazing angle.
  112578. */
  112579. _this.OPACITYFRESNEL = false;
  112580. /**
  112581. * True if an extra blur needs to be added in the reflection.
  112582. */
  112583. _this.REFLECTIONBLUR = false;
  112584. /**
  112585. * True if you want the material to fade to reflection at grazing angle.
  112586. */
  112587. _this.REFLECTIONFRESNEL = false;
  112588. /**
  112589. * True if you want the material to falloff as far as you move away from the scene center.
  112590. */
  112591. _this.REFLECTIONFALLOFF = false;
  112592. /**
  112593. * False if the current Webgl implementation does not support the texture lod extension.
  112594. */
  112595. _this.TEXTURELODSUPPORT = false;
  112596. /**
  112597. * True to ensure the data are premultiplied.
  112598. */
  112599. _this.PREMULTIPLYALPHA = false;
  112600. /**
  112601. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  112602. */
  112603. _this.USERGBCOLOR = false;
  112604. /**
  112605. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  112606. * stays aligned with the desired configuration.
  112607. */
  112608. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  112609. /**
  112610. * True to add noise in order to reduce the banding effect.
  112611. */
  112612. _this.NOISE = false;
  112613. /**
  112614. * is the reflection texture in BGR color scheme?
  112615. * Mainly used to solve a bug in ios10 video tag
  112616. */
  112617. _this.REFLECTIONBGR = false;
  112618. _this.IMAGEPROCESSING = false;
  112619. _this.VIGNETTE = false;
  112620. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  112621. _this.VIGNETTEBLENDMODEOPAQUE = false;
  112622. _this.TONEMAPPING = false;
  112623. _this.TONEMAPPING_ACES = false;
  112624. _this.CONTRAST = false;
  112625. _this.COLORCURVES = false;
  112626. _this.COLORGRADING = false;
  112627. _this.COLORGRADING3D = false;
  112628. _this.SAMPLER3DGREENDEPTH = false;
  112629. _this.SAMPLER3DBGRMAP = false;
  112630. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  112631. _this.EXPOSURE = false;
  112632. // Reflection.
  112633. _this.REFLECTION = false;
  112634. _this.REFLECTIONMAP_3D = false;
  112635. _this.REFLECTIONMAP_SPHERICAL = false;
  112636. _this.REFLECTIONMAP_PLANAR = false;
  112637. _this.REFLECTIONMAP_CUBIC = false;
  112638. _this.REFLECTIONMAP_PROJECTION = false;
  112639. _this.REFLECTIONMAP_SKYBOX = false;
  112640. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  112641. _this.REFLECTIONMAP_EXPLICIT = false;
  112642. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  112643. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  112644. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  112645. _this.INVERTCUBICMAP = false;
  112646. _this.REFLECTIONMAP_OPPOSITEZ = false;
  112647. _this.LODINREFLECTIONALPHA = false;
  112648. _this.GAMMAREFLECTION = false;
  112649. _this.RGBDREFLECTION = false;
  112650. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  112651. // Default BJS.
  112652. _this.MAINUV1 = false;
  112653. _this.MAINUV2 = false;
  112654. _this.UV1 = false;
  112655. _this.UV2 = false;
  112656. _this.CLIPPLANE = false;
  112657. _this.CLIPPLANE2 = false;
  112658. _this.CLIPPLANE3 = false;
  112659. _this.CLIPPLANE4 = false;
  112660. _this.POINTSIZE = false;
  112661. _this.FOG = false;
  112662. _this.NORMAL = false;
  112663. _this.NUM_BONE_INFLUENCERS = 0;
  112664. _this.BonesPerMesh = 0;
  112665. _this.INSTANCES = false;
  112666. _this.SHADOWFLOAT = false;
  112667. _this.rebuild();
  112668. return _this;
  112669. }
  112670. return BackgroundMaterialDefines;
  112671. }(BABYLON.MaterialDefines));
  112672. /**
  112673. * Background material used to create an efficient environement around your scene.
  112674. */
  112675. var BackgroundMaterial = /** @class */ (function (_super) {
  112676. __extends(BackgroundMaterial, _super);
  112677. /**
  112678. * Instantiates a Background Material in the given scene
  112679. * @param name The friendly name of the material
  112680. * @param scene The scene to add the material to
  112681. */
  112682. function BackgroundMaterial(name, scene) {
  112683. var _this = _super.call(this, name, scene) || this;
  112684. /**
  112685. * Key light Color (multiply against the environement texture)
  112686. */
  112687. _this.primaryColor = BABYLON.Color3.White();
  112688. _this._primaryColorShadowLevel = 0;
  112689. _this._primaryColorHighlightLevel = 0;
  112690. /**
  112691. * Reflection Texture used in the material.
  112692. * Should be author in a specific way for the best result (refer to the documentation).
  112693. */
  112694. _this.reflectionTexture = null;
  112695. /**
  112696. * Reflection Texture level of blur.
  112697. *
  112698. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  112699. * texture twice.
  112700. */
  112701. _this.reflectionBlur = 0;
  112702. /**
  112703. * Diffuse Texture used in the material.
  112704. * Should be author in a specific way for the best result (refer to the documentation).
  112705. */
  112706. _this.diffuseTexture = null;
  112707. _this._shadowLights = null;
  112708. /**
  112709. * Specify the list of lights casting shadow on the material.
  112710. * All scene shadow lights will be included if null.
  112711. */
  112712. _this.shadowLights = null;
  112713. /**
  112714. * Helps adjusting the shadow to a softer level if required.
  112715. * 0 means black shadows and 1 means no shadows.
  112716. */
  112717. _this.shadowLevel = 0;
  112718. /**
  112719. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  112720. * It is usually zero but might be interesting to modify according to your setup.
  112721. */
  112722. _this.sceneCenter = BABYLON.Vector3.Zero();
  112723. /**
  112724. * This helps specifying that the material is falling off to the sky box at grazing angle.
  112725. * This helps ensuring a nice transition when the camera goes under the ground.
  112726. */
  112727. _this.opacityFresnel = true;
  112728. /**
  112729. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  112730. * This helps adding a mirror texture on the ground.
  112731. */
  112732. _this.reflectionFresnel = false;
  112733. /**
  112734. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  112735. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  112736. */
  112737. _this.reflectionFalloffDistance = 0.0;
  112738. /**
  112739. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  112740. */
  112741. _this.reflectionAmount = 1.0;
  112742. /**
  112743. * This specifies the weight of the reflection at grazing angle.
  112744. */
  112745. _this.reflectionReflectance0 = 0.05;
  112746. /**
  112747. * This specifies the weight of the reflection at a perpendicular point of view.
  112748. */
  112749. _this.reflectionReflectance90 = 0.5;
  112750. /**
  112751. * Helps to directly use the maps channels instead of their level.
  112752. */
  112753. _this.useRGBColor = true;
  112754. /**
  112755. * This helps reducing the banding effect that could occur on the background.
  112756. */
  112757. _this.enableNoise = false;
  112758. _this._fovMultiplier = 1.0;
  112759. /**
  112760. * Enable the FOV adjustment feature controlled by fovMultiplier.
  112761. */
  112762. _this.useEquirectangularFOV = false;
  112763. _this._maxSimultaneousLights = 4;
  112764. /**
  112765. * Number of Simultaneous lights allowed on the material.
  112766. */
  112767. _this.maxSimultaneousLights = 4;
  112768. /**
  112769. * Keep track of the image processing observer to allow dispose and replace.
  112770. */
  112771. _this._imageProcessingObserver = null;
  112772. /**
  112773. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  112774. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  112775. */
  112776. _this.switchToBGR = false;
  112777. // Temp values kept as cache in the material.
  112778. _this._renderTargets = new BABYLON.SmartArray(16);
  112779. _this._reflectionControls = BABYLON.Vector4.Zero();
  112780. _this._white = BABYLON.Color3.White();
  112781. _this._primaryShadowColor = BABYLON.Color3.Black();
  112782. _this._primaryHighlightColor = BABYLON.Color3.Black();
  112783. // Setup the default processing configuration to the scene.
  112784. _this._attachImageProcessingConfiguration(null);
  112785. _this.getRenderTargetTextures = function () {
  112786. _this._renderTargets.reset();
  112787. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  112788. _this._renderTargets.push(_this._diffuseTexture);
  112789. }
  112790. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  112791. _this._renderTargets.push(_this._reflectionTexture);
  112792. }
  112793. return _this._renderTargets;
  112794. };
  112795. return _this;
  112796. }
  112797. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  112798. /**
  112799. * Experimental Internal Use Only.
  112800. *
  112801. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  112802. * This acts as a helper to set the primary color to a more "human friendly" value.
  112803. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  112804. * output color as close as possible from the chosen value.
  112805. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  112806. * part of lighting setup.)
  112807. */
  112808. get: function () {
  112809. return this.__perceptualColor;
  112810. },
  112811. set: function (value) {
  112812. this.__perceptualColor = value;
  112813. this._computePrimaryColorFromPerceptualColor();
  112814. this._markAllSubMeshesAsLightsDirty();
  112815. },
  112816. enumerable: true,
  112817. configurable: true
  112818. });
  112819. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  112820. /**
  112821. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  112822. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  112823. */
  112824. get: function () {
  112825. return this._primaryColorShadowLevel;
  112826. },
  112827. set: function (value) {
  112828. this._primaryColorShadowLevel = value;
  112829. this._computePrimaryColors();
  112830. this._markAllSubMeshesAsLightsDirty();
  112831. },
  112832. enumerable: true,
  112833. configurable: true
  112834. });
  112835. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  112836. /**
  112837. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  112838. * The primary color is used at the level chosen to define what the white area would look.
  112839. */
  112840. get: function () {
  112841. return this._primaryColorHighlightLevel;
  112842. },
  112843. set: function (value) {
  112844. this._primaryColorHighlightLevel = value;
  112845. this._computePrimaryColors();
  112846. this._markAllSubMeshesAsLightsDirty();
  112847. },
  112848. enumerable: true,
  112849. configurable: true
  112850. });
  112851. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  112852. /**
  112853. * Sets the reflection reflectance fresnel values according to the default standard
  112854. * empirically know to work well :-)
  112855. */
  112856. set: function (value) {
  112857. var reflectionWeight = value;
  112858. if (reflectionWeight < 0.5) {
  112859. reflectionWeight = reflectionWeight * 2.0;
  112860. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  112861. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  112862. }
  112863. else {
  112864. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  112865. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  112866. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  112867. }
  112868. },
  112869. enumerable: true,
  112870. configurable: true
  112871. });
  112872. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  112873. /**
  112874. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112875. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  112876. * Recommended to be keep at 1.0 except for special cases.
  112877. */
  112878. get: function () {
  112879. return this._fovMultiplier;
  112880. },
  112881. set: function (value) {
  112882. if (isNaN(value)) {
  112883. value = 1.0;
  112884. }
  112885. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  112886. },
  112887. enumerable: true,
  112888. configurable: true
  112889. });
  112890. /**
  112891. * Attaches a new image processing configuration to the PBR Material.
  112892. * @param configuration (if null the scene configuration will be use)
  112893. */
  112894. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  112895. var _this = this;
  112896. if (configuration === this._imageProcessingConfiguration) {
  112897. return;
  112898. }
  112899. // Detaches observer.
  112900. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  112901. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  112902. }
  112903. // Pick the scene configuration if needed.
  112904. if (!configuration) {
  112905. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  112906. }
  112907. else {
  112908. this._imageProcessingConfiguration = configuration;
  112909. }
  112910. // Attaches observer.
  112911. if (this._imageProcessingConfiguration) {
  112912. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  112913. _this._computePrimaryColorFromPerceptualColor();
  112914. _this._markAllSubMeshesAsImageProcessingDirty();
  112915. });
  112916. }
  112917. };
  112918. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  112919. /**
  112920. * Gets the image processing configuration used either in this material.
  112921. */
  112922. get: function () {
  112923. return this._imageProcessingConfiguration;
  112924. },
  112925. /**
  112926. * Sets the Default image processing configuration used either in the this material.
  112927. *
  112928. * If sets to null, the scene one is in use.
  112929. */
  112930. set: function (value) {
  112931. this._attachImageProcessingConfiguration(value);
  112932. // Ensure the effect will be rebuilt.
  112933. this._markAllSubMeshesAsTexturesDirty();
  112934. },
  112935. enumerable: true,
  112936. configurable: true
  112937. });
  112938. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  112939. /**
  112940. * Gets wether the color curves effect is enabled.
  112941. */
  112942. get: function () {
  112943. return this.imageProcessingConfiguration.colorCurvesEnabled;
  112944. },
  112945. /**
  112946. * Sets wether the color curves effect is enabled.
  112947. */
  112948. set: function (value) {
  112949. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  112950. },
  112951. enumerable: true,
  112952. configurable: true
  112953. });
  112954. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  112955. /**
  112956. * Gets wether the color grading effect is enabled.
  112957. */
  112958. get: function () {
  112959. return this.imageProcessingConfiguration.colorGradingEnabled;
  112960. },
  112961. /**
  112962. * Gets wether the color grading effect is enabled.
  112963. */
  112964. set: function (value) {
  112965. this.imageProcessingConfiguration.colorGradingEnabled = value;
  112966. },
  112967. enumerable: true,
  112968. configurable: true
  112969. });
  112970. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  112971. /**
  112972. * Gets wether tonemapping is enabled or not.
  112973. */
  112974. get: function () {
  112975. return this._imageProcessingConfiguration.toneMappingEnabled;
  112976. },
  112977. /**
  112978. * Sets wether tonemapping is enabled or not
  112979. */
  112980. set: function (value) {
  112981. this._imageProcessingConfiguration.toneMappingEnabled = value;
  112982. },
  112983. enumerable: true,
  112984. configurable: true
  112985. });
  112986. ;
  112987. ;
  112988. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  112989. /**
  112990. * The camera exposure used on this material.
  112991. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  112992. * This corresponds to a photographic exposure.
  112993. */
  112994. get: function () {
  112995. return this._imageProcessingConfiguration.exposure;
  112996. },
  112997. /**
  112998. * The camera exposure used on this material.
  112999. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  113000. * This corresponds to a photographic exposure.
  113001. */
  113002. set: function (value) {
  113003. this._imageProcessingConfiguration.exposure = value;
  113004. },
  113005. enumerable: true,
  113006. configurable: true
  113007. });
  113008. ;
  113009. ;
  113010. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  113011. /**
  113012. * Gets The camera contrast used on this material.
  113013. */
  113014. get: function () {
  113015. return this._imageProcessingConfiguration.contrast;
  113016. },
  113017. /**
  113018. * Sets The camera contrast used on this material.
  113019. */
  113020. set: function (value) {
  113021. this._imageProcessingConfiguration.contrast = value;
  113022. },
  113023. enumerable: true,
  113024. configurable: true
  113025. });
  113026. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  113027. /**
  113028. * Gets the Color Grading 2D Lookup Texture.
  113029. */
  113030. get: function () {
  113031. return this._imageProcessingConfiguration.colorGradingTexture;
  113032. },
  113033. /**
  113034. * Sets the Color Grading 2D Lookup Texture.
  113035. */
  113036. set: function (value) {
  113037. this.imageProcessingConfiguration.colorGradingTexture = value;
  113038. },
  113039. enumerable: true,
  113040. configurable: true
  113041. });
  113042. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  113043. /**
  113044. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  113045. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  113046. * 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;
  113047. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  113048. */
  113049. get: function () {
  113050. return this.imageProcessingConfiguration.colorCurves;
  113051. },
  113052. /**
  113053. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  113054. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  113055. * 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;
  113056. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  113057. */
  113058. set: function (value) {
  113059. this.imageProcessingConfiguration.colorCurves = value;
  113060. },
  113061. enumerable: true,
  113062. configurable: true
  113063. });
  113064. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  113065. /**
  113066. * Gets a boolean indicating that current material needs to register RTT
  113067. */
  113068. get: function () {
  113069. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  113070. return true;
  113071. }
  113072. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  113073. return true;
  113074. }
  113075. return false;
  113076. },
  113077. enumerable: true,
  113078. configurable: true
  113079. });
  113080. /**
  113081. * The entire material has been created in order to prevent overdraw.
  113082. * @returns false
  113083. */
  113084. BackgroundMaterial.prototype.needAlphaTesting = function () {
  113085. return true;
  113086. };
  113087. /**
  113088. * The entire material has been created in order to prevent overdraw.
  113089. * @returns true if blending is enable
  113090. */
  113091. BackgroundMaterial.prototype.needAlphaBlending = function () {
  113092. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  113093. };
  113094. /**
  113095. * Checks wether the material is ready to be rendered for a given mesh.
  113096. * @param mesh The mesh to render
  113097. * @param subMesh The submesh to check against
  113098. * @param useInstances Specify wether or not the material is used with instances
  113099. * @returns true if all the dependencies are ready (Textures, Effects...)
  113100. */
  113101. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  113102. var _this = this;
  113103. if (useInstances === void 0) { useInstances = false; }
  113104. if (subMesh.effect && this.isFrozen) {
  113105. if (this._wasPreviouslyReady) {
  113106. return true;
  113107. }
  113108. }
  113109. if (!subMesh._materialDefines) {
  113110. subMesh._materialDefines = new BackgroundMaterialDefines();
  113111. }
  113112. var scene = this.getScene();
  113113. var defines = subMesh._materialDefines;
  113114. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  113115. if (defines._renderId === scene.getRenderId()) {
  113116. return true;
  113117. }
  113118. }
  113119. var engine = scene.getEngine();
  113120. // Lights
  113121. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  113122. defines._needNormals = true;
  113123. // Textures
  113124. if (defines._areTexturesDirty) {
  113125. defines._needUVs = false;
  113126. if (scene.texturesEnabled) {
  113127. if (scene.getEngine().getCaps().textureLOD) {
  113128. defines.TEXTURELODSUPPORT = true;
  113129. }
  113130. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  113131. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  113132. return false;
  113133. }
  113134. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  113135. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  113136. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  113137. defines.OPACITYFRESNEL = this._opacityFresnel;
  113138. }
  113139. else {
  113140. defines.DIFFUSE = false;
  113141. defines.DIFFUSEHASALPHA = false;
  113142. defines.GAMMADIFFUSE = false;
  113143. defines.OPACITYFRESNEL = false;
  113144. }
  113145. var reflectionTexture = this._reflectionTexture;
  113146. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  113147. if (!reflectionTexture.isReadyOrNotBlocking()) {
  113148. return false;
  113149. }
  113150. defines.REFLECTION = true;
  113151. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  113152. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  113153. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  113154. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  113155. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  113156. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  113157. defines.REFLECTIONBGR = this.switchToBGR;
  113158. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  113159. defines.INVERTCUBICMAP = true;
  113160. }
  113161. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  113162. switch (reflectionTexture.coordinatesMode) {
  113163. case BABYLON.Texture.EXPLICIT_MODE:
  113164. defines.REFLECTIONMAP_EXPLICIT = true;
  113165. break;
  113166. case BABYLON.Texture.PLANAR_MODE:
  113167. defines.REFLECTIONMAP_PLANAR = true;
  113168. break;
  113169. case BABYLON.Texture.PROJECTION_MODE:
  113170. defines.REFLECTIONMAP_PROJECTION = true;
  113171. break;
  113172. case BABYLON.Texture.SKYBOX_MODE:
  113173. defines.REFLECTIONMAP_SKYBOX = true;
  113174. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  113175. break;
  113176. case BABYLON.Texture.SPHERICAL_MODE:
  113177. defines.REFLECTIONMAP_SPHERICAL = true;
  113178. break;
  113179. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  113180. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  113181. break;
  113182. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  113183. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  113184. break;
  113185. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  113186. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  113187. break;
  113188. case BABYLON.Texture.CUBIC_MODE:
  113189. case BABYLON.Texture.INVCUBIC_MODE:
  113190. default:
  113191. defines.REFLECTIONMAP_CUBIC = true;
  113192. break;
  113193. }
  113194. if (this.reflectionFresnel) {
  113195. defines.REFLECTIONFRESNEL = true;
  113196. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  113197. this._reflectionControls.x = this.reflectionAmount;
  113198. this._reflectionControls.y = this.reflectionReflectance0;
  113199. this._reflectionControls.z = this.reflectionReflectance90;
  113200. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  113201. }
  113202. else {
  113203. defines.REFLECTIONFRESNEL = false;
  113204. defines.REFLECTIONFALLOFF = false;
  113205. }
  113206. }
  113207. else {
  113208. defines.REFLECTION = false;
  113209. defines.REFLECTIONFRESNEL = false;
  113210. defines.REFLECTIONFALLOFF = false;
  113211. defines.REFLECTIONBLUR = false;
  113212. defines.REFLECTIONMAP_3D = false;
  113213. defines.REFLECTIONMAP_SPHERICAL = false;
  113214. defines.REFLECTIONMAP_PLANAR = false;
  113215. defines.REFLECTIONMAP_CUBIC = false;
  113216. defines.REFLECTIONMAP_PROJECTION = false;
  113217. defines.REFLECTIONMAP_SKYBOX = false;
  113218. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  113219. defines.REFLECTIONMAP_EXPLICIT = false;
  113220. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  113221. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  113222. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  113223. defines.INVERTCUBICMAP = false;
  113224. defines.REFLECTIONMAP_OPPOSITEZ = false;
  113225. defines.LODINREFLECTIONALPHA = false;
  113226. defines.GAMMAREFLECTION = false;
  113227. defines.RGBDREFLECTION = false;
  113228. }
  113229. }
  113230. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  113231. defines.USERGBCOLOR = this._useRGBColor;
  113232. defines.NOISE = this._enableNoise;
  113233. }
  113234. if (defines._areLightsDirty) {
  113235. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  113236. }
  113237. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  113238. if (!this._imageProcessingConfiguration.isReady()) {
  113239. return false;
  113240. }
  113241. this._imageProcessingConfiguration.prepareDefines(defines);
  113242. }
  113243. // Misc.
  113244. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  113245. // Values that need to be evaluated on every frame
  113246. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  113247. // Attribs
  113248. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  113249. if (mesh) {
  113250. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  113251. mesh.createNormals(true);
  113252. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  113253. }
  113254. }
  113255. }
  113256. // Get correct effect
  113257. if (defines.isDirty) {
  113258. defines.markAsProcessed();
  113259. scene.resetCachedMaterial();
  113260. // Fallbacks
  113261. var fallbacks = new BABYLON.EffectFallbacks();
  113262. if (defines.FOG) {
  113263. fallbacks.addFallback(0, "FOG");
  113264. }
  113265. if (defines.POINTSIZE) {
  113266. fallbacks.addFallback(1, "POINTSIZE");
  113267. }
  113268. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  113269. if (defines.NUM_BONE_INFLUENCERS > 0) {
  113270. fallbacks.addCPUSkinningFallback(0, mesh);
  113271. }
  113272. //Attributes
  113273. var attribs = [BABYLON.VertexBuffer.PositionKind];
  113274. if (defines.NORMAL) {
  113275. attribs.push(BABYLON.VertexBuffer.NormalKind);
  113276. }
  113277. if (defines.UV1) {
  113278. attribs.push(BABYLON.VertexBuffer.UVKind);
  113279. }
  113280. if (defines.UV2) {
  113281. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  113282. }
  113283. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  113284. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  113285. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  113286. "vFogInfos", "vFogColor", "pointSize",
  113287. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  113288. "vPrimaryColor", "vPrimaryColorShadow",
  113289. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  113290. "shadowLevel", "alpha",
  113291. "vBackgroundCenter", "vReflectionControl",
  113292. "vDiffuseInfos", "diffuseMatrix",
  113293. ];
  113294. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  113295. var uniformBuffers = ["Material", "Scene"];
  113296. if (BABYLON.ImageProcessingConfiguration) {
  113297. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  113298. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  113299. }
  113300. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  113301. uniformsNames: uniforms,
  113302. uniformBuffersNames: uniformBuffers,
  113303. samplers: samplers,
  113304. defines: defines,
  113305. maxSimultaneousLights: this._maxSimultaneousLights
  113306. });
  113307. var onCompiled = function (effect) {
  113308. if (_this.onCompiled) {
  113309. _this.onCompiled(effect);
  113310. }
  113311. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  113312. };
  113313. var join = defines.toString();
  113314. subMesh.setEffect(scene.getEngine().createEffect("background", {
  113315. attributes: attribs,
  113316. uniformsNames: uniforms,
  113317. uniformBuffersNames: uniformBuffers,
  113318. samplers: samplers,
  113319. defines: join,
  113320. fallbacks: fallbacks,
  113321. onCompiled: onCompiled,
  113322. onError: this.onError,
  113323. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  113324. }, engine), defines);
  113325. this.buildUniformLayout();
  113326. }
  113327. if (!subMesh.effect || !subMesh.effect.isReady()) {
  113328. return false;
  113329. }
  113330. defines._renderId = scene.getRenderId();
  113331. this._wasPreviouslyReady = true;
  113332. return true;
  113333. };
  113334. /**
  113335. * Compute the primary color according to the chosen perceptual color.
  113336. */
  113337. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  113338. if (!this.__perceptualColor) {
  113339. return;
  113340. }
  113341. this._primaryColor.copyFrom(this.__perceptualColor);
  113342. // Revert gamma space.
  113343. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  113344. // Revert image processing configuration.
  113345. if (this._imageProcessingConfiguration) {
  113346. // Revert Exposure.
  113347. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  113348. }
  113349. this._computePrimaryColors();
  113350. };
  113351. /**
  113352. * Compute the highlights and shadow colors according to their chosen levels.
  113353. */
  113354. BackgroundMaterial.prototype._computePrimaryColors = function () {
  113355. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  113356. return;
  113357. }
  113358. // Find the highlight color based on the configuration.
  113359. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  113360. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  113361. // Find the shadow color based on the configuration.
  113362. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  113363. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  113364. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  113365. };
  113366. /**
  113367. * Build the uniform buffer used in the material.
  113368. */
  113369. BackgroundMaterial.prototype.buildUniformLayout = function () {
  113370. // Order is important !
  113371. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  113372. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  113373. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  113374. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  113375. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  113376. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  113377. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  113378. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  113379. this._uniformBuffer.addUniform("pointSize", 1);
  113380. this._uniformBuffer.addUniform("shadowLevel", 1);
  113381. this._uniformBuffer.addUniform("alpha", 1);
  113382. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  113383. this._uniformBuffer.addUniform("vReflectionControl", 4);
  113384. this._uniformBuffer.create();
  113385. };
  113386. /**
  113387. * Unbind the material.
  113388. */
  113389. BackgroundMaterial.prototype.unbind = function () {
  113390. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  113391. this._uniformBuffer.setTexture("diffuseSampler", null);
  113392. }
  113393. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  113394. this._uniformBuffer.setTexture("reflectionSampler", null);
  113395. }
  113396. _super.prototype.unbind.call(this);
  113397. };
  113398. /**
  113399. * Bind only the world matrix to the material.
  113400. * @param world The world matrix to bind.
  113401. */
  113402. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  113403. this._activeEffect.setMatrix("world", world);
  113404. };
  113405. /**
  113406. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  113407. * @param world The world matrix to bind.
  113408. * @param subMesh The submesh to bind for.
  113409. */
  113410. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  113411. var scene = this.getScene();
  113412. var defines = subMesh._materialDefines;
  113413. if (!defines) {
  113414. return;
  113415. }
  113416. var effect = subMesh.effect;
  113417. if (!effect) {
  113418. return;
  113419. }
  113420. this._activeEffect = effect;
  113421. // Matrices
  113422. this.bindOnlyWorldMatrix(world);
  113423. // Bones
  113424. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  113425. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  113426. if (mustRebind) {
  113427. this._uniformBuffer.bindToEffect(effect, "Material");
  113428. this.bindViewProjection(effect);
  113429. var reflectionTexture = this._reflectionTexture;
  113430. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  113431. // Texture uniforms
  113432. if (scene.texturesEnabled) {
  113433. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  113434. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  113435. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  113436. }
  113437. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  113438. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  113439. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  113440. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  113441. }
  113442. }
  113443. if (this.shadowLevel > 0) {
  113444. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  113445. }
  113446. this._uniformBuffer.updateFloat("alpha", this.alpha);
  113447. // Point size
  113448. if (this.pointsCloud) {
  113449. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  113450. }
  113451. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  113452. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  113453. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  113454. }
  113455. else {
  113456. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  113457. }
  113458. }
  113459. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  113460. // Textures
  113461. if (scene.texturesEnabled) {
  113462. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  113463. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  113464. }
  113465. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  113466. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  113467. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  113468. }
  113469. else if (!defines.REFLECTIONBLUR) {
  113470. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  113471. }
  113472. else {
  113473. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  113474. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  113475. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  113476. }
  113477. if (defines.REFLECTIONFRESNEL) {
  113478. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  113479. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  113480. }
  113481. }
  113482. }
  113483. // Clip plane
  113484. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  113485. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  113486. }
  113487. if (mustRebind || !this.isFrozen) {
  113488. if (scene.lightsEnabled) {
  113489. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  113490. }
  113491. // View
  113492. this.bindView(effect);
  113493. // Fog
  113494. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  113495. // image processing
  113496. if (this._imageProcessingConfiguration) {
  113497. this._imageProcessingConfiguration.bind(this._activeEffect);
  113498. }
  113499. }
  113500. this._uniformBuffer.update();
  113501. this._afterBind(mesh, this._activeEffect);
  113502. };
  113503. /**
  113504. * Dispose the material.
  113505. * @param forceDisposeEffect Force disposal of the associated effect.
  113506. * @param forceDisposeTextures Force disposal of the associated textures.
  113507. */
  113508. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  113509. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  113510. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  113511. if (forceDisposeTextures) {
  113512. if (this.diffuseTexture) {
  113513. this.diffuseTexture.dispose();
  113514. }
  113515. if (this.reflectionTexture) {
  113516. this.reflectionTexture.dispose();
  113517. }
  113518. }
  113519. this._renderTargets.dispose();
  113520. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  113521. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  113522. }
  113523. _super.prototype.dispose.call(this, forceDisposeEffect);
  113524. };
  113525. /**
  113526. * Clones the material.
  113527. * @param name The cloned name.
  113528. * @returns The cloned material.
  113529. */
  113530. BackgroundMaterial.prototype.clone = function (name) {
  113531. var _this = this;
  113532. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  113533. };
  113534. /**
  113535. * Serializes the current material to its JSON representation.
  113536. * @returns The JSON representation.
  113537. */
  113538. BackgroundMaterial.prototype.serialize = function () {
  113539. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  113540. serializationObject.customType = "BABYLON.BackgroundMaterial";
  113541. return serializationObject;
  113542. };
  113543. /**
  113544. * Gets the class name of the material
  113545. * @returns "BackgroundMaterial"
  113546. */
  113547. BackgroundMaterial.prototype.getClassName = function () {
  113548. return "BackgroundMaterial";
  113549. };
  113550. /**
  113551. * Parse a JSON input to create back a background material.
  113552. * @param source The JSON data to parse
  113553. * @param scene The scene to create the parsed material in
  113554. * @param rootUrl The root url of the assets the material depends upon
  113555. * @returns the instantiated BackgroundMaterial.
  113556. */
  113557. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  113558. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  113559. };
  113560. /**
  113561. * Standard reflectance value at parallel view angle.
  113562. */
  113563. BackgroundMaterial.StandardReflectance0 = 0.05;
  113564. /**
  113565. * Standard reflectance value at grazing angle.
  113566. */
  113567. BackgroundMaterial.StandardReflectance90 = 0.5;
  113568. __decorate([
  113569. BABYLON.serializeAsColor3()
  113570. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  113571. __decorate([
  113572. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  113573. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  113574. __decorate([
  113575. BABYLON.serializeAsColor3()
  113576. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  113577. __decorate([
  113578. BABYLON.serialize()
  113579. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  113580. __decorate([
  113581. BABYLON.serialize()
  113582. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  113583. __decorate([
  113584. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  113585. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  113586. __decorate([
  113587. BABYLON.serializeAsTexture()
  113588. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  113589. __decorate([
  113590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113591. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  113592. __decorate([
  113593. BABYLON.serialize()
  113594. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  113595. __decorate([
  113596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113597. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  113598. __decorate([
  113599. BABYLON.serializeAsTexture()
  113600. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  113601. __decorate([
  113602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113603. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  113604. __decorate([
  113605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113606. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  113607. __decorate([
  113608. BABYLON.serialize()
  113609. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  113610. __decorate([
  113611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113612. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  113613. __decorate([
  113614. BABYLON.serializeAsVector3()
  113615. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  113616. __decorate([
  113617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113618. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  113619. __decorate([
  113620. BABYLON.serialize()
  113621. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  113622. __decorate([
  113623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113624. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  113625. __decorate([
  113626. BABYLON.serialize()
  113627. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  113628. __decorate([
  113629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113630. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  113631. __decorate([
  113632. BABYLON.serialize()
  113633. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  113634. __decorate([
  113635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113636. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  113637. __decorate([
  113638. BABYLON.serialize()
  113639. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  113640. __decorate([
  113641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113642. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  113643. __decorate([
  113644. BABYLON.serialize()
  113645. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  113646. __decorate([
  113647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113648. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  113649. __decorate([
  113650. BABYLON.serialize()
  113651. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  113652. __decorate([
  113653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113654. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  113655. __decorate([
  113656. BABYLON.serialize()
  113657. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  113658. __decorate([
  113659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113660. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  113661. __decorate([
  113662. BABYLON.serialize()
  113663. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  113664. __decorate([
  113665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113666. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  113667. __decorate([
  113668. BABYLON.serialize()
  113669. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  113670. __decorate([
  113671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113672. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  113673. __decorate([
  113674. BABYLON.serializeAsImageProcessingConfiguration()
  113675. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  113676. return BackgroundMaterial;
  113677. }(BABYLON.PushMaterial));
  113678. BABYLON.BackgroundMaterial = BackgroundMaterial;
  113679. })(BABYLON || (BABYLON = {}));
  113680. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  113681. var __assign = (this && this.__assign) || function () {
  113682. __assign = Object.assign || function(t) {
  113683. for (var s, i = 1, n = arguments.length; i < n; i++) {
  113684. s = arguments[i];
  113685. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  113686. t[p] = s[p];
  113687. }
  113688. return t;
  113689. };
  113690. return __assign.apply(this, arguments);
  113691. };
  113692. var BABYLON;
  113693. (function (BABYLON) {
  113694. /**
  113695. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  113696. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  113697. * It also helps with the default setup of your imageProcessing configuration.
  113698. */
  113699. var EnvironmentHelper = /** @class */ (function () {
  113700. /**
  113701. * constructor
  113702. * @param options
  113703. * @param scene The scene to add the material to
  113704. */
  113705. function EnvironmentHelper(options, scene) {
  113706. var _this = this;
  113707. this._errorHandler = function (message, exception) {
  113708. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  113709. };
  113710. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  113711. this._scene = scene;
  113712. this.onErrorObservable = new BABYLON.Observable();
  113713. this._setupBackground();
  113714. this._setupImageProcessing();
  113715. }
  113716. /**
  113717. * Creates the default options for the helper.
  113718. */
  113719. EnvironmentHelper._getDefaultOptions = function () {
  113720. return {
  113721. createGround: true,
  113722. groundSize: 15,
  113723. groundTexture: this._groundTextureCDNUrl,
  113724. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  113725. groundOpacity: 0.9,
  113726. enableGroundShadow: true,
  113727. groundShadowLevel: 0.5,
  113728. enableGroundMirror: false,
  113729. groundMirrorSizeRatio: 0.3,
  113730. groundMirrorBlurKernel: 64,
  113731. groundMirrorAmount: 1,
  113732. groundMirrorFresnelWeight: 1,
  113733. groundMirrorFallOffDistance: 0,
  113734. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  113735. groundYBias: 0.00001,
  113736. createSkybox: true,
  113737. skyboxSize: 20,
  113738. skyboxTexture: this._skyboxTextureCDNUrl,
  113739. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  113740. backgroundYRotation: 0,
  113741. sizeAuto: true,
  113742. rootPosition: BABYLON.Vector3.Zero(),
  113743. setupImageProcessing: true,
  113744. environmentTexture: this._environmentTextureCDNUrl,
  113745. cameraExposure: 0.8,
  113746. cameraContrast: 1.2,
  113747. toneMappingEnabled: true,
  113748. };
  113749. };
  113750. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  113751. /**
  113752. * Gets the root mesh created by the helper.
  113753. */
  113754. get: function () {
  113755. return this._rootMesh;
  113756. },
  113757. enumerable: true,
  113758. configurable: true
  113759. });
  113760. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  113761. /**
  113762. * Gets the skybox created by the helper.
  113763. */
  113764. get: function () {
  113765. return this._skybox;
  113766. },
  113767. enumerable: true,
  113768. configurable: true
  113769. });
  113770. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  113771. /**
  113772. * Gets the skybox texture created by the helper.
  113773. */
  113774. get: function () {
  113775. return this._skyboxTexture;
  113776. },
  113777. enumerable: true,
  113778. configurable: true
  113779. });
  113780. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  113781. /**
  113782. * Gets the skybox material created by the helper.
  113783. */
  113784. get: function () {
  113785. return this._skyboxMaterial;
  113786. },
  113787. enumerable: true,
  113788. configurable: true
  113789. });
  113790. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  113791. /**
  113792. * Gets the ground mesh created by the helper.
  113793. */
  113794. get: function () {
  113795. return this._ground;
  113796. },
  113797. enumerable: true,
  113798. configurable: true
  113799. });
  113800. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  113801. /**
  113802. * Gets the ground texture created by the helper.
  113803. */
  113804. get: function () {
  113805. return this._groundTexture;
  113806. },
  113807. enumerable: true,
  113808. configurable: true
  113809. });
  113810. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  113811. /**
  113812. * Gets the ground mirror created by the helper.
  113813. */
  113814. get: function () {
  113815. return this._groundMirror;
  113816. },
  113817. enumerable: true,
  113818. configurable: true
  113819. });
  113820. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  113821. /**
  113822. * Gets the ground mirror render list to helps pushing the meshes
  113823. * you wish in the ground reflection.
  113824. */
  113825. get: function () {
  113826. if (this._groundMirror) {
  113827. return this._groundMirror.renderList;
  113828. }
  113829. return null;
  113830. },
  113831. enumerable: true,
  113832. configurable: true
  113833. });
  113834. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  113835. /**
  113836. * Gets the ground material created by the helper.
  113837. */
  113838. get: function () {
  113839. return this._groundMaterial;
  113840. },
  113841. enumerable: true,
  113842. configurable: true
  113843. });
  113844. /**
  113845. * Updates the background according to the new options
  113846. * @param options
  113847. */
  113848. EnvironmentHelper.prototype.updateOptions = function (options) {
  113849. var newOptions = __assign({}, this._options, options);
  113850. if (this._ground && !newOptions.createGround) {
  113851. this._ground.dispose();
  113852. this._ground = null;
  113853. }
  113854. if (this._groundMaterial && !newOptions.createGround) {
  113855. this._groundMaterial.dispose();
  113856. this._groundMaterial = null;
  113857. }
  113858. if (this._groundTexture) {
  113859. if (this._options.groundTexture != newOptions.groundTexture) {
  113860. this._groundTexture.dispose();
  113861. this._groundTexture = null;
  113862. }
  113863. }
  113864. if (this._skybox && !newOptions.createSkybox) {
  113865. this._skybox.dispose();
  113866. this._skybox = null;
  113867. }
  113868. if (this._skyboxMaterial && !newOptions.createSkybox) {
  113869. this._skyboxMaterial.dispose();
  113870. this._skyboxMaterial = null;
  113871. }
  113872. if (this._skyboxTexture) {
  113873. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  113874. this._skyboxTexture.dispose();
  113875. this._skyboxTexture = null;
  113876. }
  113877. }
  113878. if (this._groundMirror && !newOptions.enableGroundMirror) {
  113879. this._groundMirror.dispose();
  113880. this._groundMirror = null;
  113881. }
  113882. if (this._scene.environmentTexture) {
  113883. if (this._options.environmentTexture != newOptions.environmentTexture) {
  113884. this._scene.environmentTexture.dispose();
  113885. }
  113886. }
  113887. this._options = newOptions;
  113888. this._setupBackground();
  113889. this._setupImageProcessing();
  113890. };
  113891. /**
  113892. * Sets the primary color of all the available elements.
  113893. * @param color the main color to affect to the ground and the background
  113894. */
  113895. EnvironmentHelper.prototype.setMainColor = function (color) {
  113896. if (this.groundMaterial) {
  113897. this.groundMaterial.primaryColor = color;
  113898. }
  113899. if (this.skyboxMaterial) {
  113900. this.skyboxMaterial.primaryColor = color;
  113901. }
  113902. if (this.groundMirror) {
  113903. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  113904. }
  113905. };
  113906. /**
  113907. * Setup the image processing according to the specified options.
  113908. */
  113909. EnvironmentHelper.prototype._setupImageProcessing = function () {
  113910. if (this._options.setupImageProcessing) {
  113911. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  113912. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  113913. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  113914. this._setupEnvironmentTexture();
  113915. }
  113916. };
  113917. /**
  113918. * Setup the environment texture according to the specified options.
  113919. */
  113920. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  113921. if (this._scene.environmentTexture) {
  113922. return;
  113923. }
  113924. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  113925. this._scene.environmentTexture = this._options.environmentTexture;
  113926. return;
  113927. }
  113928. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  113929. this._scene.environmentTexture = environmentTexture;
  113930. };
  113931. /**
  113932. * Setup the background according to the specified options.
  113933. */
  113934. EnvironmentHelper.prototype._setupBackground = function () {
  113935. if (!this._rootMesh) {
  113936. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  113937. }
  113938. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  113939. var sceneSize = this._getSceneSize();
  113940. if (this._options.createGround) {
  113941. this._setupGround(sceneSize);
  113942. this._setupGroundMaterial();
  113943. this._setupGroundDiffuseTexture();
  113944. if (this._options.enableGroundMirror) {
  113945. this._setupGroundMirrorTexture(sceneSize);
  113946. }
  113947. this._setupMirrorInGroundMaterial();
  113948. }
  113949. if (this._options.createSkybox) {
  113950. this._setupSkybox(sceneSize);
  113951. this._setupSkyboxMaterial();
  113952. this._setupSkyboxReflectionTexture();
  113953. }
  113954. this._rootMesh.position.x = sceneSize.rootPosition.x;
  113955. this._rootMesh.position.z = sceneSize.rootPosition.z;
  113956. this._rootMesh.position.y = sceneSize.rootPosition.y;
  113957. };
  113958. /**
  113959. * Get the scene sizes according to the setup.
  113960. */
  113961. EnvironmentHelper.prototype._getSceneSize = function () {
  113962. var _this = this;
  113963. var groundSize = this._options.groundSize;
  113964. var skyboxSize = this._options.skyboxSize;
  113965. var rootPosition = this._options.rootPosition;
  113966. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  113967. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  113968. }
  113969. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  113970. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  113971. });
  113972. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  113973. if (this._options.sizeAuto) {
  113974. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  113975. this._scene.activeCamera.upperRadiusLimit) {
  113976. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  113977. skyboxSize = groundSize;
  113978. }
  113979. var sceneDiagonalLenght = sceneDiagonal.length();
  113980. if (sceneDiagonalLenght > groundSize) {
  113981. groundSize = sceneDiagonalLenght * 2;
  113982. skyboxSize = groundSize;
  113983. }
  113984. // 10 % bigger.
  113985. groundSize *= 1.1;
  113986. skyboxSize *= 1.5;
  113987. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  113988. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  113989. }
  113990. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  113991. };
  113992. /**
  113993. * Setup the ground according to the specified options.
  113994. */
  113995. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  113996. var _this = this;
  113997. if (!this._ground || this._ground.isDisposed()) {
  113998. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  113999. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  114000. this._ground.parent = this._rootMesh;
  114001. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  114002. }
  114003. this._ground.receiveShadows = this._options.enableGroundShadow;
  114004. };
  114005. /**
  114006. * Setup the ground material according to the specified options.
  114007. */
  114008. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  114009. if (!this._groundMaterial) {
  114010. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  114011. }
  114012. this._groundMaterial.alpha = this._options.groundOpacity;
  114013. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  114014. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  114015. this._groundMaterial.primaryColor = this._options.groundColor;
  114016. this._groundMaterial.useRGBColor = false;
  114017. this._groundMaterial.enableNoise = true;
  114018. if (this._ground) {
  114019. this._ground.material = this._groundMaterial;
  114020. }
  114021. };
  114022. /**
  114023. * Setup the ground diffuse texture according to the specified options.
  114024. */
  114025. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  114026. if (!this._groundMaterial) {
  114027. return;
  114028. }
  114029. if (this._groundTexture) {
  114030. return;
  114031. }
  114032. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  114033. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  114034. return;
  114035. }
  114036. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  114037. diffuseTexture.gammaSpace = false;
  114038. diffuseTexture.hasAlpha = true;
  114039. this._groundMaterial.diffuseTexture = diffuseTexture;
  114040. };
  114041. /**
  114042. * Setup the ground mirror texture according to the specified options.
  114043. */
  114044. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  114045. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114046. if (!this._groundMirror) {
  114047. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  114048. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  114049. this._groundMirror.anisotropicFilteringLevel = 1;
  114050. this._groundMirror.wrapU = wrapping;
  114051. this._groundMirror.wrapV = wrapping;
  114052. this._groundMirror.gammaSpace = false;
  114053. if (this._groundMirror.renderList) {
  114054. for (var i = 0; i < this._scene.meshes.length; i++) {
  114055. var mesh = this._scene.meshes[i];
  114056. if (mesh !== this._ground &&
  114057. mesh !== this._skybox &&
  114058. mesh !== this._rootMesh) {
  114059. this._groundMirror.renderList.push(mesh);
  114060. }
  114061. }
  114062. }
  114063. }
  114064. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  114065. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  114066. };
  114067. /**
  114068. * Setup the ground to receive the mirror texture.
  114069. */
  114070. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  114071. if (this._groundMaterial) {
  114072. this._groundMaterial.reflectionTexture = this._groundMirror;
  114073. this._groundMaterial.reflectionFresnel = true;
  114074. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  114075. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  114076. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  114077. }
  114078. };
  114079. /**
  114080. * Setup the skybox according to the specified options.
  114081. */
  114082. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  114083. var _this = this;
  114084. if (!this._skybox || this._skybox.isDisposed()) {
  114085. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  114086. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  114087. }
  114088. this._skybox.parent = this._rootMesh;
  114089. };
  114090. /**
  114091. * Setup the skybox material according to the specified options.
  114092. */
  114093. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  114094. if (!this._skybox) {
  114095. return;
  114096. }
  114097. if (!this._skyboxMaterial) {
  114098. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  114099. }
  114100. this._skyboxMaterial.useRGBColor = false;
  114101. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  114102. this._skyboxMaterial.enableNoise = true;
  114103. this._skybox.material = this._skyboxMaterial;
  114104. };
  114105. /**
  114106. * Setup the skybox reflection texture according to the specified options.
  114107. */
  114108. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  114109. if (!this._skyboxMaterial) {
  114110. return;
  114111. }
  114112. if (this._skyboxTexture) {
  114113. return;
  114114. }
  114115. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  114116. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  114117. return;
  114118. }
  114119. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  114120. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  114121. this._skyboxTexture.gammaSpace = false;
  114122. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  114123. };
  114124. /**
  114125. * Dispose all the elements created by the Helper.
  114126. */
  114127. EnvironmentHelper.prototype.dispose = function () {
  114128. if (this._groundMaterial) {
  114129. this._groundMaterial.dispose(true, true);
  114130. }
  114131. if (this._skyboxMaterial) {
  114132. this._skyboxMaterial.dispose(true, true);
  114133. }
  114134. this._rootMesh.dispose(false);
  114135. };
  114136. /**
  114137. * Default ground texture URL.
  114138. */
  114139. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  114140. /**
  114141. * Default skybox texture URL.
  114142. */
  114143. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  114144. /**
  114145. * Default environment texture URL.
  114146. */
  114147. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  114148. return EnvironmentHelper;
  114149. }());
  114150. BABYLON.EnvironmentHelper = EnvironmentHelper;
  114151. })(BABYLON || (BABYLON = {}));
  114152. //# sourceMappingURL=babylon.environmentHelper.js.map
  114153. var BABYLON;
  114154. (function (BABYLON) {
  114155. /** Internal class used to store shapes for emitters */
  114156. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  114157. function ParticleSystemSetEmitterCreationOptions() {
  114158. }
  114159. return ParticleSystemSetEmitterCreationOptions;
  114160. }());
  114161. /**
  114162. * Represents a set of particle systems working together to create a specific effect
  114163. */
  114164. var ParticleSystemSet = /** @class */ (function () {
  114165. function ParticleSystemSet() {
  114166. /**
  114167. * Gets the particle system list
  114168. */
  114169. this.systems = new Array();
  114170. }
  114171. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  114172. /**
  114173. * Gets the emitter node used with this set
  114174. */
  114175. get: function () {
  114176. return this._emitterNode;
  114177. },
  114178. enumerable: true,
  114179. configurable: true
  114180. });
  114181. /**
  114182. * Creates a new emitter mesh as a sphere
  114183. * @param options defines the options used to create the sphere
  114184. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  114185. * @param scene defines the hosting scene
  114186. */
  114187. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  114188. if (this._emitterNode) {
  114189. this._emitterNode.dispose();
  114190. }
  114191. this._emitterCreationOptions = {
  114192. kind: "Sphere",
  114193. options: options,
  114194. renderingGroupId: renderingGroupId
  114195. };
  114196. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  114197. emitterMesh.renderingGroupId = renderingGroupId;
  114198. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  114199. material.emissiveColor = options.color;
  114200. emitterMesh.material = material;
  114201. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114202. var system = _a[_i];
  114203. system.emitter = emitterMesh;
  114204. }
  114205. this._emitterNode = emitterMesh;
  114206. };
  114207. /**
  114208. * Starts all particle systems of the set
  114209. * @param emitter defines an optional mesh to use as emitter for the particle systems
  114210. */
  114211. ParticleSystemSet.prototype.start = function (emitter) {
  114212. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114213. var system = _a[_i];
  114214. if (emitter) {
  114215. system.emitter = emitter;
  114216. }
  114217. system.start();
  114218. }
  114219. };
  114220. /**
  114221. * Release all associated resources
  114222. */
  114223. ParticleSystemSet.prototype.dispose = function () {
  114224. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114225. var system = _a[_i];
  114226. system.dispose();
  114227. }
  114228. this.systems = [];
  114229. if (this._emitterNode) {
  114230. this._emitterNode.dispose();
  114231. this._emitterNode = null;
  114232. }
  114233. };
  114234. /**
  114235. * Serialize the set into a JSON compatible object
  114236. * @returns a JSON compatible representation of the set
  114237. */
  114238. ParticleSystemSet.prototype.serialize = function () {
  114239. var result = {};
  114240. result.systems = [];
  114241. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114242. var system = _a[_i];
  114243. result.systems.push(system.serialize());
  114244. }
  114245. if (this._emitterNode) {
  114246. result.emitter = this._emitterCreationOptions;
  114247. }
  114248. return result;
  114249. };
  114250. /**
  114251. * Parse a new ParticleSystemSet from a serialized source
  114252. * @param data defines a JSON compatible representation of the set
  114253. * @param scene defines the hosting scene
  114254. * @param gpu defines if we want GPU particles or CPU particles
  114255. * @returns a new ParticleSystemSet
  114256. */
  114257. ParticleSystemSet.Parse = function (data, scene, gpu) {
  114258. if (gpu === void 0) { gpu = false; }
  114259. var result = new ParticleSystemSet();
  114260. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  114261. scene = scene || BABYLON.Engine.LastCreatedScene;
  114262. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  114263. var system = _a[_i];
  114264. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  114265. }
  114266. if (data.emitter) {
  114267. var options = data.emitter.options;
  114268. switch (data.emitter.kind) {
  114269. case "Sphere":
  114270. result.setEmitterAsSphere({
  114271. diameter: options.diameter,
  114272. segments: options.segments,
  114273. color: BABYLON.Color3.FromArray(options.color)
  114274. }, data.emitter.renderingGroupId, scene);
  114275. break;
  114276. }
  114277. }
  114278. return result;
  114279. };
  114280. return ParticleSystemSet;
  114281. }());
  114282. BABYLON.ParticleSystemSet = ParticleSystemSet;
  114283. })(BABYLON || (BABYLON = {}));
  114284. //# sourceMappingURL=babylon.particleSystemSet.js.map
  114285. var BABYLON;
  114286. (function (BABYLON) {
  114287. /**
  114288. * This class is made for on one-liner static method to help creating particle system set.
  114289. */
  114290. var ParticleHelper = /** @class */ (function () {
  114291. function ParticleHelper() {
  114292. }
  114293. /**
  114294. * Create a default particle system that you can tweak
  114295. * @param emitter defines the emitter to use
  114296. * @param capacity defines the system capacity (default is 500 particles)
  114297. * @param scene defines the hosting scene
  114298. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  114299. * @returns the new Particle system
  114300. */
  114301. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  114302. if (capacity === void 0) { capacity = 500; }
  114303. if (useGPU === void 0) { useGPU = false; }
  114304. var system;
  114305. if (useGPU) {
  114306. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  114307. }
  114308. else {
  114309. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  114310. }
  114311. system.emitter = emitter;
  114312. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  114313. system.createConeEmitter(0.1, Math.PI / 4);
  114314. // Particle color
  114315. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  114316. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  114317. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  114318. // Particle Size
  114319. system.minSize = 0.1;
  114320. system.maxSize = 0.1;
  114321. // Emission speed
  114322. system.minEmitPower = 2;
  114323. system.maxEmitPower = 2;
  114324. // Update speed
  114325. system.updateSpeed = 1 / 60;
  114326. system.emitRate = 30;
  114327. return system;
  114328. };
  114329. /**
  114330. * This is the main static method (one-liner) of this helper to create different particle systems
  114331. * @param type This string represents the type to the particle system to create
  114332. * @param scene The scene where the particle system should live
  114333. * @param gpu If the system will use gpu
  114334. * @returns the ParticleSystemSet created
  114335. */
  114336. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  114337. if (gpu === void 0) { gpu = false; }
  114338. if (!scene) {
  114339. scene = BABYLON.Engine.LastCreatedScene;
  114340. ;
  114341. }
  114342. var token = {};
  114343. scene._addPendingData(token);
  114344. return new Promise(function (resolve, reject) {
  114345. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  114346. scene._removePendingData(token);
  114347. return reject("Particle system with GPU is not supported.");
  114348. }
  114349. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  114350. scene._removePendingData(token);
  114351. var newData = JSON.parse(data.toString());
  114352. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  114353. }, undefined, undefined, undefined, function (req, exception) {
  114354. scene._removePendingData(token);
  114355. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  114356. });
  114357. });
  114358. };
  114359. /**
  114360. * Static function used to export a particle system to a ParticleSystemSet variable.
  114361. * Please note that the emitter shape is not exported
  114362. * @param systems defines the particle systems to export
  114363. * @returns the created particle system set
  114364. */
  114365. ParticleHelper.ExportSet = function (systems) {
  114366. var set = new BABYLON.ParticleSystemSet();
  114367. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  114368. var system = systems_1[_i];
  114369. set.systems.push(system);
  114370. }
  114371. return set;
  114372. };
  114373. /**
  114374. * Gets or sets base Assets URL
  114375. */
  114376. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  114377. return ParticleHelper;
  114378. }());
  114379. BABYLON.ParticleHelper = ParticleHelper;
  114380. })(BABYLON || (BABYLON = {}));
  114381. //# sourceMappingURL=babylon.particleHelper.js.map
  114382. var BABYLON;
  114383. (function (BABYLON) {
  114384. /**
  114385. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  114386. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  114387. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  114388. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  114389. */
  114390. var VideoDome = /** @class */ (function (_super) {
  114391. __extends(VideoDome, _super);
  114392. /**
  114393. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  114394. * @param name Element's name, child elements will append suffixes for their own names.
  114395. * @param urlsOrVideo defines the url(s) or the video element to use
  114396. * @param options An object containing optional or exposed sub element properties
  114397. */
  114398. function VideoDome(name, urlsOrVideo, options, scene) {
  114399. var _this = _super.call(this, name, scene) || this;
  114400. _this._useDirectMapping = false;
  114401. // set defaults and manage values
  114402. name = name || "videoDome";
  114403. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  114404. options.clickToPlay = Boolean(options.clickToPlay);
  114405. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  114406. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  114407. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  114408. if (options.useDirectMapping === undefined) {
  114409. _this._useDirectMapping = true;
  114410. }
  114411. else {
  114412. _this._useDirectMapping = options.useDirectMapping;
  114413. }
  114414. _this._setReady(false);
  114415. // create
  114416. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  114417. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  114418. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  114419. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  114420. texture.onLoadObservable.addOnce(function () {
  114421. _this._setReady(true);
  114422. });
  114423. // configure material
  114424. material.useEquirectangularFOV = true;
  114425. material.fovMultiplier = 1.0;
  114426. material.opacityFresnel = false;
  114427. if (_this._useDirectMapping) {
  114428. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114429. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114430. material.diffuseTexture = texture;
  114431. }
  114432. else {
  114433. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  114434. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114435. material.reflectionTexture = texture;
  114436. }
  114437. // configure mesh
  114438. _this._mesh.material = material;
  114439. _this._mesh.parent = _this;
  114440. // optional configuration
  114441. if (options.clickToPlay) {
  114442. scene.onPointerUp = function () {
  114443. _this._videoTexture.video.play();
  114444. };
  114445. }
  114446. return _this;
  114447. }
  114448. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  114449. /**
  114450. * Gets the video texture being displayed on the sphere
  114451. */
  114452. get: function () {
  114453. return this._videoTexture;
  114454. },
  114455. enumerable: true,
  114456. configurable: true
  114457. });
  114458. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  114459. /**
  114460. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114461. * Also see the options.resolution property.
  114462. */
  114463. get: function () {
  114464. return this._material.fovMultiplier;
  114465. },
  114466. set: function (value) {
  114467. this._material.fovMultiplier = value;
  114468. },
  114469. enumerable: true,
  114470. configurable: true
  114471. });
  114472. /**
  114473. * Releases resources associated with this node.
  114474. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  114475. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  114476. */
  114477. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  114478. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  114479. this._videoTexture.dispose();
  114480. this._mesh.dispose();
  114481. this._material.dispose();
  114482. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  114483. };
  114484. return VideoDome;
  114485. }(BABYLON.TransformNode));
  114486. BABYLON.VideoDome = VideoDome;
  114487. })(BABYLON || (BABYLON = {}));
  114488. //# sourceMappingURL=babylon.videoDome.js.map
  114489. var BABYLON;
  114490. (function (BABYLON) {
  114491. /**
  114492. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  114493. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  114494. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  114495. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  114496. */
  114497. var PhotoDome = /** @class */ (function (_super) {
  114498. __extends(PhotoDome, _super);
  114499. /**
  114500. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  114501. * @param name Element's name, child elements will append suffixes for their own names.
  114502. * @param urlsOfPhoto defines the url of the photo to display
  114503. * @param options defines an object containing optional or exposed sub element properties
  114504. * @param onError defines a callback called when an error occured while loading the texture
  114505. */
  114506. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  114507. if (onError === void 0) { onError = null; }
  114508. var _this = _super.call(this, name, scene) || this;
  114509. _this._useDirectMapping = false;
  114510. /**
  114511. * Observable raised when an error occured while loading the 360 image
  114512. */
  114513. _this.onLoadErrorObservable = new BABYLON.Observable();
  114514. // set defaults and manage values
  114515. name = name || "photoDome";
  114516. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  114517. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  114518. if (options.useDirectMapping === undefined) {
  114519. _this._useDirectMapping = true;
  114520. }
  114521. else {
  114522. _this._useDirectMapping = options.useDirectMapping;
  114523. }
  114524. _this._setReady(false);
  114525. // create
  114526. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  114527. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  114528. // configure material
  114529. material.opacityFresnel = false;
  114530. material.useEquirectangularFOV = true;
  114531. material.fovMultiplier = 1.0;
  114532. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  114533. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  114534. if (onError) {
  114535. onError(message, exception);
  114536. }
  114537. });
  114538. _this.photoTexture.onLoadObservable.addOnce(function () {
  114539. _this._setReady(true);
  114540. });
  114541. // configure mesh
  114542. _this._mesh.material = material;
  114543. _this._mesh.parent = _this;
  114544. return _this;
  114545. }
  114546. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  114547. /**
  114548. * Gets or sets the texture being displayed on the sphere
  114549. */
  114550. get: function () {
  114551. return this._photoTexture;
  114552. },
  114553. set: function (value) {
  114554. if (this._photoTexture === value) {
  114555. return;
  114556. }
  114557. this._photoTexture = value;
  114558. if (this._useDirectMapping) {
  114559. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114560. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114561. this._material.diffuseTexture = this._photoTexture;
  114562. }
  114563. else {
  114564. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  114565. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114566. this._material.reflectionTexture = this._photoTexture;
  114567. }
  114568. },
  114569. enumerable: true,
  114570. configurable: true
  114571. });
  114572. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  114573. /**
  114574. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114575. * Also see the options.resolution property.
  114576. */
  114577. get: function () {
  114578. return this._material.fovMultiplier;
  114579. },
  114580. set: function (value) {
  114581. this._material.fovMultiplier = value;
  114582. },
  114583. enumerable: true,
  114584. configurable: true
  114585. });
  114586. /**
  114587. * Releases resources associated with this node.
  114588. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  114589. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  114590. */
  114591. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  114592. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  114593. this._photoTexture.dispose();
  114594. this._mesh.dispose();
  114595. this._material.dispose();
  114596. this.onLoadErrorObservable.clear();
  114597. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  114598. };
  114599. return PhotoDome;
  114600. }(BABYLON.TransformNode));
  114601. BABYLON.PhotoDome = PhotoDome;
  114602. })(BABYLON || (BABYLON = {}));
  114603. //# sourceMappingURL=babylon.photoDome.js.map
  114604. var BABYLON;
  114605. (function (BABYLON) {
  114606. /** @hidden */
  114607. var _OcclusionDataStorage = /** @class */ (function () {
  114608. function _OcclusionDataStorage() {
  114609. /** @hidden */
  114610. this.occlusionInternalRetryCounter = 0;
  114611. /** @hidden */
  114612. this.isOcclusionQueryInProgress = false;
  114613. /** @hidden */
  114614. this.isOccluded = false;
  114615. /** @hidden */
  114616. this.occlusionRetryCount = -1;
  114617. /** @hidden */
  114618. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  114619. /** @hidden */
  114620. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  114621. }
  114622. return _OcclusionDataStorage;
  114623. }());
  114624. BABYLON.Engine.prototype.createQuery = function () {
  114625. return this._gl.createQuery();
  114626. };
  114627. BABYLON.Engine.prototype.deleteQuery = function (query) {
  114628. this._gl.deleteQuery(query);
  114629. return this;
  114630. };
  114631. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  114632. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  114633. };
  114634. BABYLON.Engine.prototype.getQueryResult = function (query) {
  114635. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  114636. };
  114637. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  114638. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  114639. this._gl.beginQuery(glAlgorithm, query);
  114640. return this;
  114641. };
  114642. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  114643. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  114644. this._gl.endQuery(glAlgorithm);
  114645. return this;
  114646. };
  114647. BABYLON.Engine.prototype._createTimeQuery = function () {
  114648. var timerQuery = this.getCaps().timerQuery;
  114649. if (timerQuery.createQueryEXT) {
  114650. return timerQuery.createQueryEXT();
  114651. }
  114652. return this.createQuery();
  114653. };
  114654. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  114655. var timerQuery = this.getCaps().timerQuery;
  114656. if (timerQuery.deleteQueryEXT) {
  114657. timerQuery.deleteQueryEXT(query);
  114658. return;
  114659. }
  114660. this.deleteQuery(query);
  114661. };
  114662. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  114663. var timerQuery = this.getCaps().timerQuery;
  114664. if (timerQuery.getQueryObjectEXT) {
  114665. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  114666. }
  114667. return this.getQueryResult(query);
  114668. };
  114669. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  114670. var timerQuery = this.getCaps().timerQuery;
  114671. if (timerQuery.getQueryObjectEXT) {
  114672. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  114673. }
  114674. return this.isQueryResultAvailable(query);
  114675. };
  114676. BABYLON.Engine.prototype.startTimeQuery = function () {
  114677. var caps = this.getCaps();
  114678. var timerQuery = caps.timerQuery;
  114679. if (!timerQuery) {
  114680. return null;
  114681. }
  114682. var token = new BABYLON._TimeToken();
  114683. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  114684. if (caps.canUseTimestampForTimerQuery) {
  114685. token._startTimeQuery = this._createTimeQuery();
  114686. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  114687. }
  114688. else {
  114689. if (this._currentNonTimestampToken) {
  114690. return this._currentNonTimestampToken;
  114691. }
  114692. token._timeElapsedQuery = this._createTimeQuery();
  114693. if (timerQuery.beginQueryEXT) {
  114694. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  114695. }
  114696. else {
  114697. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  114698. }
  114699. this._currentNonTimestampToken = token;
  114700. }
  114701. return token;
  114702. };
  114703. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  114704. var caps = this.getCaps();
  114705. var timerQuery = caps.timerQuery;
  114706. if (!timerQuery || !token) {
  114707. return -1;
  114708. }
  114709. if (caps.canUseTimestampForTimerQuery) {
  114710. if (!token._startTimeQuery) {
  114711. return -1;
  114712. }
  114713. if (!token._endTimeQuery) {
  114714. token._endTimeQuery = this._createTimeQuery();
  114715. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  114716. }
  114717. }
  114718. else if (!token._timeElapsedQueryEnded) {
  114719. if (!token._timeElapsedQuery) {
  114720. return -1;
  114721. }
  114722. if (timerQuery.endQueryEXT) {
  114723. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  114724. }
  114725. else {
  114726. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  114727. }
  114728. token._timeElapsedQueryEnded = true;
  114729. }
  114730. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  114731. var available = false;
  114732. if (token._endTimeQuery) {
  114733. available = this._getTimeQueryAvailability(token._endTimeQuery);
  114734. }
  114735. else if (token._timeElapsedQuery) {
  114736. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  114737. }
  114738. if (available && !disjoint) {
  114739. var result = 0;
  114740. if (caps.canUseTimestampForTimerQuery) {
  114741. if (!token._startTimeQuery || !token._endTimeQuery) {
  114742. return -1;
  114743. }
  114744. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  114745. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  114746. result = timeEnd - timeStart;
  114747. this._deleteTimeQuery(token._startTimeQuery);
  114748. this._deleteTimeQuery(token._endTimeQuery);
  114749. token._startTimeQuery = null;
  114750. token._endTimeQuery = null;
  114751. }
  114752. else {
  114753. if (!token._timeElapsedQuery) {
  114754. return -1;
  114755. }
  114756. result = this._getTimeQueryResult(token._timeElapsedQuery);
  114757. this._deleteTimeQuery(token._timeElapsedQuery);
  114758. token._timeElapsedQuery = null;
  114759. token._timeElapsedQueryEnded = false;
  114760. this._currentNonTimestampToken = null;
  114761. }
  114762. return result;
  114763. }
  114764. return -1;
  114765. };
  114766. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  114767. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  114768. };
  114769. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  114770. get: function () {
  114771. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  114772. },
  114773. enumerable: false,
  114774. configurable: true
  114775. });
  114776. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  114777. get: function () {
  114778. if (!this.__occlusionDataStorage) {
  114779. this.__occlusionDataStorage = new _OcclusionDataStorage();
  114780. }
  114781. return this.__occlusionDataStorage;
  114782. },
  114783. enumerable: false,
  114784. configurable: true
  114785. });
  114786. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  114787. get: function () {
  114788. return this._occlusionDataStorage.isOccluded;
  114789. },
  114790. set: function (value) {
  114791. this._occlusionDataStorage.isOccluded = value;
  114792. },
  114793. enumerable: true,
  114794. configurable: true
  114795. });
  114796. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  114797. get: function () {
  114798. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  114799. },
  114800. set: function (value) {
  114801. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  114802. },
  114803. enumerable: true,
  114804. configurable: true
  114805. });
  114806. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  114807. get: function () {
  114808. return this._occlusionDataStorage.occlusionType;
  114809. },
  114810. set: function (value) {
  114811. this._occlusionDataStorage.occlusionType = value;
  114812. },
  114813. enumerable: true,
  114814. configurable: true
  114815. });
  114816. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  114817. get: function () {
  114818. return this._occlusionDataStorage.occlusionRetryCount;
  114819. },
  114820. set: function (value) {
  114821. this._occlusionDataStorage.occlusionRetryCount = value;
  114822. },
  114823. enumerable: true,
  114824. configurable: true
  114825. });
  114826. // We also need to update AbstractMesh as there is a portion of the code there
  114827. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  114828. var dataStorage = this._occlusionDataStorage;
  114829. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  114830. dataStorage.isOccluded = false;
  114831. return false;
  114832. }
  114833. var engine = this.getEngine();
  114834. if (engine.webGLVersion < 2) {
  114835. dataStorage.isOccluded = false;
  114836. return false;
  114837. }
  114838. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  114839. dataStorage.isOccluded = false;
  114840. return false;
  114841. }
  114842. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  114843. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  114844. if (isOcclusionQueryAvailable) {
  114845. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  114846. dataStorage.isOcclusionQueryInProgress = false;
  114847. dataStorage.occlusionInternalRetryCounter = 0;
  114848. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  114849. }
  114850. else {
  114851. dataStorage.occlusionInternalRetryCounter++;
  114852. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  114853. dataStorage.isOcclusionQueryInProgress = false;
  114854. dataStorage.occlusionInternalRetryCounter = 0;
  114855. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  114856. // if strict continue the last state of the object.
  114857. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  114858. }
  114859. else {
  114860. return false;
  114861. }
  114862. }
  114863. }
  114864. var scene = this.getScene();
  114865. if (scene.getBoundingBoxRenderer) {
  114866. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  114867. if (!this._occlusionQuery) {
  114868. this._occlusionQuery = engine.createQuery();
  114869. }
  114870. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  114871. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  114872. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  114873. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  114874. }
  114875. return dataStorage.isOccluded;
  114876. };
  114877. })(BABYLON || (BABYLON = {}));
  114878. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  114879. var BABYLON;
  114880. (function (BABYLON) {
  114881. /**
  114882. * Class used to generate noise procedural textures
  114883. */
  114884. var NoiseProceduralTexture = /** @class */ (function (_super) {
  114885. __extends(NoiseProceduralTexture, _super);
  114886. /**
  114887. * Creates a new NoiseProceduralTexture
  114888. * @param name defines the name fo the texture
  114889. * @param size defines the size of the texture (default is 256)
  114890. * @param scene defines the hosting scene
  114891. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  114892. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  114893. */
  114894. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  114895. if (size === void 0) { size = 256; }
  114896. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  114897. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  114898. _this._time = 0;
  114899. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  114900. _this.brightness = 0.2;
  114901. /** Defines the number of octaves to process */
  114902. _this.octaves = 3;
  114903. /** Defines the level of persistence (0.8 by default) */
  114904. _this.persistence = 0.8;
  114905. /** Gets or sets animation speed factor (default is 1) */
  114906. _this.animationSpeedFactor = 1;
  114907. _this._updateShaderUniforms();
  114908. return _this;
  114909. }
  114910. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  114911. var scene = this.getScene();
  114912. if (!scene) {
  114913. return;
  114914. }
  114915. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  114916. this.setFloat("brightness", this.brightness);
  114917. this.setFloat("persistence", this.persistence);
  114918. this.setFloat("timeScale", this._time);
  114919. };
  114920. NoiseProceduralTexture.prototype._getDefines = function () {
  114921. return "#define OCTAVES " + (this.octaves | 0);
  114922. };
  114923. /** Generate the current state of the procedural texture */
  114924. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  114925. this._updateShaderUniforms();
  114926. _super.prototype.render.call(this, useCameraPostProcess);
  114927. };
  114928. /**
  114929. * Serializes this noise procedural texture
  114930. * @returns a serialized noise procedural texture object
  114931. */
  114932. NoiseProceduralTexture.prototype.serialize = function () {
  114933. var serializationObject = {};
  114934. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  114935. serializationObject.brightness = this.brightness;
  114936. serializationObject.octaves = this.octaves;
  114937. serializationObject.persistence = this.persistence;
  114938. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  114939. serializationObject.size = this.getSize().width;
  114940. serializationObject.generateMipMaps = this._generateMipMaps;
  114941. return serializationObject;
  114942. };
  114943. /**
  114944. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  114945. * @param parsedTexture defines parsed texture data
  114946. * @param scene defines the current scene
  114947. * @param rootUrl defines the root URL containing noise procedural texture information
  114948. * @returns a parsed NoiseProceduralTexture
  114949. */
  114950. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  114951. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  114952. texture.brightness = parsedTexture.brightness;
  114953. texture.octaves = parsedTexture.octaves;
  114954. texture.persistence = parsedTexture.persistence;
  114955. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  114956. return texture;
  114957. };
  114958. return NoiseProceduralTexture;
  114959. }(BABYLON.ProceduralTexture));
  114960. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  114961. })(BABYLON || (BABYLON = {}));
  114962. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  114963. var __assign = (this && this.__assign) || function () {
  114964. __assign = Object.assign || function(t) {
  114965. for (var s, i = 1, n = arguments.length; i < n; i++) {
  114966. s = arguments[i];
  114967. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  114968. t[p] = s[p];
  114969. }
  114970. return t;
  114971. };
  114972. return __assign.apply(this, arguments);
  114973. };
  114974. var BABYLON;
  114975. (function (BABYLON) {
  114976. /**
  114977. * This can helps recording videos from BabylonJS.
  114978. * This is based on the available WebRTC functionalities of the browser.
  114979. *
  114980. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  114981. */
  114982. var VideoRecorder = /** @class */ (function () {
  114983. /**
  114984. * Create a new VideoCapture object which can help converting what you see in Babylon to
  114985. * a video file.
  114986. * @param engine Defines the BabylonJS Engine you wish to record
  114987. * @param options Defines options that can be used to customized the capture
  114988. */
  114989. function VideoRecorder(engine, options) {
  114990. if (options === void 0) { options = null; }
  114991. if (!VideoRecorder.IsSupported(engine)) {
  114992. throw "Your browser does not support recording so far.";
  114993. }
  114994. var canvas = engine.getRenderingCanvas();
  114995. if (!canvas) {
  114996. throw "The babylon engine must have a canvas to be recorded";
  114997. }
  114998. this._canvas = canvas;
  114999. this._canvas.isRecording = false;
  115000. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  115001. var stream = this._canvas.captureStream(this._options.fps);
  115002. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  115003. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  115004. this._mediaRecorder.onerror = this._handleError.bind(this);
  115005. this._mediaRecorder.onstop = this._handleStop.bind(this);
  115006. }
  115007. /**
  115008. * Returns wehther or not the VideoRecorder is available in your browser.
  115009. * @param engine Defines the Babylon Engine to check the support for
  115010. * @returns true if supported otherwise false
  115011. */
  115012. VideoRecorder.IsSupported = function (engine) {
  115013. var canvas = engine.getRenderingCanvas();
  115014. return (!!canvas && typeof canvas.captureStream === "function");
  115015. };
  115016. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  115017. /**
  115018. * True wether a recording is already in progress.
  115019. */
  115020. get: function () {
  115021. return !!this._canvas && this._canvas.isRecording;
  115022. },
  115023. enumerable: true,
  115024. configurable: true
  115025. });
  115026. /**
  115027. * Stops the current recording before the default capture timeout passed in the startRecording
  115028. * functions.
  115029. */
  115030. VideoRecorder.prototype.stopRecording = function () {
  115031. if (!this._canvas || !this._mediaRecorder) {
  115032. return;
  115033. }
  115034. if (!this.isRecording) {
  115035. return;
  115036. }
  115037. this._canvas.isRecording = false;
  115038. this._mediaRecorder.stop();
  115039. };
  115040. /**
  115041. * Starts recording the canvas for a max duration specified in parameters.
  115042. * @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.
  115043. * @param maxDuration Defines the maximum recording time in seconds.
  115044. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  115045. * @return a promise callback at the end of the recording with the video data in Blob.
  115046. */
  115047. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  115048. var _this = this;
  115049. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  115050. if (maxDuration === void 0) { maxDuration = 7; }
  115051. if (!this._canvas || !this._mediaRecorder) {
  115052. throw "Recorder has already been disposed";
  115053. }
  115054. if (this.isRecording) {
  115055. throw "Recording already in progress";
  115056. }
  115057. if (maxDuration > 0) {
  115058. setTimeout(function () {
  115059. _this.stopRecording();
  115060. }, maxDuration * 1000);
  115061. }
  115062. this._fileName = fileName;
  115063. this._recordedChunks = [];
  115064. this._resolve = null;
  115065. this._reject = null;
  115066. this._canvas.isRecording = true;
  115067. this._mediaRecorder.start(this._options.recordChunckSize);
  115068. return new Promise(function (resolve, reject) {
  115069. _this._resolve = resolve;
  115070. _this._reject = reject;
  115071. });
  115072. };
  115073. /**
  115074. * Releases internal resources used during the recording.
  115075. */
  115076. VideoRecorder.prototype.dispose = function () {
  115077. this._canvas = null;
  115078. this._mediaRecorder = null;
  115079. this._recordedChunks = [];
  115080. this._fileName = null;
  115081. this._resolve = null;
  115082. this._reject = null;
  115083. };
  115084. VideoRecorder.prototype._handleDataAvailable = function (event) {
  115085. if (event.data.size > 0) {
  115086. this._recordedChunks.push(event.data);
  115087. }
  115088. };
  115089. VideoRecorder.prototype._handleError = function (event) {
  115090. this.stopRecording();
  115091. if (this._reject) {
  115092. this._reject(event.error);
  115093. }
  115094. else {
  115095. throw new event.error;
  115096. }
  115097. };
  115098. VideoRecorder.prototype._handleStop = function () {
  115099. this.stopRecording();
  115100. var superBuffer = new Blob(this._recordedChunks);
  115101. if (this._resolve) {
  115102. this._resolve(superBuffer);
  115103. }
  115104. window.URL.createObjectURL(superBuffer);
  115105. if (this._fileName) {
  115106. BABYLON.Tools.Download(superBuffer, this._fileName);
  115107. }
  115108. };
  115109. VideoRecorder._defaultOptions = {
  115110. mimeType: "video/webm",
  115111. fps: 25,
  115112. recordChunckSize: 3000
  115113. };
  115114. return VideoRecorder;
  115115. }());
  115116. BABYLON.VideoRecorder = VideoRecorder;
  115117. })(BABYLON || (BABYLON = {}));
  115118. //# sourceMappingURL=babylon.videoRecorder.js.map
  115119. var BABYLON;
  115120. (function (BABYLON) {
  115121. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  115122. if (replace === void 0) { replace = false; }
  115123. // Dispose existing light in replace mode.
  115124. if (replace) {
  115125. if (this.lights) {
  115126. for (var i = 0; i < this.lights.length; i++) {
  115127. this.lights[i].dispose();
  115128. }
  115129. }
  115130. }
  115131. // Light
  115132. if (this.lights.length === 0) {
  115133. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  115134. }
  115135. };
  115136. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  115137. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  115138. if (replace === void 0) { replace = false; }
  115139. if (attachCameraControls === void 0) { attachCameraControls = false; }
  115140. // Dispose existing camera in replace mode.
  115141. if (replace) {
  115142. if (this.activeCamera) {
  115143. this.activeCamera.dispose();
  115144. this.activeCamera = null;
  115145. }
  115146. }
  115147. // Camera
  115148. if (!this.activeCamera) {
  115149. var worldExtends = this.getWorldExtends();
  115150. var worldSize = worldExtends.max.subtract(worldExtends.min);
  115151. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  115152. var camera;
  115153. var radius = worldSize.length() * 1.5;
  115154. // empty scene scenario!
  115155. if (!isFinite(radius)) {
  115156. radius = 1;
  115157. worldCenter.copyFromFloats(0, 0, 0);
  115158. }
  115159. if (createArcRotateCamera) {
  115160. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  115161. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  115162. arcRotateCamera.wheelPrecision = 100 / radius;
  115163. camera = arcRotateCamera;
  115164. }
  115165. else {
  115166. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  115167. freeCamera.setTarget(worldCenter);
  115168. camera = freeCamera;
  115169. }
  115170. camera.minZ = radius * 0.01;
  115171. camera.maxZ = radius * 1000;
  115172. camera.speed = radius * 0.2;
  115173. this.activeCamera = camera;
  115174. var canvas = this.getEngine().getRenderingCanvas();
  115175. if (attachCameraControls && canvas) {
  115176. camera.attachControl(canvas);
  115177. }
  115178. }
  115179. };
  115180. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  115181. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  115182. if (replace === void 0) { replace = false; }
  115183. if (attachCameraControls === void 0) { attachCameraControls = false; }
  115184. this.createDefaultLight(replace);
  115185. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  115186. };
  115187. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  115188. if (pbr === void 0) { pbr = false; }
  115189. if (scale === void 0) { scale = 1000; }
  115190. if (blur === void 0) { blur = 0; }
  115191. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  115192. if (!environmentTexture) {
  115193. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  115194. return null;
  115195. }
  115196. if (setGlobalEnvTexture) {
  115197. if (environmentTexture) {
  115198. this.environmentTexture = environmentTexture;
  115199. }
  115200. }
  115201. // Skybox
  115202. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  115203. if (pbr) {
  115204. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  115205. hdrSkyboxMaterial.backFaceCulling = false;
  115206. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  115207. if (hdrSkyboxMaterial.reflectionTexture) {
  115208. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115209. }
  115210. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  115211. hdrSkyboxMaterial.disableLighting = true;
  115212. hdrSkyboxMaterial.twoSidedLighting = true;
  115213. hdrSkybox.infiniteDistance = true;
  115214. hdrSkybox.material = hdrSkyboxMaterial;
  115215. }
  115216. else {
  115217. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  115218. skyboxMaterial.backFaceCulling = false;
  115219. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  115220. if (skyboxMaterial.reflectionTexture) {
  115221. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115222. }
  115223. skyboxMaterial.disableLighting = true;
  115224. hdrSkybox.infiniteDistance = true;
  115225. hdrSkybox.material = skyboxMaterial;
  115226. }
  115227. return hdrSkybox;
  115228. };
  115229. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  115230. if (BABYLON.EnvironmentHelper) {
  115231. return new BABYLON.EnvironmentHelper(options, this);
  115232. }
  115233. return null;
  115234. };
  115235. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  115236. if (webVROptions === void 0) { webVROptions = {}; }
  115237. return new BABYLON.VRExperienceHelper(this, webVROptions);
  115238. };
  115239. })(BABYLON || (BABYLON = {}));
  115240. //# sourceMappingURL=babylon.sceneHelpers.js.map
  115241. 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\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\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(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"};
  115242. 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};"};